diff --git a/crates/recording/src/feeds/camera.rs b/crates/recording/src/feeds/camera.rs index 28d822b4bf0..d9417d61c1f 100644 --- a/crates/recording/src/feeds/camera.rs +++ b/crates/recording/src/feeds/camera.rs @@ -53,12 +53,93 @@ pub struct CameraFeed { state: State, senders: Vec>, ffmpeg_sender_count: Arc, - native_senders: Vec>, - native_sender_count: Arc, + native_senders: Vec>, + native_ingress: Arc, + native_fanout_full: u64, + native_fanout_log: DropLog, + ffmpeg_fanout_full: u64, + ffmpeg_fanout_log: DropLog, on_ready: Vec>, on_disconnect: Vec>, } +/// Shared between the camera feed and its capture callback, which runs on a +/// capture thread and must never wait for the feed. +#[derive(Debug, Default)] +pub struct NativeCameraIngress { + senders: std::sync::atomic::AtomicUsize, + mailbox_full: std::sync::atomic::AtomicU64, +} + +impl NativeCameraIngress { + /// Frames the capture callback could not hand to the feed because its + /// mailbox was full. Monotonic over the feed's lifetime. + pub fn mailbox_full(&self) -> u64 { + self.mailbox_full.load(std::sync::atomic::Ordering::Relaxed) + } + + pub fn record_mailbox_full(&self) { + self.mailbox_full + .fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } +} + +/// A fan-out target. Senders attached with a counter (recordings) count the +/// frames the feed could not deliver to them; previews attach without one. +struct CountedSender { + tx: flume::Sender, + dropped: Option>, +} + +trait FanoutTarget { + fn channel(&self) -> &flume::Sender; + fn record_drop(&self) {} +} + +impl FanoutTarget for flume::Sender { + fn channel(&self) -> &flume::Sender { + self + } +} + +impl FanoutTarget for CountedSender { + fn channel(&self) -> &flume::Sender { + &self.tx + } + + fn record_drop(&self) { + if let Some(dropped) = &self.dropped { + dropped.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } + } +} + +/// Rate limit for drop warnings: the first drop is reported at once, later +/// drops at most once per interval with the count since the last report, so +/// an isolated loss is never hidden and a sustained loss cannot flood the log. +#[derive(Debug, Default)] +pub(crate) struct DropLog { + last_report: Option, + unreported: u64, +} + +impl DropLog { + pub(crate) const INTERVAL: Duration = Duration::from_secs(5); + + pub(crate) fn record(&mut self, count: u64, now: std::time::Instant) -> Option { + self.unreported = self.unreported.saturating_add(count); + if self.unreported == 0 + || self + .last_report + .is_some_and(|last| now.duration_since(last) < Self::INTERVAL) + { + return None; + } + self.last_report = Some(now); + Some(std::mem::take(&mut self.unreported)) + } +} + enum State { Open(OpenState), Locked { @@ -210,7 +291,11 @@ impl Default for CameraFeed { senders: Vec::new(), ffmpeg_sender_count: Arc::new(std::sync::atomic::AtomicUsize::new(0)), native_senders: Vec::new(), - native_sender_count: Arc::new(std::sync::atomic::AtomicUsize::new(0)), + native_ingress: Arc::new(NativeCameraIngress::default()), + native_fanout_full: 0, + native_fanout_log: DropLog::default(), + ffmpeg_fanout_full: 0, + ffmpeg_fanout_log: DropLog::default(), on_ready: Vec::new(), on_disconnect: Vec::new(), } @@ -229,11 +314,16 @@ pub struct CameraFeedLock { actor: ActorRef, camera_info: cap_camera::CameraInfo, video_info: VideoInfo, + native_ingress: Arc, drop_tx: Option>, _token: Arc<()>, } impl CameraFeedLock { + pub fn native_ingress(&self) -> &Arc { + &self.native_ingress + } + pub fn camera_info(&self) -> &cap_camera::CameraInfo { &self.camera_info } @@ -301,6 +391,13 @@ pub struct AddSender(pub flume::Sender); pub struct AddNativeSender(pub flume::Sender); +/// Attaches a recording's native queue; every frame the feed cannot deliver +/// to it is added to the counter. +pub struct AddCountedNativeSender( + pub flume::Sender, + pub Arc, +); + pub struct RemoveSender(pub flume::Sender); pub struct RemoveNativeSender(pub flume::Sender); @@ -369,7 +466,7 @@ struct CameraSetupArgs { new_frame_recipient: Recipient, native_frame_recipient: Recipient, ffmpeg_sender_count: Arc, - native_sender_count: Arc, + native_ingress: Arc, flow: CameraSetupFlow, } @@ -432,7 +529,7 @@ fn spawn_camera_setup(args: CameraSetupArgs) -> (ReadyFuture, SyncSender<()>) { new_frame_recipient, native_frame_recipient, ffmpeg_sender_count, - native_sender_count, + native_ingress, flow, } = args; @@ -498,7 +595,7 @@ fn spawn_camera_setup(args: CameraSetupArgs) -> (ReadyFuture, SyncSender<()>) { new_frame_recipient, native_frame_recipient, ffmpeg_sender_count, - native_sender_count, + native_ingress, &done_rx_thread, ) .await; @@ -857,7 +954,7 @@ async fn setup_camera( recipient: Recipient, native_recipient: Recipient, ffmpeg_sender_count: Arc, - native_sender_count: Arc, + native_ingress: Arc, cancel_rx: &mpsc::Receiver<()>, ) -> Result { let camera = find_camera(id).ok_or(SetInputError::DeviceNotFound)?; @@ -882,7 +979,7 @@ async fn setup_camera( recipient.clone(), native_recipient.clone(), ffmpeg_sender_count.clone(), - native_sender_count.clone(), + native_ingress.clone(), ) .await; @@ -910,7 +1007,7 @@ async fn setup_camera( recipient, native_recipient, ffmpeg_sender_count, - native_sender_count, + native_ingress, ) .await .inspect(|_| { @@ -921,6 +1018,21 @@ async fn setup_camera( } } +/// The capture callback's hand-over to the feed: never waits for mailbox +/// capacity; a full mailbox loses the frame and counts it. +#[cfg(any(target_os = "macos", windows))] +fn hand_native_frame_to_feed( + recipient: &Recipient, + ingress: &NativeCameraIngress, + frame: NativeCameraFrame, +) { + if let Err(kameo::error::SendError::MailboxFull(_)) = + recipient.tell(NewNativeFrame(frame)).try_send() + { + ingress.record_mailbox_full(); + } +} + #[cfg(target_os = "macos")] async fn start_camera_capture_attempt( camera: &cap_camera::CameraInfo, @@ -929,7 +1041,7 @@ async fn start_camera_capture_attempt( recipient: Recipient, native_recipient: Recipient, ffmpeg_sender_count: Arc, - native_sender_count: Arc, + native_ingress: Arc, ) -> Result { let frame_rate = format.frame_rate().round().max(1.0) as u32; @@ -945,13 +1057,19 @@ async fn start_camera_capture_attempt( cidre::cm::Clock::convert_host_time_to_sys_units(frame.native().sample_buf().pts()), )); - if native_sender_count.load(std::sync::atomic::Ordering::Relaxed) > 0 { - let _ = native_recipient - .tell(NewNativeFrame(NativeCameraFrame { + if native_ingress + .senders + .load(std::sync::atomic::Ordering::Relaxed) + > 0 + { + hand_native_frame_to_feed( + &native_recipient, + &native_ingress, + NativeCameraFrame { sample_buf: frame.native().sample_buf().clone(), timestamp, - })) - .try_send(); + }, + ); } // Until the ready signal fires the first frame must still be @@ -1015,7 +1133,7 @@ async fn setup_camera( recipient: Recipient, native_recipient: Recipient, ffmpeg_sender_count: Arc, - native_sender_count: Arc, + native_ingress: Arc, _cancel_rx: &mpsc::Receiver<()>, ) -> Result { let camera = find_camera(id).ok_or(SetInputError::DeviceNotFound)?; @@ -1034,7 +1152,10 @@ async fn setup_camera( cap_timestamp::PerformanceCounterTimestamp::new(frame.native().perf_counter), ); - if native_sender_count.load(std::sync::atomic::Ordering::Relaxed) > 0 + if native_ingress + .senders + .load(std::sync::atomic::Ordering::Relaxed) + > 0 && let Ok(bytes) = frame.native().bytes() { use cap_mediafoundation_utils::IMFMediaBufferExt; @@ -1056,16 +1177,18 @@ async fn setup_camera( #[allow(clippy::arc_with_non_send_sync)] let buffer = std::sync::Arc::new(std::sync::Mutex::new(buffer)); - let _ = native_recipient - .tell(NewNativeFrame(NativeCameraFrame { + hand_native_frame_to_feed( + &native_recipient, + &native_ingress, + NativeCameraFrame { buffer, pixel_format: frame.native().pixel_format, width: frame.native().width as u32, height: frame.native().height as u32, is_bottom_up: frame.native().is_bottom_up, timestamp, - })) - .try_send(); + }, + ); } } } @@ -1131,7 +1254,7 @@ async fn setup_camera( recipient: Recipient, _native_recipient: Recipient, _ffmpeg_sender_count: Arc, - _native_sender_count: Arc, + _native_ingress: Arc, _cancel_rx: &mpsc::Receiver<()>, ) -> Result { let camera = find_camera(id).ok_or(SetInputError::DeviceNotFound)?; @@ -1267,7 +1390,7 @@ impl Message for CameraFeed { new_frame_recipient, native_frame_recipient, ffmpeg_sender_count: self.ffmpeg_sender_count.clone(), - native_sender_count: self.native_sender_count.clone(), + native_ingress: self.native_ingress.clone(), flow: CameraSetupFlow::Open, }); @@ -1295,7 +1418,7 @@ impl Message for CameraFeed { new_frame_recipient, native_frame_recipient, ffmpeg_sender_count: self.ffmpeg_sender_count.clone(), - native_sender_count: self.native_sender_count.clone(), + native_ingress: self.native_ingress.clone(), flow: CameraSetupFlow::Locked { lock_generation: self.lock_generation, }, @@ -1329,7 +1452,8 @@ impl Message for CameraFeed { self.ffmpeg_sender_count .store(0, std::sync::atomic::Ordering::Release); self.native_senders.clear(); - self.native_sender_count + self.native_ingress + .senders .store(0, std::sync::atomic::Ordering::Release); for cb in &self.on_disconnect { @@ -1359,31 +1483,53 @@ impl Message for CameraFeed { } } -impl Message for CameraFeed { - type Reply = (); - - async fn handle( +impl CameraFeed { + fn add_native_sender( &mut self, - msg: AddNativeSender, - _: &mut Context, - ) -> Self::Reply { + tx: flume::Sender, + dropped: Option>, + ) { if self .native_senders .iter() - .any(|sender| sender.same_channel(&msg.0)) + .any(|sender| sender.tx.same_channel(&tx)) { return; } debug!("CameraFeed: Adding new native sender"); - self.native_senders.push(msg.0); - self.native_sender_count.store( + self.native_senders.push(CountedSender { tx, dropped }); + self.native_ingress.senders.store( self.native_senders.len(), std::sync::atomic::Ordering::Release, ); } } +impl Message for CameraFeed { + type Reply = (); + + async fn handle( + &mut self, + msg: AddNativeSender, + _: &mut Context, + ) -> Self::Reply { + self.add_native_sender(msg.0, None); + } +} + +impl Message for CameraFeed { + type Reply = (); + + async fn handle( + &mut self, + msg: AddCountedNativeSender, + _: &mut Context, + ) -> Self::Reply { + self.add_native_sender(msg.0, Some(msg.1)); + } +} + impl Message for CameraFeed { type Reply = (); @@ -1407,8 +1553,8 @@ impl Message for CameraFeed { _: &mut Context, ) -> Self::Reply { self.native_senders - .retain(|sender| !sender.same_channel(&msg.0)); - self.native_sender_count.store( + .retain(|sender| !sender.tx.same_channel(&msg.0)); + self.native_ingress.senders.store( self.native_senders.len(), std::sync::atomic::Ordering::Release, ); @@ -1451,16 +1597,39 @@ impl Message for CameraFeed { static CAMERA_FRAME_COUNTER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); -fn send_frame_to_camera_senders( - senders: &mut Vec>, +/// Frames a fan-out could not deliver: one per sender whose queue was full. +struct FanoutDrops<'a> { + total: &'a mut u64, + log: &'a mut DropLog, +} + +impl FanoutDrops<'_> { + fn record(&mut self, count: u64, frame_num: u64, sender_label: &str) { + if count == 0 { + return; + } + *self.total = self.total.saturating_add(count); + let total = *self.total; + if let Some(dropped) = self.log.record(count, std::time::Instant::now()) { + warn!( + dropped, + total, frame_num, "{sender_label} ingress queue full, frames dropped" + ); + } + } +} + +fn send_frame_to_camera_senders>( + senders: &mut Vec, frame: T, frame_num: u64, sender_label: &str, + mut drops: FanoutDrops<'_>, ) -> bool { // A disconnected sender whose queue is still full would otherwise never be // try_send'd again, leaving it (and its queued frames) retained forever. let len_before_retain = senders.len(); - senders.retain(|sender| !sender.is_disconnected()); + senders.retain(|sender| !sender.channel().is_disconnected()); let removed_disconnected = senders.len() != len_before_retain; if removed_disconnected { debug!( @@ -1470,54 +1639,40 @@ fn send_frame_to_camera_senders( ); } - let mut last_ready_sender = None; - - for (i, sender) in senders.iter().enumerate() { - if sender.is_full() { - if frame_num.is_multiple_of(30) { - warn!( - "{} sender {} channel full at frame {}, dropping frame", - sender_label, i, frame_num - ); - } - } else { - last_ready_sender = Some(i); - } - } - - let Some(last_ready_sender) = last_ready_sender else { - return removed_disconnected; - }; + // The last sender with room takes the frame itself instead of a clone. + let last_ready_sender = senders + .iter() + .rposition(|sender| !sender.channel().is_full()); let mut frame = Some(frame); + let mut skipped = 0; let mut to_remove = vec![]; - for (i, sender) in senders.iter().enumerate().take(last_ready_sender + 1) { - if sender.is_full() { + for (i, sender) in senders.iter().enumerate() { + let ready = last_ready_sender.is_some_and(|last| i <= last); + if !ready || sender.channel().is_full() { + sender.record_drop(); + skipped += 1; continue; } - let send_result = if i == last_ready_sender { + let send_result = if Some(i) == last_ready_sender { let Some(frame) = frame.take() else { break; }; - sender.try_send(frame) + sender.channel().try_send(frame) } else { let Some(frame) = frame.as_ref() else { break; }; - sender.try_send((*frame).clone()) + sender.channel().try_send(frame.clone()) }; match send_result { Ok(()) => {} Err(flume::TrySendError::Full(_)) => { - if frame_num.is_multiple_of(30) { - warn!( - "{} sender {} channel full at frame {}, dropping frame", - sender_label, i, frame_num - ); - } + sender.record_drop(); + skipped += 1; } Err(flume::TrySendError::Disconnected(_)) => { debug!( @@ -1529,6 +1684,8 @@ fn send_frame_to_camera_senders( } } + drops.record(skipped, frame_num, sender_label); + if to_remove.is_empty() { return removed_disconnected; } @@ -1557,7 +1714,16 @@ impl Message for CameraFeed { } let frame_num = CAMERA_FRAME_COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed); - if send_frame_to_camera_senders(&mut self.senders, msg.0, frame_num, "Camera") { + if send_frame_to_camera_senders( + &mut self.senders, + msg.0, + frame_num, + "Camera", + FanoutDrops { + total: &mut self.ffmpeg_fanout_full, + log: &mut self.ffmpeg_fanout_log, + }, + ) { self.ffmpeg_sender_count .store(self.senders.len(), std::sync::atomic::Ordering::Release); } @@ -1585,9 +1751,17 @@ impl Message for CameraFeed { let frame_num = NATIVE_CAMERA_FRAME_COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed); - if send_frame_to_camera_senders(&mut self.native_senders, msg.0, frame_num, "Native camera") - { - self.native_sender_count.store( + if send_frame_to_camera_senders( + &mut self.native_senders, + msg.0, + frame_num, + "Native camera", + FanoutDrops { + total: &mut self.native_fanout_full, + log: &mut self.native_fanout_log, + }, + ) { + self.native_ingress.senders.store( self.native_senders.len(), std::sync::atomic::Ordering::Release, ); @@ -1666,6 +1840,7 @@ impl Message for CameraFeed { Ok(CameraFeedLock { camera_info, video_info, + native_ingress: self.native_ingress.clone(), actor: ctx.actor_ref(), drop_tx: Some(drop_tx), _token: token, @@ -2483,3 +2658,296 @@ mod tests { ); } } + +#[cfg(test)] +mod ingress_tests { + use super::*; + use crate::sources::native_camera::native_ingress_capacity; + use cap_media_info::RawVideoFormat; + use std::sync::atomic::{AtomicU64, Ordering::Relaxed}; + + type Output = (flume::Receiver, Arc); + + struct Fanout { + senders: Vec>, + total: u64, + log: DropLog, + } + + impl Fanout { + fn new(capacities: &[usize]) -> (Self, Vec) { + let mut senders = vec![]; + let mut outputs = vec![]; + for &capacity in capacities { + let (tx, rx) = flume::bounded(capacity); + let dropped = Arc::new(AtomicU64::new(0)); + senders.push(CountedSender { + tx, + dropped: Some(dropped.clone()), + }); + outputs.push((rx, dropped)); + } + let fanout = Self { + senders, + total: 0, + log: DropLog::default(), + }; + (fanout, outputs) + } + + fn send(&mut self, frame: u32) { + send_frame_to_camera_senders( + &mut self.senders, + frame, + u64::from(frame), + "Native camera", + FanoutDrops { + total: &mut self.total, + log: &mut self.log, + }, + ); + } + } + + fn hd30() -> VideoInfo { + VideoInfo::from_raw(RawVideoFormat::Nv12, 1280, 720, 30) + } + + #[test] + fn burst_after_a_two_second_stall_fits_the_ingress_queue() { + let (mut fanout, outputs) = Fanout::new(&[native_ingress_capacity(&hd30())]); + // The consumer is stalled for 2 s at 30 fps; the feed then hands the + // whole backlog over at once. + for frame in 0..60 { + fanout.send(frame); + } + let (rx, dropped) = &outputs[0]; + assert_eq!(dropped.load(Relaxed), 0); + assert_eq!(fanout.total, 0); + assert_eq!(rx.drain().collect::>(), (0..60).collect::>()); + } + + #[test] + fn frames_past_the_ingress_bound_are_counted_and_reported() { + let capacity = native_ingress_capacity(&hd30()); + let (mut fanout, outputs) = Fanout::new(&[capacity]); + for frame in 0..capacity as u32 + 5 { + fanout.send(frame); + } + assert_eq!(outputs[0].1.load(Relaxed), 5); + assert_eq!(outputs[0].0.len(), capacity); + assert_eq!(fanout.total, 5); + // The first drop was reported at once; the other four wait for the + // next report window. + let now = std::time::Instant::now(); + assert_eq!(fanout.log.record(0, now), None); + assert_eq!(fanout.log.record(0, now + DropLog::INTERVAL), Some(4)); + } + + #[test] + fn previous_eight_frame_queue_lost_most_of_the_same_burst() { + let (mut fanout, outputs) = Fanout::new(&[8]); + for frame in 0..60 { + fanout.send(frame); + } + assert_eq!(outputs[0].1.load(Relaxed), 52); + assert_eq!(outputs[0].0.len(), 8); + } + + /// A full preview queue is not a recording loss: each attached queue + /// counts only the frames it did not receive. + #[test] + fn losses_are_counted_per_attached_queue() { + let (mut fanout, outputs) = Fanout::new(&[4, 64, 2]); + for frame in 0..10 { + fanout.send(frame); + } + let counts: Vec<_> = outputs + .iter() + .map(|(rx, dropped)| (rx.len(), dropped.load(Relaxed))) + .collect(); + assert_eq!(counts, [(4, 6), (10, 0), (2, 8)]); + assert_eq!(fanout.total, 14); + } + + /// Consumers draining concurrently with the fan-out: every frame is + /// either received or counted as dropped for each queue, never both. + #[test] + fn received_plus_dropped_is_every_frame_per_queue() { + const FRAMES: u32 = 20_000; + let (mut fanout, outputs) = Fanout::new(&[1, 2, 1]); + let stop = Arc::new(std::sync::atomic::AtomicBool::new(false)); + let drains: Vec<_> = outputs + .iter() + .enumerate() + .map(|(i, (rx, _))| { + let rx = rx.clone(); + let stop = stop.clone(); + std::thread::spawn(move || { + let mut received = 0_u64; + while !stop.load(Relaxed) || !rx.is_empty() { + if rx.try_recv().is_ok() { + received += 1; + } + if i == 1 { + std::thread::yield_now(); + } + } + received + }) + }) + .collect(); + for frame in 0..FRAMES { + fanout.send(frame); + } + stop.store(true, Relaxed); + let mut total_dropped = 0; + for ((_, dropped), drain) in outputs.iter().zip(drains) { + let received = drain.join().unwrap(); + let dropped = dropped.load(Relaxed); + assert_eq!(received + dropped, u64::from(FRAMES)); + total_dropped += dropped; + } + assert_eq!(fanout.total, total_dropped); + } + + #[test] + fn drop_log_reports_the_first_drop_then_rate_limits() { + let mut log = DropLog::default(); + let start = std::time::Instant::now(); + assert_eq!(log.record(0, start), None); + assert_eq!(log.record(1, start), Some(1)); + assert_eq!(log.record(3, start + Duration::from_secs(1)), None); + assert_eq!(log.record(1, start + Duration::from_secs(4)), None); + assert_eq!(log.record(2, start + DropLog::INTERVAL), Some(6)); + assert_eq!(log.record(0, start + DropLog::INTERVAL * 3), None); + } + + #[cfg(target_os = "macos")] + mod actor { + use super::*; + + /// Scripted runtime stall: the feed actor handles nothing else. + struct Hold(Duration, oneshot::Sender<()>); + + impl Message for CameraFeed { + type Reply = (); + + async fn handle(&mut self, msg: Hold, _: &mut Context) { + let _ = msg.1.send(()); + tokio::time::sleep(msg.0).await; + } + } + + fn frame(index: i64) -> NativeCameraFrame { + use cidre::{cm, cv}; + let buf = cv::PixelBuf::new(16, 16, cv::PixelFormat::_420V, None).unwrap(); + let desc = cm::VideoFormatDesc::with_image_buf(&buf).unwrap(); + let timing = cm::SampleTimingInfo { + duration: cm::Time::new(1, 30), + pts: cm::Time::new(index, 30), + dts: cm::Time::invalid(), + }; + let sample_buf = + cm::SampleBuf::with_image_buf(&buf, true, None, std::ptr::null(), &desc, &timing) + .unwrap(); + NativeCameraFrame { + sample_buf, + timestamp: Timestamp::MachAbsoluteTime(cap_timestamp::MachAbsoluteTimestamp::new( + index as u64, + )), + } + } + + async fn eventually(what: &str, check: impl Fn() -> bool) { + let deadline = std::time::Instant::now() + Duration::from_secs(10); + while !check() { + assert!(std::time::Instant::now() < deadline, "timed out: {what}"); + tokio::time::sleep(Duration::from_millis(5)).await; + } + } + + struct StalledFeed { + feed: ActorRef, + ingress: Arc, + dropped: Arc, + rx: flume::Receiver, + } + + async fn stalled_feed(capacity: usize, hold: Duration) -> StalledFeed { + let ingress = Arc::new(NativeCameraIngress::default()); + let feed = CameraFeed::spawn(CameraFeed { + native_ingress: ingress.clone(), + ..CameraFeed::default() + }); + let (tx, rx) = flume::bounded(capacity); + let dropped = Arc::new(AtomicU64::new(0)); + feed.ask(AddCountedNativeSender(tx, dropped.clone())) + .await + .unwrap(); + let (held_tx, held_rx) = oneshot::channel(); + feed.tell(Hold(hold, held_tx)).await.unwrap(); + held_rx.await.unwrap(); + StalledFeed { + feed, + ingress, + dropped, + rx, + } + } + + /// The capture callback keeps delivering while the feed is stalled; + /// after the stall the feed fans the backlog out in one burst and the + /// recording receives every frame, in order. + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn stall_then_burst_keeps_every_frame() { + let capacity = native_ingress_capacity(&hd30()); + let f = stalled_feed(capacity, Duration::from_millis(1500)).await; + let recipient = f.feed.clone().recipient::(); + let frames: Vec<_> = (0..45).map(frame).collect(); + for frame in frames { + hand_native_frame_to_feed(&recipient, &f.ingress, frame); + } + eventually("burst delivered", || f.rx.len() == 45).await; + assert_eq!(f.ingress.mailbox_full(), 0); + assert_eq!(f.dropped.load(Relaxed), 0); + let pts: Vec<_> = + f.rx.drain() + .map(|frame| frame.sample_buf.pts().value) + .collect(); + assert_eq!(pts, (0..45).collect::>()); + } + + /// Past the mailbox and the ingress queue every lost frame is + /// counted, and the callback's hand-over never waits for the stalled + /// feed. + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn losses_past_the_bound_are_counted_without_blocking_the_callback() { + let capacity = native_ingress_capacity(&hd30()); + let f = stalled_feed(capacity, Duration::from_millis(1000)).await; + let recipient = f.feed.clone().recipient::(); + let frames: Vec<_> = (0..70).map(frame).collect(); + let mut slowest = Duration::ZERO; + for frame in frames { + let start = std::time::Instant::now(); + hand_native_frame_to_feed(&recipient, &f.ingress, frame); + slowest = slowest.max(start.elapsed()); + } + assert!( + slowest < Duration::from_millis(50), + "callback hand-over waited {slowest:?}" + ); + // The mailbox holds 64 frames; the other six are lost and counted. + assert_eq!(f.ingress.mailbox_full(), 6); + eventually("backlog delivered", || f.rx.len() == capacity).await; + assert_eq!(f.dropped.load(Relaxed), 0); + // The recording still does not drain: the next frames overflow + // its ingress queue and are counted. + for frame in (70..73).map(frame) { + hand_native_frame_to_feed(&recipient, &f.ingress, frame); + } + eventually("overflow counted", || f.dropped.load(Relaxed) == 3).await; + assert_eq!(f.rx.len(), capacity); + } + } +} diff --git a/crates/recording/src/output_pipeline/macos.rs b/crates/recording/src/output_pipeline/macos.rs index ea764ef3457..53e73bca231 100644 --- a/crates/recording/src/output_pipeline/macos.rs +++ b/crates/recording/src/output_pipeline/macos.rs @@ -196,9 +196,36 @@ impl FrameDropTracker { fn record_drop(&mut self) { self.drops_in_window += 1; self.total_drops += 1; + if self.total_drops == 1 { + warn!( + source = self.source, + total_frames = self.total_frames, + "MP4 muxer encoder queue full, first frame dropped" + ); + if let Some(tx) = &self.health_tx { + emit_health( + tx, + PipelineHealthEvent::FrameDropRateHigh { + source: self.source.to_string(), + rate_pct: 100.0 / (self.total_frames + 1) as f64, + }, + ); + } + } self.check_drop_rate(); } + fn log_totals(&self) { + if self.total_drops > 0 { + warn!( + source = self.source, + total_frames = self.total_frames, + total_drops = self.total_drops, + "MP4 muxer dropped frames during the recording" + ); + } + } + 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; @@ -226,11 +253,13 @@ impl FrameDropTracker { self.health_emitted = true; } } else if self.drops_in_window > 0 { - debug!( + warn!( + source = self.source, frames = self.frames_in_window, drops = self.drops_in_window, drop_rate_pct = format!("{:.1}%", drop_rate), - "MP4 muxer frame stats" + total_drops = self.total_drops, + "MP4 muxer dropped frames" ); } } @@ -685,6 +714,7 @@ impl Muxer for AVFoundationMp4Muxer { fn finish(&mut self, timestamp: Duration) -> anyhow::Result> { let mut finish_error: Option = None; + self.frame_drops.log_totals(); if let Some(mut state) = self.state.take() { if let Err(e) = state.video_tx.send(None) { @@ -1287,6 +1317,7 @@ impl Muxer for AVFoundationCameraMuxer { fn finish(&mut self, timestamp: Duration) -> anyhow::Result> { let mut finish_error: Option = None; + self.frame_drops.log_totals(); if let Some(mut state) = self.state.take() { if let Err(e) = state.video_tx.send(None) { diff --git a/crates/recording/src/sources/native_camera.rs b/crates/recording/src/sources/native_camera.rs index abb50eff221..d82d2cfe6c7 100644 --- a/crates/recording/src/sources/native_camera.rs +++ b/crates/recording/src/sources/native_camera.rs @@ -1,36 +1,213 @@ use crate::{ - feeds::camera::{self, CameraFeedLock}, - output_pipeline::{NativeCameraFrame, SetupCtx, VideoSource}, + feeds::camera::{self, CameraFeedLock, DropLog, NativeCameraIngress}, + output_pipeline::{ + HealthSender, NativeCameraFrame, PipelineHealthEvent, SetupCtx, VideoSource, emit_health, + }, }; use anyhow::anyhow; -use cap_media_info::VideoInfo; +use cap_media_info::{Pixel, VideoInfo}; use futures::{FutureExt, channel::mpsc, future::BoxFuture}; use std::sync::{ Arc, - atomic::{AtomicBool, Ordering}, + atomic::{AtomicBool, AtomicU64, Ordering}, }; -use std::time::Duration; +use std::time::{Duration, Instant}; use tokio::sync::oneshot; const CAMERA_SENDER_ATTACH_TIMEOUT: Duration = Duration::from_millis(1500); +/// How long the recording may stop draining camera frames (a runtime stall) +/// before the ingress queue fills. +const INGRESS_TIME_BUDGET_SECS: usize = 2; +/// The camera feed's actor mailbox (kameo's default bounded mailbox). After a +/// stall the feed hands its whole backlog over in one burst, so the ingress +/// queue must take that many frames at once. +const CAMERA_FEED_MAILBOX_FRAMES: usize = 64; +/// Upper bound on the pixel data the ingress queue can keep alive. On macOS a +/// queued frame retains a capture pool surface (the pool grows per retained +/// buffer); on Windows it is a heap copy of the frame. +const INGRESS_BYTE_BUDGET: usize = 256 * 1024 * 1024; +/// The previous fixed capacity; never go below it. +const MIN_INGRESS_FRAMES: usize = 8; + +fn frame_bytes(info: &VideoInfo) -> usize { + let pixels = info.width as usize * info.height as usize; + match info.pixel_format { + Pixel::NV12 | Pixel::NV21 | Pixel::YUV420P | Pixel::YUVJ420P => pixels * 3 / 2, + Pixel::UYVY422 | Pixel::YUYV422 | Pixel::YUV422P | Pixel::YUVJ422P | Pixel::NV16 => { + pixels * 2 + } + _ => pixels * 4, + } +} + +/// Frames the native ingress queue holds: the time budget at the camera's +/// frame rate (at least one full feed mailbox), capped by the byte budget. +pub(crate) fn native_ingress_capacity(info: &VideoInfo) -> usize { + let by_time = (info.fps().max(1) as usize).saturating_mul(INGRESS_TIME_BUDGET_SECS); + let by_bytes = INGRESS_BYTE_BUDGET / frame_bytes(info).max(1); + by_time + .max(CAMERA_FEED_MAILBOX_FRAMES) + .min(by_bytes) + .max(MIN_INGRESS_FRAMES) +} + pub struct NativeCamera { feed_lock: Arc, stop_tx: Option>, stopped: Arc, } +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub(crate) struct IngressSummary { + pub received: u64, + pub sent: u64, + pub mailbox_full: u64, + pub ingress_full: u64, + pub forwarder_full: u64, +} + +impl IngressSummary { + fn lost(&self) -> u64 { + self.mailbox_full + self.ingress_full + self.forwarder_full + } +} + +/// Reports every camera frame this recording loses: at the feed's mailbox +/// (shared by everything attached to the feed), at this recording's ingress +/// queue, and between this source and the encoder. The first loss at each +/// boundary is logged at warn and sent as a health event at once; later +/// losses at most every five seconds; the totals at the end. +pub(crate) struct IngressReporter { + feed: Option>, + mailbox_start: u64, + mailbox_seen: u64, + ingress_dropped: Arc, + ingress_seen: u64, + health_tx: Option, + feed_log: DropLog, + forwarder_log: DropLog, + summary: IngressSummary, +} + +impl IngressReporter { + /// Create before attaching the ingress queue: mailbox losses while it + /// attaches already affect this recording. + pub(crate) fn new( + feed: Option>, + ingress_dropped: Arc, + health_tx: Option, + ) -> Self { + let mailbox_start = feed.as_ref().map_or(0, |feed| feed.mailbox_full()); + Self { + feed, + mailbox_start, + mailbox_seen: mailbox_start, + ingress_seen: ingress_dropped.load(Ordering::Relaxed), + ingress_dropped, + health_tx, + feed_log: DropLog::default(), + forwarder_log: DropLog::default(), + summary: IngressSummary::default(), + } + } + + fn received(&mut self) { + self.summary.received += 1; + self.poll_feed(Instant::now()); + } + + fn sent(&mut self) { + self.summary.sent += 1; + } + + fn poll_feed(&mut self, now: Instant) { + let mailbox = self + .feed + .as_ref() + .map_or(self.mailbox_seen, |feed| feed.mailbox_full()); + let ingress = self.ingress_dropped.load(Ordering::Relaxed); + let new = + mailbox.saturating_sub(self.mailbox_seen) + ingress.saturating_sub(self.ingress_seen); + if new == 0 { + return; + } + self.mailbox_seen = mailbox; + self.ingress_seen = ingress; + self.summary.mailbox_full = mailbox.saturating_sub(self.mailbox_start); + self.summary.ingress_full = ingress; + if let Some(dropped) = self.feed_log.record(new, now) { + tracing::warn!( + dropped, + mailbox_full = self.summary.mailbox_full, + ingress_full = self.summary.ingress_full, + "Native camera frames lost before the recording received them" + ); + self.emit("camera-ingress:feed"); + } + } + + fn forwarder_full(&mut self, now: Instant) { + self.summary.forwarder_full += 1; + if let Some(dropped) = self.forwarder_log.record(1, now) { + tracing::warn!( + dropped, + total = self.summary.forwarder_full, + "Native camera encoder queue full, frames dropped" + ); + self.emit("camera-ingress:encoder-queue"); + } + } + + fn emit(&self, source: &str) { + let Some(health_tx) = &self.health_tx else { + return; + }; + let lost = self.summary.lost(); + let offered = self.summary.received + self.summary.mailbox_full + self.summary.ingress_full; + emit_health( + health_tx, + PipelineHealthEvent::FrameDropRateHigh { + source: source.to_string(), + rate_pct: 100.0 * lost as f64 / offered.max(1) as f64, + }, + ); + } + + fn finish(mut self, elapsed: Duration) -> IngressSummary { + self.poll_feed(Instant::now()); + let summary = self.summary; + if summary.lost() > 0 { + tracing::warn!( + received = summary.received, + sent = summary.sent, + mailbox_full = summary.mailbox_full, + ingress_full = summary.ingress_full, + encoder_queue_full = summary.forwarder_full, + ?elapsed, + "Native camera source finished with lost frames" + ); + } else { + tracing::info!( + "Native camera source finished: {} received, {} sent, 0 dropped in {:?}", + summary.received, + summary.sent, + elapsed + ); + } + summary + } +} + async fn forward_native_frames( rx: flume::Receiver, video_tx: mpsc::Sender, stop_rx: oneshot::Receiver<()>, stopped: Arc, required: bool, -) -> anyhow::Result<()> { + mut report: IngressReporter, +) -> anyhow::Result { tracing::debug!("Native camera source task started"); - let mut frame_count: u64 = 0; - let mut sent_count: u64 = 0; - let mut dropped_count: u64 = 0; let start = std::time::Instant::now(); let mut video_tx = video_tx; let mut stop_rx = stop_rx.fuse(); @@ -50,33 +227,16 @@ async fn forward_native_frames( result = rx.recv_async() => { match result { Ok(frame) => { - frame_count += 1; + report.received(); match video_tx.try_send(frame) { - Ok(()) => { - sent_count += 1; - if sent_count.is_multiple_of(30) { - tracing::debug!( - "Native camera source: sent {} frames, dropped {} in {:?}", - sent_count, - dropped_count, - start.elapsed() - ); - } - } + Ok(()) => report.sent(), Err(e) => { if e.is_full() { - dropped_count += 1; - if dropped_count.is_multiple_of(30) { - tracing::warn!( - "Native camera source: encoder can't keep up, dropped {} frames so far", - dropped_count - ); - } + report.forwarder_full(Instant::now()); } else if e.is_disconnected() { tracing::debug!( - "Native camera source: pipeline closed after {} sent, {} dropped", - sent_count, - dropped_count + "Native camera source: pipeline closed after {:?}", + report.summary ); if required && !stopped.load(Ordering::Acquire) { return Err(anyhow!("Native camera encoder disconnected before Stop")); @@ -89,7 +249,7 @@ async fn forward_native_frames( Err(e) => { tracing::debug!( "Native camera feed disconnected (rx closed) after {} frames in {:?}: {e}", - frame_count, + report.summary.received, start.elapsed() ); if required && !stopped.load(Ordering::Acquire) { @@ -104,14 +264,7 @@ async fn forward_native_frames( drop(video_tx); - tracing::info!( - "Native camera source finished: {} received, {} sent, {} dropped in {:?}", - frame_count, - sent_count, - dropped_count, - start.elapsed() - ); - Ok(()) + Ok(report.finish(start.elapsed())) } impl VideoSource for NativeCamera { @@ -121,16 +274,24 @@ impl VideoSource for NativeCamera { async fn setup( feed_lock: Self::Config, video_tx: mpsc::Sender, - _ctx: &mut SetupCtx, + ctx: &mut SetupCtx, ) -> anyhow::Result where Self: Sized, { - let (tx, rx) = flume::bounded(8); + let capacity = native_ingress_capacity(feed_lock.video_info()); + tracing::debug!(capacity, "Native camera ingress queue"); + let (tx, rx) = flume::bounded(capacity); + let ingress_dropped = Arc::new(AtomicU64::new(0)); + let report = IngressReporter::new( + Some(feed_lock.native_ingress().clone()), + ingress_dropped.clone(), + Some(ctx.health_tx().clone()), + ); tokio::time::timeout( CAMERA_SENDER_ATTACH_TIMEOUT, - feed_lock.ask(camera::AddNativeSender(tx)), + feed_lock.ask(camera::AddCountedNativeSender(tx, ingress_dropped)), ) .await .map_err(|_| anyhow!("Timed out adding native camera sender"))? @@ -140,9 +301,11 @@ impl VideoSource for NativeCamera { let stopped = Arc::new(AtomicBool::new(false)); let stopped_clone = stopped.clone(); - let task = forward_native_frames(rx, video_tx, stop_rx, stopped_clone, cfg!(windows)); + let task = + forward_native_frames(rx, video_tx, stop_rx, stopped_clone, cfg!(windows), report) + .map(|result| result.map(drop)); #[cfg(windows)] - _ctx.tasks().spawn("native-camera", task); + ctx.tasks().spawn("native-camera", task); #[cfg(not(windows))] drop(tokio::spawn(task)); @@ -187,6 +350,7 @@ mod forwarding_tests { stopped, Arc::new(AtomicBool::new(false)), true, + IngressReporter::new(None, Default::default(), None), ) .await; assert!( @@ -210,6 +374,7 @@ mod forwarding_tests { stopped, Arc::new(AtomicBool::new(false)), true, + IngressReporter::new(None, Default::default(), None), ) .await .unwrap(); @@ -227,6 +392,7 @@ mod forwarding_tests { stopped, Arc::new(AtomicBool::new(false)), true, + IngressReporter::new(None, Default::default(), None), )); sender.send_async(17_u8).await.unwrap(); assert_eq!(frames.next().await, Some(17)); @@ -249,6 +415,7 @@ mod forwarding_tests { stopped, Arc::new(AtomicBool::new(false)), true, + IngressReporter::new(None, Default::default(), None), ) .await; assert!( @@ -271,8 +438,99 @@ mod forwarding_tests { stopped, Arc::new(AtomicBool::new(false)), false, + IngressReporter::new(None, Default::default(), None), + ) + .await + .unwrap(); + } + + fn info(format: cap_media_info::RawVideoFormat, w: u32, h: u32, fps: u32) -> VideoInfo { + VideoInfo::from_raw(format, w, h, fps) + } + + #[test] + fn ingress_capacity_is_sized_by_time_and_bounded_by_bytes() { + use cap_media_info::RawVideoFormat::{Bgra, Nv12, Uyvy}; + let cases = [ + (info(Nv12, 1280, 720, 30), 64), + (info(Nv12, 1920, 1080, 30), 64), + (info(Nv12, 1280, 720, 60), 120), + (info(Nv12, 1920, 1080, 60), 86), + (info(Uyvy, 1920, 1080, 30), 64), + (info(Nv12, 3840, 2160, 30), 21), + (info(Bgra, 3840, 2160, 30), MIN_INGRESS_FRAMES), + ]; + for (info, expected) in cases { + let capacity = native_ingress_capacity(&info); + assert_eq!( + capacity, + expected, + "{}x{}@{} {:?}", + info.width, + info.height, + info.fps(), + info.pixel_format + ); + assert!( + capacity == MIN_INGRESS_FRAMES + || capacity * frame_bytes(&info) <= INGRESS_BYTE_BUDGET + ); + } + } + + #[tokio::test] + async fn encoder_queue_overflow_is_counted() { + let (sender, receiver) = flume::bounded(16); + let (video, frames) = mpsc::channel(1); + let (_stop, stopped) = oneshot::channel(); + for frame in 0..10_u8 { + sender.send_async(frame).await.unwrap(); + } + drop(sender); + let summary = forward_native_frames( + receiver, + video, + stopped, + Arc::new(AtomicBool::new(false)), + false, + IngressReporter::new(None, Default::default(), None), + ) + .await + .unwrap(); + // futures mpsc holds its buffer plus one slot per sender. + assert_eq!(summary.received, 10); + assert_eq!(summary.sent, 2); + assert_eq!(summary.forwarder_full, 8); + drop(frames); + } + + #[tokio::test] + async fn feed_losses_count_from_the_recording_start() { + let ingress = Arc::new(NativeCameraIngress::default()); + ingress.record_mailbox_full(); + let ingress_dropped = Arc::new(AtomicU64::new(0)); + let report = IngressReporter::new(Some(ingress.clone()), ingress_dropped.clone(), None); + ingress.record_mailbox_full(); + ingress.record_mailbox_full(); + ingress_dropped.fetch_add(3, Ordering::Relaxed); + let (sender, receiver) = flume::bounded(4); + let (video, mut frames) = mpsc::channel(4); + let (_stop, stopped) = oneshot::channel(); + sender.send_async(1_u8).await.unwrap(); + drop(sender); + let summary = forward_native_frames( + receiver, + video, + stopped, + Arc::new(AtomicBool::new(false)), + false, + report, ) .await .unwrap(); + assert_eq!(summary.mailbox_full, 2); + assert_eq!(summary.ingress_full, 3); + assert_eq!(summary.sent, 1); + assert_eq!(futures::StreamExt::next(&mut frames).await, Some(1)); } }