Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

feat(recording): route source drops and mic dropped-messages through health events

Richie McIlroy7fffd6b12308
diff --git a/crates/recording/src/feeds/microphone.rs b/crates/recording/src/feeds/microphone.rs
index 29a823090..a74d95873 100644
--- a/crates/recording/src/feeds/microphone.rs
+++ b/crates/recording/src/feeds/microphone.rs
@@ -1,3 +1,4 @@
+use crate::output_pipeline::{HealthSender, PipelineHealthEvent, emit_health};
use cap_audio::estimate_input_latency;
use cap_media_info::{AudioInfo, ffmpeg_sample_format_for};
use cap_timestamp::Timestamp;
@@ -15,8 +16,10 @@ use std::{
ops::Deref,
sync::{
Arc, Weak,
+ atomic::{AtomicU64, Ordering},
mpsc::{self, SyncSender},
},
+ time::{Duration, Instant},
};
use tracing::{debug, error, info, trace, warn};
@@ -39,8 +42,48 @@ pub struct MicrophoneFeed {
input_id_counter: u32,
lock_generation: u64,
state: State,
- senders: Vec<flume::Sender<MicrophoneSamples>>,
+ senders: Vec<MicrophoneFeedSender>,
error_sender: flume::Sender<StreamError>,
+ dropped_message_count: Arc<AtomicU64>,
+}
+
+struct MicrophoneFeedSender {
+ sender: flume::Sender<MicrophoneSamples>,
+ health_tx: Option<HealthSender>,
+ label: Option<String>,
+ stalled_since: Option<Instant>,
+ last_stalled_event: Option<Instant>,
+}
+
+impl MicrophoneFeedSender {
+ fn new(sender: flume::Sender<MicrophoneSamples>) -> Self {
+ Self {
+ sender,
+ health_tx: None,
+ label: None,
+ stalled_since: None,
+ last_stalled_event: None,
+ }
+ }
+
+ fn recording(
+ sender: flume::Sender<MicrophoneSamples>,
+ health_tx: HealthSender,
+ label: String,
+ ) -> Self {
+ Self {
+ sender,
+ health_tx: Some(health_tx),
+ label: Some(label),
+ stalled_since: None,
+ last_stalled_event: None,
+ }
+ }
+
+ fn reset_stall(&mut self) {
+ self.stalled_since = None;
+ self.last_stalled_event = None;
+ }
}
enum State {
@@ -123,6 +166,7 @@ impl MicrophoneFeed {
}),
senders: Vec::new(),
error_sender,
+ dropped_message_count: Arc::new(AtomicU64::new(0)),
}
}
@@ -166,6 +210,7 @@ impl MicrophoneFeed {
sample_format,
actor_ref,
error_sender,
+ dropped_message_count,
log_action,
} = params;
@@ -189,6 +234,7 @@ impl MicrophoneFeed {
let config = config.clone();
let actor_ref = actor_ref.clone();
let error_sender = error_sender.clone();
+ let dropped_message_count = dropped_message_count.clone();
move || {
let device_name_for_log = device.name().ok();
@@ -245,7 +291,7 @@ impl MicrophoneFeed {
}
callback_count += 1;
- let _ = actor_ref
+ if let Err(error) = actor_ref
.tell(MicrophoneSamples {
data: data.bytes().to_vec(),
format: data.sample_format(),
@@ -254,7 +300,11 @@ impl MicrophoneFeed {
info: info.clone(),
timestamp: Timestamp::from_cpal(info.timestamp().capture),
})
- .try_send();
+ .try_send()
+ {
+ dropped_message_count.fetch_add(1, Ordering::Relaxed);
+ warn!("Failed to enqueue microphone samples: {error}");
+ }
}
},
move |e| {
@@ -443,6 +493,10 @@ impl MicrophoneFeedLock {
pub fn device_name(&self) -> &str {
&self.device_name
}
+
+ pub async fn dropped_message_count(&self) -> u64 {
+ self.actor.ask(GetDroppedMessageCount).await.unwrap_or(0)
+ }
}
impl Deref for MicrophoneFeedLock {
@@ -471,8 +525,16 @@ pub struct RemoveInput;
pub struct AddSender(pub flume::Sender<MicrophoneSamples>);
+pub struct AddRecordingSender {
+ pub sender: flume::Sender<MicrophoneSamples>,
+ pub health_tx: HealthSender,
+ pub label: String,
+}
+
pub struct Lock;
+pub struct GetDroppedMessageCount;
+
// Private Events
struct InputConnected {
@@ -524,6 +586,7 @@ struct StreamSpawnParams {
sample_format: SampleFormat,
actor_ref: ActorRef<MicrophoneFeed>,
error_sender: flume::Sender<StreamError>,
+ dropped_message_count: Arc<AtomicU64>,
log_action: StreamLogAction,
}
@@ -580,6 +643,7 @@ impl Message<SetInput> for MicrophoneFeed {
sample_format,
actor_ref: actor_ref.clone(),
error_sender: self.error_sender.clone(),
+ dropped_message_count: self.dropped_message_count.clone(),
log_action: StreamLogAction::Build,
});
let ready = ready_future.shared();
@@ -669,6 +733,7 @@ impl Message<SetInput> for MicrophoneFeed {
sample_format,
actor_ref: actor_ref.clone(),
error_sender: self.error_sender.clone(),
+ dropped_message_count: self.dropped_message_count.clone(),
log_action: StreamLogAction::Rebuild,
});
let ready = ready_future.shared();
@@ -723,7 +788,23 @@ impl Message<AddSender> for MicrophoneFeed {
type Reply = ();
async fn handle(&mut self, msg: AddSender, _: &mut Context<Self, Self::Reply>) -> Self::Reply {
- self.senders.push(msg.0);
+ self.senders.push(MicrophoneFeedSender::new(msg.0));
+ }
+}
+
+impl Message<AddRecordingSender> for MicrophoneFeed {
+ type Reply = ();
+
+ async fn handle(
+ &mut self,
+ msg: AddRecordingSender,
+ _: &mut Context<Self, Self::Reply>,
+ ) -> Self::Reply {
+ self.senders.push(MicrophoneFeedSender::recording(
+ msg.sender,
+ msg.health_tx,
+ msg.label,
+ ));
}
}
@@ -736,12 +817,36 @@ impl Message<MicrophoneSamples> for MicrophoneFeed {
_: &mut Context<Self, Self::Reply>,
) -> Self::Reply {
let mut to_remove = vec![];
-
- for (i, sender) in self.senders.iter().enumerate() {
- if let Err(TrySendError::Disconnected(_)) = sender.try_send(msg.clone()) {
- warn!("Audio sender {} disconnected, will be removed", i);
- to_remove.push(i);
- };
+ let now = Instant::now();
+ let stall_emit_interval = Duration::from_secs(5);
+
+ for (i, sender) in self.senders.iter_mut().enumerate() {
+ match sender.sender.try_send(msg.clone()) {
+ Ok(()) => sender.reset_stall(),
+ Err(TrySendError::Full(_)) => {
+ let stalled_since = sender.stalled_since.get_or_insert(now);
+ let should_emit = sender
+ .last_stalled_event
+ .is_none_or(|last| now.duration_since(last) >= stall_emit_interval);
+ if should_emit {
+ sender.last_stalled_event = Some(now);
+ if let (Some(health_tx), Some(label)) = (&sender.health_tx, &sender.label) {
+ emit_health(
+ health_tx,
+ PipelineHealthEvent::Stalled {
+ source: label.clone(),
+ waited_ms: now.duration_since(*stalled_since).as_millis()
+ as u64,
+ },
+ );
+ }
+ }
+ }
+ Err(TrySendError::Disconnected(_)) => {
+ warn!("Audio sender {} disconnected, will be removed", i);
+ to_remove.push(i);
+ }
+ }
}
if !to_remove.is_empty() {
@@ -824,6 +929,18 @@ impl Message<Lock> for MicrophoneFeed {
}
}
+impl Message<GetDroppedMessageCount> for MicrophoneFeed {
+ type Reply = u64;
+
+ async fn handle(
+ &mut self,
+ _: GetDroppedMessageCount,
+ _: &mut Context<Self, Self::Reply>,
+ ) -> Self::Reply {
+ self.dropped_message_count.load(Ordering::Relaxed)
+ }
+}
+
impl Message<InputConnected> for MicrophoneFeed {
type Reply = Result<(), FeedLockedError>;
diff --git a/crates/recording/src/sources/camera.rs b/crates/recording/src/sources/camera.rs
index aede5e52d..0826ba21f 100644
--- a/crates/recording/src/sources/camera.rs
+++ b/crates/recording/src/sources/camera.rs
@@ -1,7 +1,7 @@
use crate::{
feeds::camera::{self, CameraFeedLock},
ffmpeg::FFmpegVideoFrame,
- output_pipeline::{SetupCtx, VideoSource},
+ output_pipeline::{SetupCtx, StallSendOutcome, VideoSource, send_with_stall_budget_futures},
};
use anyhow::anyhow;
use cap_media_info::VideoInfo;
@@ -73,12 +73,13 @@ impl VideoSource for Camera {
async fn setup(
feed_lock: Self::Config,
video_tx: mpsc::Sender<Self::Frame>,
- _: &mut SetupCtx,
+ ctx: &mut SetupCtx,
) -> anyhow::Result<Self>
where
Self: Sized,
{
let (tx, rx) = flume::bounded(256);
+ let stall_health_tx = ctx.health_tx().clone();
let original_video_info = *feed_lock.video_info();
let original_width = original_video_info.width;
@@ -195,8 +196,13 @@ impl VideoSource for Camera {
scaler = None;
}
- match video_tx.try_send(frame) {
- Ok(()) => {
+ match send_with_stall_budget_futures(
+ &mut video_tx,
+ frame,
+ "camera-video",
+ &stall_health_tx,
+ ) {
+ StallSendOutcome::Sent => {
sent_count += 1;
if sent_count.is_multiple_of(300) {
let total_scaled = scaled_count_clone.load(Ordering::Relaxed);
@@ -209,24 +215,23 @@ impl VideoSource for Camera {
);
}
}
- Err(e) => {
- if e.is_full() {
- dropped_count += 1;
- if dropped_count.is_multiple_of(30) {
- tracing::warn!(
- dropped_count,
- "Camera source: encoder can't keep up"
- );
- }
- } else if e.is_disconnected() {
- tracing::debug!(
- sent_count,
+ StallSendOutcome::StalledAndDropped { .. } => {
+ dropped_count += 1;
+ if dropped_count.is_multiple_of(30) {
+ tracing::warn!(
dropped_count,
- "Camera source: pipeline closed"
+ "Camera source: encoder can't keep up"
);
- break;
}
}
+ StallSendOutcome::Disconnected => {
+ tracing::debug!(
+ sent_count,
+ dropped_count,
+ "Camera source: pipeline closed"
+ );
+ break;
+ }
}
}
Err(e) => {
diff --git a/crates/recording/src/sources/microphone.rs b/crates/recording/src/sources/microphone.rs
index c32d1bc66..71740c4f6 100644
--- a/crates/recording/src/sources/microphone.rs
+++ b/crates/recording/src/sources/microphone.rs
@@ -1,13 +1,13 @@
use crate::{
feeds::microphone::{self, MicrophoneFeedLock},
output_pipeline::{AudioFrame, AudioSource, PipelineHealthEvent, emit_health},
+ sources::audio_mixer::AudioMixer,
};
use cap_media_info::{AudioInfo, ffmpeg_sample_format_for};
use cpal::SampleFormat;
use futures::{SinkExt, channel::mpsc};
use kameo::error::SendError;
use std::{
- borrow::Cow,
sync::{
Arc,
atomic::{AtomicBool, AtomicU64, Ordering},
@@ -103,12 +103,34 @@ impl MicResampler {
);
let input_frame = source_info.wrap_frame(data);
- let mut output = ffmpeg::frame::Audio::empty();
+ let input_samples = input_frame.samples();
+
+ let target = *self.context.output();
+ let src_rate = source_rate.max(1) as u64;
+ let dst_rate = target.rate.max(1) as u64;
+ let pending_output_samples = self
+ .context
+ .delay()
+ .map(|d| d.output.max(0) as u64)
+ .unwrap_or(0);
+ let resampled_from_input = (input_samples as u64)
+ .saturating_mul(dst_rate)
+ .div_ceil(src_rate);
+ let capacity = pending_output_samples
+ .saturating_add(resampled_from_input)
+ .saturating_add(16)
+ .min(i32::MAX as u64) as usize;
+
+ let mut output = ffmpeg::frame::Audio::new(target.format, capacity, target.channel_layout);
if self.context.run(&input_frame, &mut output).is_err() {
return None;
}
+ if output.samples() == 0 {
+ return None;
+ }
+
Some(AudioFrame::new(output, timestamp))
}
}
@@ -128,9 +150,11 @@ impl AudioSource for Microphone {
let health_tx = ctx.health_tx().clone();
async move {
let source_info = feed_lock.audio_info();
- let audio_info = source_info.with_max_channels(MICROPHONE_TARGET_CHANNELS);
- let source_channels = source_info.channels;
- let target_channels = audio_info.channels;
+ let audio_info = source_info
+ .with_max_channels(MICROPHONE_TARGET_CHANNELS)
+ .with_sample_rate(AudioMixer::INFO.sample_rate)
+ .with_sample_format(AudioMixer::INFO.sample_format)
+ .with_channels(MICROPHONE_TARGET_CHANNELS as usize);
let is_wireless = source_info.is_wireless_transport;
let device_name = feed_lock.device_name().to_string();
let cancel = CancellationToken::new();
@@ -143,7 +167,11 @@ impl AudioSource for Microphone {
};
feed_lock
- .ask(microphone::AddSender(tx))
+ .ask(microphone::AddRecordingSender {
+ sender: tx,
+ health_tx: health_tx.clone(),
+ label: "microphone-feed:recording".to_string(),
+ })
.await
.map_err(|err| match err {
SendError::ActorNotRunning(_) => MicrophoneSourceError::ActorNotRunning,
@@ -163,8 +191,16 @@ impl AudioSource for Microphone {
let silence_chunk_samples =
(audio_info.rate() as f64 * SILENCE_CHUNK_DURATION.as_secs_f64()).ceil() as usize;
- let original_rate = source_info.sample_rate;
- let original_channels = source_info.channels as u16;
+ info!(
+ device = %device_name,
+ source_rate = source_info.sample_rate,
+ source_channels = source_info.channels,
+ source_format = ?source_info.sample_format,
+ target_rate = audio_info.sample_rate,
+ target_channels = audio_info.channels,
+ target_format = ?audio_info.sample_format,
+ "Microphone source configured"
+ );
tokio::spawn({
let frame_counter = mic_frame_counter.clone();
@@ -183,6 +219,7 @@ impl AudioSource for Microphone {
let mut next_reconnect_after = MIC_RECONNECT_AFTER;
let mut last_timestamp: Option<cap_timestamp::Timestamp> = None;
let mut last_frame_duration = SILENCE_CHUNK_DURATION;
+ let mut logged_current_source: Option<(u32, u16, SampleFormat)> = None;
loop {
let recv_result = tokio::select! {
@@ -207,68 +244,64 @@ impl AudioSource for Microphone {
emit_health(&health_tx, PipelineHealthEvent::SourceRestarted);
}
- let format_changed = frame.sample_rate != original_rate
- || frame.channels != original_channels;
-
- let needs_resampling = if format_changed {
- match &resampler {
- Some(r)
- if r.matches(
- frame.sample_rate,
- frame.channels,
- frame.format,
- ) =>
- {
- true
- }
- Some(_) | None => {
- info!(
- old_rate = original_rate,
- new_rate = frame.sample_rate,
- old_channels = original_channels,
- new_channels = frame.channels,
- "Microphone format changed, creating resampler"
- );
- resampler = MicResampler::create(
- frame.sample_rate,
- frame.channels,
- frame.format,
- &audio_info,
- );
- resampler.is_some()
- }
- }
- } else {
- if resampler.is_some() {
+ let target_matches_source = frame.sample_rate
+ == audio_info.sample_rate
+ && frame.channels as usize == audio_info.channels
+ && ffmpeg_sample_format_for(frame.format)
+ == Some(audio_info.sample_format);
+
+ let resampler_matches = resampler.as_ref().is_some_and(|r| {
+ r.matches(frame.sample_rate, frame.channels, frame.format)
+ });
+
+ if !target_matches_source && !resampler_matches {
+ let previous_source = logged_current_source;
+ let new_source =
+ (frame.sample_rate, frame.channels, frame.format);
+ if previous_source.is_none() {
info!(
- "Microphone format restored to original, dropping resampler"
+ source_rate = new_source.0,
+ source_channels = new_source.1,
+ source_format = ?new_source.2,
+ target_rate = audio_info.sample_rate,
+ target_channels = audio_info.channels,
+ target_format = ?audio_info.sample_format,
+ "Microphone: creating resampler for source→target"
);
- resampler = None;
- }
- false
- };
-
- let audio_frame = if needs_resampling {
- if let Some(ref mut ctx) = resampler {
- ctx.resample(
- &frame.data,
- frame.sample_rate,
- frame.channels,
- frame.format,
- frame.timestamp,
- )
} else {
- None
+ info!(
+ old = ?previous_source,
+ new = ?new_source,
+ "Microphone format changed mid-stream, rebuilding resampler"
+ );
}
- } else {
- let packed = maybe_downmix_channels(
- &frame.data,
+ resampler = MicResampler::create(
+ frame.sample_rate,
+ frame.channels,
frame.format,
- source_channels,
- target_channels,
+ &audio_info,
+ );
+ logged_current_source = Some(new_source);
+ } else if target_matches_source && resampler.is_some() {
+ info!(
+ "Microphone source now matches target, dropping resampler"
);
+ resampler = None;
+ logged_current_source =
+ Some((frame.sample_rate, frame.channels, frame.format));
+ }
+
+ let audio_frame = if let Some(ref mut ctx) = resampler {
+ ctx.resample(
+ &frame.data,
+ frame.sample_rate,
+ frame.channels,
+ frame.format,
+ frame.timestamp,
+ )
+ } else {
Some(AudioFrame::new(
- audio_info.wrap_frame(packed.as_ref()),
+ audio_info.wrap_frame(&frame.data),
frame.timestamp,
))
};
@@ -484,196 +517,119 @@ fn create_silence_frame(info: &AudioInfo, sample_count: usize) -> ffmpeg::frame:
frame
}
-fn maybe_downmix_channels<'a>(
- data: &'a [u8],
- format: SampleFormat,
- source_channels: usize,
- target_channels: usize,
-) -> Cow<'a, [u8]> {
- if target_channels == 0 || source_channels == 0 || target_channels >= source_channels {
- return Cow::Borrowed(data);
- }
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use cap_media_info::{Sample, Type};
- if target_channels == 1 {
- if let Some(samples) = downmix_to_mono(data, format, source_channels) {
- Cow::Owned(samples)
- } else {
- Cow::Borrowed(data)
- }
- } else {
- Cow::Borrowed(data)
+ #[test]
+ fn target_info_uses_output_rate_and_mono() {
+ let device_info = AudioInfo {
+ sample_format: Sample::F32(Type::Packed),
+ sample_rate: 32000,
+ channels: 2,
+ time_base: cap_media_info::FFRational(1, 1_000_000),
+ buffer_size: 1024,
+ is_wireless_transport: false,
+ };
+
+ let target = device_info
+ .with_max_channels(MICROPHONE_TARGET_CHANNELS)
+ .with_sample_rate(AudioMixer::INFO.sample_rate)
+ .with_sample_format(AudioMixer::INFO.sample_format)
+ .with_channels(MICROPHONE_TARGET_CHANNELS as usize);
+
+ assert_eq!(target.sample_rate, 48000);
+ assert_eq!(target.channels, 1);
+ assert_eq!(target.sample_format, AudioMixer::INFO.sample_format);
}
-}
-fn downmix_to_mono(data: &[u8], format: SampleFormat, source_channels: usize) -> Option<Vec<u8>> {
- let sample_size = sample_format_size(format)?;
+ #[test]
+ fn resampler_detects_mismatch_between_source_and_target() {
+ let target = AudioInfo::new_raw(Sample::F32(Type::Packed), 48000, 1);
- let frame_size = sample_size.checked_mul(source_channels)?;
- if frame_size == 0 || !data.len().is_multiple_of(frame_size) {
- return None;
+ assert!(MicResampler::create(32000, 1, SampleFormat::F32, &target).is_some());
+ assert!(MicResampler::create(44100, 2, SampleFormat::I16, &target).is_some());
+ assert!(MicResampler::create(96000, 2, SampleFormat::F32, &target).is_some());
}
- let frame_count = data.len() / frame_size;
- let mut out = vec![0u8; frame_count * sample_size];
-
- for (frame_idx, frame) in data.chunks(frame_size).enumerate() {
- let mono = average_frame_sample(format, frame, sample_size, source_channels)?;
- let start = frame_idx * sample_size;
- write_sample_from_f64(format, mono, &mut out[start..start + sample_size]);
+ #[test]
+ fn resampler_matches_detects_same_source() {
+ let target = AudioInfo::new_raw(Sample::F32(Type::Packed), 48000, 1);
+ let resampler =
+ MicResampler::create(32000, 1, SampleFormat::F32, &target).expect("resampler");
+ assert!(resampler.matches(32000, 1, SampleFormat::F32));
+ assert!(!resampler.matches(48000, 1, SampleFormat::F32));
+ assert!(!resampler.matches(32000, 2, SampleFormat::F32));
+ assert!(!resampler.matches(32000, 1, SampleFormat::I16));
}
- Some(out)
-}
+ #[test]
+ fn upsampling_preserves_total_duration() {
+ use cap_timestamp::{MachAbsoluteTimestamp, Timestamp};
-fn sample_format_size(format: SampleFormat) -> Option<usize> {
- Some(match format {
- SampleFormat::I8 | SampleFormat::U8 => 1,
- SampleFormat::I16 | SampleFormat::U16 => 2,
- SampleFormat::I32 | SampleFormat::U32 | SampleFormat::F32 => 4,
- SampleFormat::I64 | SampleFormat::U64 | SampleFormat::F64 => 8,
- _ => return None,
- })
-}
+ let target = AudioInfo::new_raw(Sample::F32(Type::Packed), 48000, 1);
+ let mut resampler =
+ MicResampler::create(32000, 2, SampleFormat::F32, &target).expect("resampler");
-fn average_frame_sample(
- format: SampleFormat,
- frame: &[u8],
- sample_size: usize,
- channels: usize,
-) -> Option<f64> {
- let mut sum = 0.0;
- for ch in 0..channels {
- let start = ch * sample_size;
- let end = start + sample_size;
- sum += sample_to_f64(format, &frame[start..end])?;
- }
+ const FRAME_SAMPLES: usize = 1024;
+ const FRAME_COUNT: usize = 64;
+ const CHANNELS: usize = 2;
- Some(sum / channels as f64)
-}
+ let ts = Timestamp::MachAbsoluteTime(MachAbsoluteTimestamp::now());
-fn sample_to_f64(format: SampleFormat, bytes: &[u8]) -> Option<f64> {
- match format {
- SampleFormat::I8 => bytes.first().copied().map(|v| v as i8 as f64),
- SampleFormat::U8 => bytes.first().copied().map(|v| v as f64),
- SampleFormat::I16 => {
- let mut buf = [0u8; 2];
- buf.copy_from_slice(bytes);
- Some(i16::from_ne_bytes(buf) as f64)
- }
- SampleFormat::U16 => {
- let mut buf = [0u8; 2];
- buf.copy_from_slice(bytes);
- Some(u16::from_ne_bytes(buf) as f64)
- }
- SampleFormat::I32 => {
- let mut buf = [0u8; 4];
- buf.copy_from_slice(bytes);
- Some(i32::from_ne_bytes(buf) as f64)
- }
- SampleFormat::U32 => {
- let mut buf = [0u8; 4];
- buf.copy_from_slice(bytes);
- Some(u32::from_ne_bytes(buf) as f64)
- }
- SampleFormat::I64 => {
- let mut buf = [0u8; 8];
- buf.copy_from_slice(bytes);
- Some(i64::from_ne_bytes(buf) as f64)
- }
- SampleFormat::U64 => {
- let mut buf = [0u8; 8];
- buf.copy_from_slice(bytes);
- Some(u64::from_ne_bytes(buf) as f64)
- }
- SampleFormat::F32 => {
- let mut buf = [0u8; 4];
- buf.copy_from_slice(bytes);
- Some(f32::from_ne_bytes(buf) as f64)
- }
- SampleFormat::F64 => {
- let mut buf = [0u8; 8];
- buf.copy_from_slice(bytes);
- Some(f64::from_ne_bytes(buf))
- }
- _ => None,
- }
-}
+ let payload_len_bytes = FRAME_SAMPLES * CHANNELS * std::mem::size_of::<f32>();
+ let payload = vec![0u8; payload_len_bytes];
-fn write_sample_from_f64(format: SampleFormat, value: f64, out: &mut [u8]) {
- match format {
- SampleFormat::I8 => {
- let sample = value.round().clamp(i8::MIN as f64, i8::MAX as f64) as i8;
- out[0] = sample as u8;
- }
- SampleFormat::U8 => {
- let sample = value.round().clamp(u8::MIN as f64, u8::MAX as f64) as u8;
- out[0] = sample;
- }
- SampleFormat::I16 => {
- let sample = value.round().clamp(i16::MIN as f64, i16::MAX as f64) as i16;
- out.copy_from_slice(&sample.to_ne_bytes());
- }
- SampleFormat::U16 => {
- let sample = value.round().clamp(u16::MIN as f64, u16::MAX as f64) as u16;
- out.copy_from_slice(&sample.to_ne_bytes());
- }
- SampleFormat::I32 => {
- let sample = value.round().clamp(i32::MIN as f64, i32::MAX as f64) as i32;
- out.copy_from_slice(&sample.to_ne_bytes());
- }
- SampleFormat::U32 => {
- let sample = value.round().clamp(u32::MIN as f64, u32::MAX as f64) as u32;
- out.copy_from_slice(&sample.to_ne_bytes());
- }
- SampleFormat::I64 => {
- let sample = value.round().clamp(i64::MIN as f64, i64::MAX as f64) as i64;
- out.copy_from_slice(&sample.to_ne_bytes());
+ let mut produced: u64 = 0;
+ for _ in 0..FRAME_COUNT {
+ if let Some(frame) = resampler.resample(&payload, 32000, 2, SampleFormat::F32, ts) {
+ produced += frame.samples() as u64;
+ }
}
- SampleFormat::U64 => {
- let sample = value.round().clamp(u64::MIN as f64, u64::MAX as f64) as u64;
- out.copy_from_slice(&sample.to_ne_bytes());
- }
- SampleFormat::F32 => {
- let sample = value as f32;
- out.copy_from_slice(&sample.to_ne_bytes());
- }
- SampleFormat::F64 => {
- out.copy_from_slice(&value.to_ne_bytes());
- }
- _ => {}
- }
-}
-#[cfg(test)]
-mod tests {
- use super::*;
+ let consumed_input_samples = (FRAME_SAMPLES * FRAME_COUNT) as u64;
+ let expected_output_samples = consumed_input_samples * 48_000 / 32_000;
- #[test]
- fn downmixes_stereo_f32_to_mono() {
- let frames = [(0.5f32, -0.25f32), (1.0f32, 1.0f32)];
- let mut data = Vec::new();
+ let lower_bound = expected_output_samples * 99 / 100;
+ assert!(
+ produced >= lower_bound,
+ "upsampling lost samples: produced={produced}, expected≈{expected_output_samples}, \
+ lower_bound={lower_bound}"
+ );
+ }
- for (left, right) in frames {
- data.extend_from_slice(&left.to_ne_bytes());
- data.extend_from_slice(&right.to_ne_bytes());
+ #[test]
+ fn downsampling_preserves_total_duration() {
+ use cap_timestamp::{MachAbsoluteTimestamp, Timestamp};
+
+ let target = AudioInfo::new_raw(Sample::F32(Type::Packed), 48000, 1);
+ let mut resampler =
+ MicResampler::create(96000, 2, SampleFormat::F32, &target).expect("resampler");
+
+ const FRAME_SAMPLES: usize = 1024;
+ const FRAME_COUNT: usize = 64;
+ const CHANNELS: usize = 2;
+
+ let ts = Timestamp::MachAbsoluteTime(MachAbsoluteTimestamp::now());
+ let payload_len_bytes = FRAME_SAMPLES * CHANNELS * std::mem::size_of::<f32>();
+ let payload = vec![0u8; payload_len_bytes];
+
+ let mut produced: u64 = 0;
+ for _ in 0..FRAME_COUNT {
+ if let Some(frame) = resampler.resample(&payload, 96000, 2, SampleFormat::F32, ts) {
+ produced += frame.samples() as u64;
+ }
}
- let downmixed = maybe_downmix_channels(&data, SampleFormat::F32, 2, 1);
- let owned = downmixed.into_owned();
- assert_eq!(owned.len(), frames.len() * std::mem::size_of::<f32>());
-
- let first = f32::from_ne_bytes(owned[0..4].try_into().unwrap());
- let second = f32::from_ne_bytes(owned[4..8].try_into().unwrap());
+ let consumed_input_samples = (FRAME_SAMPLES * FRAME_COUNT) as u64;
+ let expected_output_samples = consumed_input_samples * 48_000 / 96_000;
- assert!((first - 0.125).abs() < f32::EPSILON);
- assert!((second - 1.0).abs() < f32::EPSILON);
- }
-
- #[test]
- fn leaves_mono_buffers_untouched() {
- let sample = 0.75f32;
- let data = sample.to_ne_bytes().to_vec();
- let result = maybe_downmix_channels(&data, SampleFormat::F32, 1, 1);
- assert!(matches!(result, Cow::Borrowed(_)));
+ let lower_bound = expected_output_samples * 99 / 100;
+ assert!(
+ produced >= lower_bound,
+ "downsampling lost samples: produced={produced}, expected≈{expected_output_samples}, \
+ lower_bound={lower_bound}"
+ );
}
}
diff --git a/crates/recording/src/sources/screen_capture/macos.rs b/crates/recording/src/sources/screen_capture/macos.rs
index d23642131..e2d5f3f34 100644
--- a/crates/recording/src/sources/screen_capture/macos.rs
+++ b/crates/recording/src/sources/screen_capture/macos.rs
@@ -300,6 +300,9 @@ impl ScreenCaptureConfig<CMSampleBufferCapture> {
PixelBufferCopier::new(expected_width, expected_height),
));
+ let (stall_health_tx, stall_health_rx) =
+ tokio::sync::mpsc::channel::<output_pipeline::PipelineHealthEvent>(32);
+
let rebuild_params = Arc::new(CapturerRebuildParams {
display_id: self.config.display.clone(),
config: self.config.clone(),
@@ -317,6 +320,7 @@ impl ScreenCaptureConfig<CMSampleBufferCapture> {
scaling_logged: scaling_logged.clone(),
scaled_frame_count: scaled_frame_count.clone(),
pixel_buffer_copier: pixel_buffer_copier.clone(),
+ stall_health_tx: stall_health_tx.clone(),
});
let builder = scap_screencapturekit::Capturer::builder(content_filter, settings)
@@ -325,6 +329,7 @@ impl ScreenCaptureConfig<CMSampleBufferCapture> {
let drop_counter = drop_counter.clone();
let sys_audio_drop_counter = system_audio_drop_counter.clone();
let sys_audio_frame_counter = system_audio_frame_counter.clone();
+ let stall_health_tx = stall_health_tx.clone();
move |frame| {
let sample_buffer = frame.sample_buf();
@@ -428,14 +433,20 @@ impl ScreenCaptureConfig<CMSampleBufferCapture> {
video_frame_count.fetch_add(1, atomic::Ordering::Relaxed);
- if video_tx
- .try_send(VideoFrame {
+ match output_pipeline::send_with_stall_budget_flume(
+ &video_tx,
+ VideoFrame {
sample_buf: final_sample_buf,
timestamp,
- })
- .is_err()
- {
- drop_counter.fetch_add(1, atomic::Ordering::Relaxed);
+ },
+ "screen-video",
+ &stall_health_tx,
+ ) {
+ output_pipeline::StallSendOutcome::Sent => {}
+ output_pipeline::StallSendOutcome::StalledAndDropped { .. }
+ | output_pipeline::StallSendOutcome::Disconnected => {
+ drop_counter.fetch_add(1, atomic::Ordering::Relaxed);
+ }
}
}
scap_screencapturekit::Frame::Audio(_) => {
@@ -470,12 +481,18 @@ impl ScreenCaptureConfig<CMSampleBufferCapture> {
);
}
- match audio_tx.try_send(AudioFrame::new(frame, timestamp)) {
- Ok(()) => {
+ match output_pipeline::send_with_stall_budget_futures(
+ audio_tx,
+ AudioFrame::new(frame, timestamp),
+ "screen-system-audio",
+ &stall_health_tx,
+ ) {
+ output_pipeline::StallSendOutcome::Sent => {
sys_audio_frame_counter
.fetch_add(1, atomic::Ordering::Relaxed);
}
- Err(_) => {
+ output_pipeline::StallSendOutcome::StalledAndDropped { .. }
+ | output_pipeline::StallSendOutcome::Disconnected => {
sys_audio_drop_counter
.fetch_add(1, atomic::Ordering::Relaxed);
}
@@ -511,6 +528,7 @@ impl ScreenCaptureConfig<CMSampleBufferCapture> {
cancel_token: cancel_token.clone(),
drop_guard: cancel_token.drop_guard(),
rebuild_params: rebuild_params.clone(),
+ stall_health_rx: Some(stall_health_rx),
},
audio_rx.map(|rx| {
SystemAudioSourceConfig(
@@ -612,6 +630,7 @@ pub struct VideoSourceConfig {
video_frame_counter: Arc<AtomicU32>,
drop_counter: Arc<AtomicU64>,
rebuild_params: Arc<CapturerRebuildParams>,
+ stall_health_rx: Option<tokio::sync::mpsc::Receiver<output_pipeline::PipelineHealthEvent>>,
}
pub struct VideoSource {
inner: ChannelVideoSource<VideoFrame>,
@@ -645,10 +664,28 @@ impl output_pipeline::VideoSource for VideoSource {
video_frame_counter,
drop_counter,
rebuild_params,
+ stall_health_rx,
} = config;
let monitor_cancel = cancel_token.clone();
let health_tx = ctx.health_tx().clone();
+
+ if let Some(mut stall_rx) = stall_health_rx {
+ let forward_tx = ctx.health_tx().clone();
+ let forward_cancel = cancel_token.clone();
+ ctx.tasks()
+ .spawn("screen-capture-stall-forwarder", async move {
+ loop {
+ tokio::select! {
+ _ = forward_cancel.cancelled() => break Ok(()),
+ event = stall_rx.recv() => match event {
+ Some(ev) => output_pipeline::emit_health(&forward_tx, ev),
+ None => break Ok(()),
+ }
+ }
+ }
+ });
+ }
let active_capturer: Arc<Mutex<Option<Capturer>>> = Arc::new(Mutex::new(None));
let active_capturer_for_stop = active_capturer.clone();
let original_capturer = capturer.clone();
@@ -709,6 +746,23 @@ impl output_pipeline::VideoSource for VideoSource {
break Ok(());
}
+ if Display::from_id(&rebuild_params.display_id).is_none() {
+ error!(
+ display_id = ?rebuild_params.display_id,
+ "Capture target display is gone; aborting restart"
+ );
+ output_pipeline::emit_health(
+ &health_tx,
+ output_pipeline::PipelineHealthEvent::CaptureTargetLost {
+ target: "display".to_string(),
+ },
+ );
+ return Err(anyhow!(
+ "Capture target display disappeared: {:?}",
+ rebuild_params.display_id
+ ));
+ }
+
match rebuild_capturer(&rebuild_params).await {
Ok(new_capturer) => {
if let Ok(mut guard) = active_capturer.lock() {
@@ -793,6 +847,7 @@ impl output_pipeline::VideoSource for VideoSource {
output_pipeline::emit_health(
&health_tx,
output_pipeline::PipelineHealthEvent::FrameDropRateHigh {
+ source: "screen-video".to_string(),
rate_pct: drop_rate,
},
);
@@ -884,6 +939,7 @@ struct CapturerRebuildParams {
scaling_logged: Arc<AtomicBool>,
scaled_frame_count: Arc<AtomicU64>,
pixel_buffer_copier: Arc<Mutex<Option<PixelBufferCopier>>>,
+ stall_health_tx: output_pipeline::HealthSender,
}
unsafe impl Send for CapturerRebuildParams {}
@@ -980,6 +1036,7 @@ async fn rebuild_capturer(params: &CapturerRebuildParams) -> anyhow::Result<Capt
let pixel_buffer_copier = params.pixel_buffer_copier.clone();
let sys_audio_drop_counter = params.system_audio_drop_counter.clone();
let sys_audio_frame_counter = params.system_audio_frame_counter.clone();
+ let stall_health_tx = params.stall_health_tx.clone();
move |frame| {
let sample_buffer = frame.sample_buf();
@@ -1082,14 +1139,20 @@ async fn rebuild_capturer(params: &CapturerRebuildParams) -> anyhow::Result<Capt
video_frame_count.fetch_add(1, atomic::Ordering::Relaxed);
- if video_tx
- .try_send(VideoFrame {
+ match output_pipeline::send_with_stall_budget_flume(
+ &video_tx,
+ VideoFrame {
sample_buf: final_sample_buf,
timestamp,
- })
- .is_err()
- {
- drop_counter.fetch_add(1, atomic::Ordering::Relaxed);
+ },
+ "screen-video",
+ &stall_health_tx,
+ ) {
+ output_pipeline::StallSendOutcome::Sent => {}
+ output_pipeline::StallSendOutcome::StalledAndDropped { .. }
+ | output_pipeline::StallSendOutcome::Disconnected => {
+ drop_counter.fetch_add(1, atomic::Ordering::Relaxed);
+ }
}
}
scap_screencapturekit::Frame::Audio(_) => {
@@ -1124,12 +1187,18 @@ async fn rebuild_capturer(params: &CapturerRebuildParams) -> anyhow::Result<Capt
);
}
- match audio_tx.try_send(AudioFrame::new(frame, timestamp)) {
- Ok(()) => {
+ match output_pipeline::send_with_stall_budget_futures(
+ audio_tx,
+ AudioFrame::new(frame, timestamp),
+ "screen-system-audio",
+ &stall_health_tx,
+ ) {
+ output_pipeline::StallSendOutcome::Sent => {
sys_audio_frame_counter
.fetch_add(1, atomic::Ordering::Relaxed);
}
- Err(_) => {
+ output_pipeline::StallSendOutcome::StalledAndDropped { .. }
+ | output_pipeline::StallSendOutcome::Disconnected => {
sys_audio_drop_counter
.fetch_add(1, atomic::Ordering::Relaxed);
}
diff --git a/crates/recording/src/sources/screen_capture/windows.rs b/crates/recording/src/sources/screen_capture/windows.rs
index 5ff607716..9063c71c1 100644
--- a/crates/recording/src/sources/screen_capture/windows.rs
+++ b/crates/recording/src/sources/screen_capture/windows.rs
@@ -428,11 +428,37 @@ enum VideoControl {
Start(oneshot::Sender<anyhow::Result<()>>),
Stop(oneshot::Sender<anyhow::Result<()>>),
Restart,
+ RecreateDevice,
}
const MAX_CAPTURE_RESTARTS: u32 = 3;
const RESTART_DELAY: Duration = Duration::from_secs(1);
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+enum CaptureClosureKind {
+ DeviceRemoved { hresult: i32 },
+ TargetLost,
+ Transient,
+}
+
+fn classify_capture_closure(device: &ID3D11Device) -> CaptureClosureKind {
+ unsafe {
+ let removed_hr = device.GetDeviceRemovedReason();
+ if removed_hr.is_err() {
+ return CaptureClosureKind::DeviceRemoved {
+ hresult: removed_hr.0,
+ };
+ }
+ }
+ CaptureClosureKind::TargetLost
+}
+
+#[derive(Debug, Clone)]
+struct CaptureClosureEvent {
+ kind: CaptureClosureKind,
+ message: String,
+}
+
struct CreateCapturerParams<'a> {
display_id: &'a DisplayId,
settings: &'a scap_direct3d::Settings,
@@ -445,11 +471,12 @@ struct CreateCapturerParams<'a> {
frame_scaler: Arc<Mutex<WindowsFrameScaler>>,
scaling_logged: Arc<AtomicBool>,
scaled_frame_count: Arc<AtomicU32>,
+ stall_health_tx: output_pipeline::HealthSender,
}
fn create_d3d_capturer(
params: &CreateCapturerParams,
- error_tx: &mpsc::Sender<anyhow::Error>,
+ error_tx: &mpsc::Sender<CaptureClosureEvent>,
) -> anyhow::Result<scap_direct3d::Capturer> {
let capture_item = Display::from_id(params.display_id)
.ok_or_else(|| anyhow!("Display not found for ID: {:?}", params.display_id))?
@@ -469,6 +496,7 @@ fn create_d3d_capturer(
let frame_scaler = params.frame_scaler.clone();
let scaling_logged = params.scaling_logged.clone();
let scaled_frame_count = params.scaled_frame_count.clone();
+ let stall_health_tx = params.stall_health_tx.clone();
move |frame| {
let timestamp = frame.inner().SystemRelativeTime()?;
let timestamp = Timestamp::PerformanceCounter(PerformanceCounterTimestamp::new(
@@ -524,14 +552,20 @@ fn create_d3d_capturer(
ScreenFrame::Captured(frame)
};
- match tx.try_send(VideoFrame {
- frame: screen_frame,
- timestamp,
- }) {
- Ok(()) => {
+ match output_pipeline::send_with_stall_budget_futures(
+ &mut tx,
+ VideoFrame {
+ frame: screen_frame,
+ timestamp,
+ },
+ "screen-video",
+ &stall_health_tx,
+ ) {
+ output_pipeline::StallSendOutcome::Sent => {
video_frame_counter.fetch_add(1, atomic::Ordering::Relaxed);
}
- Err(_) => {
+ output_pipeline::StallSendOutcome::StalledAndDropped { .. }
+ | output_pipeline::StallSendOutcome::Disconnected => {
video_drop_counter.fetch_add(1, atomic::Ordering::Relaxed);
}
}
@@ -540,8 +574,17 @@ fn create_d3d_capturer(
},
{
let mut err_tx = error_tx.clone();
+ let device_for_callback = params.d3d_device.clone();
move || {
- drop(err_tx.try_send(anyhow!("closed")));
+ let kind = classify_capture_closure(&device_for_callback);
+ let message = match kind {
+ CaptureClosureKind::DeviceRemoved { hresult } => {
+ format!("d3d11 device removed (hresult=0x{hresult:08x})")
+ }
+ CaptureClosureKind::TargetLost => "capture target lost".to_string(),
+ CaptureClosureKind::Transient => "capture closed".to_string(),
+ };
+ drop(err_tx.try_send(CaptureClosureEvent { kind, message }));
Ok(())
}
},
@@ -567,8 +610,8 @@ impl output_pipeline::VideoSource for VideoSource {
where
Self: Sized,
{
- let (error_tx, mut error_rx) = mpsc::channel(4);
- let (ctrl_tx, ctrl_rx) = std::sync::mpsc::sync_channel::<VideoControl>(2);
+ let (error_tx, mut error_rx) = mpsc::channel::<CaptureClosureEvent>(4);
+ let (ctrl_tx, ctrl_rx) = std::sync::mpsc::sync_channel::<VideoControl>(4);
let monitor_ctrl_tx = ctrl_tx.clone();
let tokio_rt = tokio::runtime::Handle::current();
@@ -599,22 +642,26 @@ impl output_pipeline::VideoSource for VideoSource {
let video_drop_counter: Arc<AtomicU32> = Arc::new(AtomicU32::new(0));
let cancel_token = CancellationToken::new();
let mut error_tx = error_tx;
-
- let capturer_params = CreateCapturerParams {
- display_id: &display_id,
- settings: &settings,
- d3d_device: &d3d_device,
- video_tx: &video_tx,
- video_frame_counter: &video_frame_counter,
- video_drop_counter: &video_drop_counter,
- expected_width,
- expected_height,
- frame_scaler: frame_scaler.clone(),
- scaling_logged: scaling_logged.clone(),
- scaled_frame_count: scaled_frame_count.clone(),
+ let mut d3d_device = d3d_device;
+
+ let build_params = |device: &ID3D11Device| -> CreateCapturerParams<'_> {
+ CreateCapturerParams {
+ display_id: &display_id,
+ settings: &settings,
+ d3d_device: device,
+ video_tx: &video_tx,
+ video_frame_counter: &video_frame_counter,
+ video_drop_counter: &video_drop_counter,
+ expected_width,
+ expected_height,
+ frame_scaler: frame_scaler.clone(),
+ scaling_logged: scaling_logged.clone(),
+ scaled_frame_count: scaled_frame_count.clone(),
+ stall_health_tx: stats_health_tx.clone(),
+ }
};
- let mut capturer = match create_d3d_capturer(&capturer_params, &error_tx) {
+ let mut capturer = match create_d3d_capturer(&build_params(&d3d_device), &error_tx) {
Ok(c) => {
trace!("D3D capturer created successfully");
Some(c)
@@ -663,6 +710,7 @@ impl output_pipeline::VideoSource for VideoSource {
output_pipeline::emit_health(
&stats_health_tx,
output_pipeline::PipelineHealthEvent::FrameDropRateHigh {
+ source: "screen-video".to_string(),
rate_pct: drop_pct,
},
);
@@ -701,6 +749,55 @@ impl output_pipeline::VideoSource for VideoSource {
}
break;
}
+ Ok(VideoControl::RecreateDevice) => {
+ warn!("Recreating D3D device after device-lost");
+ if let Some(mut old) = capturer.take() {
+ let _ = old.stop();
+ drop(old);
+ }
+ match crate::capture_pipeline::create_d3d_device() {
+ Ok(new_device) => {
+ info!("Recreated D3D device after device-lost");
+ d3d_device = new_device;
+ }
+ Err(e) => {
+ error!(error = %e, "Failed to recreate D3D device");
+ let _ = error_tx.try_send(CaptureClosureEvent {
+ kind: CaptureClosureKind::Transient,
+ message: format!("recreate_device_failed: {e}"),
+ });
+ continue;
+ }
+ }
+ match create_d3d_capturer(&build_params(&d3d_device), &error_tx) {
+ Ok(mut new_cap) => match new_cap.start() {
+ Ok(()) => {
+ info!(
+ "Windows screen capture resumed after device recreation"
+ );
+ output_pipeline::emit_health(
+ &stats_health_tx,
+ output_pipeline::PipelineHealthEvent::SourceRestarted,
+ );
+ capturer = Some(new_cap);
+ }
+ Err(e) => {
+ warn!(error = %e, "Failed to start capturer after device recreation");
+ let _ = error_tx.try_send(CaptureClosureEvent {
+ kind: CaptureClosureKind::Transient,
+ message: format!("recreate_start_failed: {e}"),
+ });
+ }
+ },
+ Err(e) => {
+ warn!(error = %e, "Failed to recreate capturer after device recreation");
+ let _ = error_tx.try_send(CaptureClosureEvent {
+ kind: CaptureClosureKind::Transient,
+ message: format!("recreate_capturer_failed: {e}"),
+ });
+ }
+ }
+ }
Ok(VideoControl::Restart) => {
info!("Restarting Windows screen capture");
output_pipeline::emit_health(
@@ -712,7 +809,7 @@ impl output_pipeline::VideoSource for VideoSource {
drop(old);
}
- match create_d3d_capturer(&capturer_params, &error_tx) {
+ match create_d3d_capturer(&build_params(&d3d_device), &error_tx) {
Ok(mut new_cap) => match new_cap.start() {
Ok(()) => {
let count = restart_counter
@@ -730,14 +827,18 @@ impl output_pipeline::VideoSource for VideoSource {
}
Err(e) => {
warn!(error = %e, "Failed to start restarted capturer");
- let _ =
- error_tx.try_send(anyhow!("restart_start_failed: {e}"));
+ let _ = error_tx.try_send(CaptureClosureEvent {
+ kind: CaptureClosureKind::Transient,
+ message: format!("restart_start_failed: {e}"),
+ });
}
},
Err(e) => {
warn!(error = %e, "Failed to recreate capturer");
- let _ =
- error_tx.try_send(anyhow!("restart_create_failed: {e}"));
+ let _ = error_tx.try_send(CaptureClosureEvent {
+ kind: CaptureClosureKind::Transient,
+ message: format!("restart_create_failed: {e}"),
+ });
}
}
}
@@ -752,28 +853,63 @@ impl output_pipeline::VideoSource for VideoSource {
}
});
+ let monitor_health_tx = ctx.health_tx().clone();
ctx.tasks().spawn("d3d-capture", async move {
let mut restart_count = 0u32;
- while let Some(err) = error_rx.next().await {
+ while let Some(event) = error_rx.next().await {
+ let is_device_lost = matches!(event.kind, CaptureClosureKind::DeviceRemoved { .. });
+ match event.kind {
+ CaptureClosureKind::DeviceRemoved { hresult } => {
+ error!(
+ hresult = format!("0x{:08x}", hresult),
+ message = %event.message,
+ "Windows D3D device removed"
+ );
+ output_pipeline::emit_health(
+ &monitor_health_tx,
+ output_pipeline::PipelineHealthEvent::DeviceLost {
+ subsystem: "d3d11".to_string(),
+ },
+ );
+ }
+ CaptureClosureKind::TargetLost => {
+ warn!(message = %event.message, "Windows capture target lost");
+ output_pipeline::emit_health(
+ &monitor_health_tx,
+ output_pipeline::PipelineHealthEvent::CaptureTargetLost {
+ target: "display".to_string(),
+ },
+ );
+ return Err(anyhow!("Windows capture target lost: {}", event.message));
+ }
+ CaptureClosureKind::Transient => {}
+ }
+
if restart_count < MAX_CAPTURE_RESTARTS {
restart_count += 1;
warn!(
restart_count,
max_restarts = MAX_CAPTURE_RESTARTS,
- error = %err,
+ message = %event.message,
"Windows capture interrupted, attempting restart"
);
tokio::time::sleep(RESTART_DELAY).await;
- if monitor_ctrl_tx.try_send(VideoControl::Restart).is_err() {
+ let control = if is_device_lost {
+ VideoControl::RecreateDevice
+ } else {
+ VideoControl::Restart
+ };
+ if monitor_ctrl_tx.try_send(control).is_err() {
return Err(anyhow!("Failed to send restart signal to capture thread"));
}
continue;
}
return Err(anyhow!(
- "Windows screen capture failed after {} restart attempts: {err}",
- MAX_CAPTURE_RESTARTS
+ "Windows screen capture failed after {} restart attempts: {}",
+ MAX_CAPTURE_RESTARTS,
+ event.message
));
}
@@ -868,8 +1004,29 @@ impl SystemAudioResampler {
input: ffmpeg::frame::Audio,
timestamp: Timestamp,
) -> Option<AudioFrame> {
- let mut output = ffmpeg::frame::Audio::empty();
+ let input_samples = input.samples();
+ let src_rate = self.context.input().rate.max(1) as u64;
+ let target = *self.context.output();
+ let dst_rate = target.rate.max(1) as u64;
+
+ let pending_output_samples = self
+ .context
+ .delay()
+ .map(|d| d.output.max(0) as u64)
+ .unwrap_or(0);
+ let resampled_from_input = (input_samples as u64)
+ .saturating_mul(dst_rate)
+ .div_ceil(src_rate);
+ let capacity = pending_output_samples
+ .saturating_add(resampled_from_input)
+ .saturating_add(16)
+ .min(i32::MAX as u64) as usize;
+
+ let mut output = ffmpeg::frame::Audio::new(target.format, capacity, target.channel_layout);
self.context.run(&input, &mut output).ok()?;
+ if output.samples() == 0 {
+ return None;
+ }
Some(AudioFrame::new(output, timestamp))
}
}
@@ -897,22 +1054,24 @@ fn create_system_audio_capturer(
drop_counter: Arc<AtomicU32>,
error_flag: Arc<AtomicBool>,
last_timestamp: Arc<std::sync::Mutex<Option<Timestamp>>>,
- original_info: AudioInfo,
+ _target_info: AudioInfo,
+ stall_health_tx: output_pipeline::HealthSender,
) -> Result<scap_cpal::Capturer, scap_cpal::CapturerError> {
- let new_info = Direct3DCapture::audio_info();
- let needs_resample = new_info.sample_rate != original_info.sample_rate
- || new_info.channels != original_info.channels
- || new_info.sample_format != original_info.sample_format;
+ let device_info = Direct3DCapture::audio_info();
+ let target_info = crate::sources::audio_mixer::AudioMixer::INFO;
+ let device_differs_from_target = !device_info.matches_format(&target_info);
- let mut resampler = if needs_resample {
+ let mut resampler = if device_differs_from_target {
info!(
- original_rate = original_info.sample_rate,
- new_rate = new_info.sample_rate,
- original_channels = original_info.channels,
- new_channels = new_info.channels,
- "System audio device format differs from original, creating resampler"
+ device_rate = device_info.sample_rate,
+ device_channels = device_info.channels,
+ device_format = ?device_info.sample_format,
+ target_rate = target_info.sample_rate,
+ target_channels = target_info.channels,
+ target_format = ?target_info.sample_format,
+ "System audio device differs from output target, creating resampler"
);
- SystemAudioResampler::create(&new_info, &original_info)
+ SystemAudioResampler::create(&device_info, &target_info)
} else {
None
};
@@ -925,6 +1084,18 @@ fn create_system_audio_capturer(
move |data, info, config| {
use scap_ffmpeg::*;
+ thread_local! {
+ static MMCSS_HANDLE: std::cell::RefCell<
+ Option<cap_mediafoundation_utils::MmcssAudioHandle>,
+ > = const { std::cell::RefCell::new(None) };
+ }
+ MMCSS_HANDLE.with(|cell| {
+ let mut h = cell.borrow_mut();
+ if h.is_none() {
+ *h = cap_mediafoundation_utils::MmcssAudioHandle::register_audio();
+ }
+ });
+
let timestamp = Timestamp::from_cpal(info.timestamp().capture);
let raw_frame = data.as_ffmpeg(config);
@@ -944,27 +1115,18 @@ fn create_system_audio_capturer(
*guard = Some(timestamp);
}
- const MAX_RETRIES: u32 = 3;
- const RETRY_DELAY_US: u64 = 500;
-
- let mut retries = 0;
- let mut current_frame = Some(frame);
-
- while let Some(f) = current_frame.take() {
- match tx.try_send(f) {
- Ok(()) => {
- frame_counter.fetch_add(1, atomic::Ordering::Relaxed);
- break;
- }
- Err(err) if err.is_full() && retries < MAX_RETRIES => {
- retries += 1;
- std::thread::sleep(Duration::from_micros(RETRY_DELAY_US));
- current_frame = Some(err.into_inner());
- }
- Err(_) => {
- drop_counter.fetch_add(1, atomic::Ordering::Relaxed);
- break;
- }
+ match output_pipeline::send_with_stall_budget_futures(
+ &mut tx,
+ frame,
+ "screen-system-audio",
+ &stall_health_tx,
+ ) {
+ output_pipeline::StallSendOutcome::Sent => {
+ frame_counter.fetch_add(1, atomic::Ordering::Relaxed);
+ }
+ output_pipeline::StallSendOutcome::StalledAndDropped { .. }
+ | output_pipeline::StallSendOutcome::Disconnected => {
+ drop_counter.fetch_add(1, atomic::Ordering::Relaxed);
}
}
}
@@ -1000,7 +1162,7 @@ impl output_pipeline::AudioSource for SystemAudioSource {
}
});
- let audio_info = Direct3DCapture::audio_info();
+ let audio_info = crate::sources::audio_mixer::AudioMixer::INFO;
let device_name = get_current_device_name();
let frame_counter: Arc<AtomicU32> = Arc::new(AtomicU32::new(0));
@@ -1011,6 +1173,7 @@ impl output_pipeline::AudioSource for SystemAudioSource {
let device_switch_count: Arc<AtomicU32> = Arc::new(AtomicU32::new(0));
let silence_frame_count: Arc<AtomicU32> = Arc::new(AtomicU32::new(0));
+ let stall_health_tx_for_setup = ctx.health_tx().clone();
let setup_result = create_system_audio_capturer(
tx.clone(),
frame_counter.clone(),
@@ -1018,6 +1181,7 @@ impl output_pipeline::AudioSource for SystemAudioSource {
error_flag.clone(),
last_timestamp.clone(),
audio_info,
+ stall_health_tx_for_setup,
);
let state = Arc::new(std::sync::Mutex::new(CapturerState {
@@ -1026,6 +1190,7 @@ impl output_pipeline::AudioSource for SystemAudioSource {
device_name,
}));
+ let stall_health_tx_for_watcher = ctx.health_tx().clone();
ctx.tasks().spawn_thread("system-audio-watcher", {
let state = state.clone();
let mut watcher_tx = tx.clone();
@@ -1036,6 +1201,7 @@ impl output_pipeline::AudioSource for SystemAudioSource {
let cancel = cancel_token.clone();
let device_switch_count = device_switch_count.clone();
let silence_frame_count = silence_frame_count.clone();
+ let stall_health_tx = stall_health_tx_for_watcher;
move || {
let silence_chunk_samples = (audio_info.sample_rate as f64
@@ -1094,10 +1260,21 @@ impl output_pipeline::AudioSource for SystemAudioSource {
ts = ts + chunk_duration;
let silence = create_silence_frame(&audio_info, silence_chunk_samples);
let frame = AudioFrame::new(silence, ts);
- if watcher_tx.try_send(frame).is_err() {
- break;
+ match output_pipeline::send_with_stall_budget_futures(
+ &mut watcher_tx,
+ frame,
+ "screen-system-audio:silence-fill",
+ &stall_health_tx,
+ ) {
+ output_pipeline::StallSendOutcome::Sent => {
+ silence_frame_count.fetch_add(1, atomic::Ordering::Relaxed);
+ }
+ output_pipeline::StallSendOutcome::StalledAndDropped { .. } => {
+ drop_counter.fetch_add(1, atomic::Ordering::Relaxed);
+ break;
+ }
+ output_pipeline::StallSendOutcome::Disconnected => break,
}
- silence_frame_count.fetch_add(1, atomic::Ordering::Relaxed);
}
if let Ok(mut lt) = last_timestamp.lock() {
*lt = Some(ts);
@@ -1111,6 +1288,7 @@ impl output_pipeline::AudioSource for SystemAudioSource {
error_flag.clone(),
last_timestamp.clone(),
audio_info,
+ stall_health_tx.clone(),
) {
Ok(new_capturer) => {
if was_started {