Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

fix: bound recording device setup and native capture lifetimes

Richie McIlroyea4a2e985988
diff --git a/crates/camera-avfoundation/src/lib.rs b/crates/camera-avfoundation/src/lib.rs
index dcbc84a05..defb855ea 100644
--- a/crates/camera-avfoundation/src/lib.rs
+++ b/crates/camera-avfoundation/src/lib.rs
@@ -105,11 +105,46 @@ impl CallbackOutputDelegateInner {
}
define_obj_type!(
- pub CallbackOutputDelegate + VideoDataOutputSampleBufDelegateImpl,
+ pub CallbackOutputDelegate + VideoDataOutputSampleBufDelegateImpl + OutputDelegateDeallocation,
CallbackOutputDelegateInner,
OUTPUT_DELEGATE
);
+trait OutputDelegateDeallocation {
+ fn cls_add_methods(cls: &objc::Class<objc::Id>) {
+ extern "C" fn dealloc(delegate: &mut CallbackOutputDelegate, selector: &objc::Sel) {
+ let object = delegate as *mut CallbackOutputDelegate;
+ unsafe {
+ let superclass_dealloc: unsafe extern "C" fn(
+ *mut CallbackOutputDelegate,
+ &objc::Sel,
+ ) = std::mem::transmute(objc::NS_OBJECT.method_impl(selector));
+ std::ptr::drop_in_place(delegate.inner_mut());
+ superclass_dealloc(object, selector);
+ }
+ }
+
+ // The pinned cidre macro drops only the Rust payload. Its later
+ // class_addMethod cannot replace this complete NSObject deallocator.
+ let added = unsafe {
+ objc::class_addMethod(
+ cls,
+ objc::sel_reg_name(c"dealloc".as_ptr().cast()),
+ std::mem::transmute::<
+ extern "C" fn(&mut CallbackOutputDelegate, &objc::Sel),
+ extern "C" fn(),
+ >(dealloc),
+ c"v@:".as_ptr().cast(),
+ )
+ };
+ assert!(added, "Camera delegate deallocator already registered");
+ }
+
+ fn cls_add_protocol(_: &objc::Class<objc::Id>) {}
+}
+
+impl OutputDelegateDeallocation for CallbackOutputDelegate {}
+
impl VideoDataOutputSampleBufDelegate for CallbackOutputDelegate {}
#[objc::add_methods]
@@ -238,3 +273,63 @@ impl<'a> Drop for BaseAddrLockGuard<'a> {
let _ = unsafe { self.0.unlock_lock_base_addr(self.1) };
}
}
+
+#[cfg(test)]
+mod deallocation_tests {
+ use super::*;
+ use std::{
+ ffi::c_void,
+ sync::{
+ Arc,
+ atomic::{AtomicUsize, Ordering},
+ },
+ };
+
+ #[link(name = "objc")]
+ unsafe extern "C" {
+ #[link_name = "objc_setAssociatedObject"]
+ fn set_associated_object(
+ object: *const c_void,
+ key: *const c_void,
+ value: *const c_void,
+ policy: usize,
+ );
+ }
+
+ static ASSOCIATION_KEY: u8 = 0;
+
+ struct DropCounter(Arc<AtomicUsize>);
+
+ impl Drop for DropCounter {
+ fn drop(&mut self) {
+ self.0.fetch_add(1, Ordering::SeqCst);
+ }
+ }
+
+ fn delegate(counter: DropCounter) -> arc::R<CallbackOutputDelegate> {
+ CallbackOutputDelegate::with(CallbackOutputDelegateInner::new(Box::new(move |_| {
+ let _ = &counter;
+ })))
+ }
+
+ #[test]
+ fn final_release_drops_payload_and_native_associated_objects_once() {
+ let drops = Arc::new(AtomicUsize::new(0));
+ for cycle in 0..100 {
+ let outer = delegate(DropCounter(drops.clone()));
+ let associated = delegate(DropCounter(drops.clone()));
+ unsafe {
+ set_associated_object(
+ std::ptr::from_ref(outer.as_ref()).cast(),
+ std::ptr::from_ref(&ASSOCIATION_KEY).cast(),
+ std::ptr::from_ref(associated.as_ref()).cast(),
+ 1,
+ );
+ }
+ drop(associated);
+ assert_eq!(drops.load(Ordering::SeqCst), cycle * 2);
+ drop(outer);
+ assert_eq!(drops.load(Ordering::SeqCst), (cycle + 1) * 2);
+ }
+ }
+}
diff --git a/crates/camera/src/linux.rs b/crates/camera/src/linux.rs
index 8d6c36122..f12147c10 100644
--- a/crates/camera/src/linux.rs
+++ b/crates/camera/src/linux.rs
@@ -41,6 +41,9 @@ const PREFERRED_STEPWISE_SIZES: &[(u32, u32)] = &[
];
const PREFERRED_STEPWISE_FPS: &[u32] = &[60, 30, 24, 15];
+const CAMERA_POLL_INTERVAL_MS: i32 = 250;
+const CAMERA_FRAME_TIMEOUT: Duration = Duration::from_secs(4);
+const POLLIN: i16 = 0x0001;
#[derive(Clone, Debug)]
pub struct NativeFormat {
@@ -204,49 +207,65 @@ pub fn start_capturing_impl(
let (ready_tx, ready_rx) = mpsc::sync_channel(1);
let started = Instant::now();
- let thread = thread::spawn(move || {
- let mut stream = match MmapStream::with_buffers(&device, Type::VideoCapture, 4) {
- Ok(stream) => {
- let _ = ready_tx.send(Ok(()));
- stream
- }
- Err(e) => {
- let _ = ready_tx.send(Err(e.to_string()));
- return;
- }
- };
-
- loop {
- if stop_rx.try_recv().is_ok() {
- break;
- }
+ let thread = thread::Builder::new()
+ .name("cap-linux-camera".to_string())
+ .spawn(move || {
+ let mut stream = match MmapStream::with_buffers(&device, Type::VideoCapture, 4) {
+ Ok(mut stream) => {
+ stream.set_timeout(CAMERA_FRAME_TIMEOUT);
+ if ready_tx.send(Ok(())).is_err() {
+ return;
+ }
+ stream
+ }
+ Err(e) => {
+ let _ = ready_tx.send(Err(e.to_string()));
+ return;
+ }
+ };
- match stream.next() {
- Ok((bytes, meta)) => {
- let used = meta.bytesused as usize;
- let bytes = bytes.get(..used).unwrap_or(bytes);
- callback(CapturedFrame {
- native: NativeCapturedFrame {
- bytes: bytes.to_vec(),
- format: frame_format,
- },
- timestamp: started.elapsed(),
- });
+ let can_poll_before_requeue = has_multiple_capture_buffers(&stream);
+ let mut received_frame = false;
+ loop {
+ if !matches!(stop_rx.try_recv(), Err(mpsc::TryRecvError::Empty)) {
+ break;
}
- Err(e)
- if matches!(
- e.kind(),
- std::io::ErrorKind::TimedOut | std::io::ErrorKind::WouldBlock
- ) =>
- {
- thread::sleep(Duration::from_millis(5));
+
+ // Poll before next() so a stalled camera stays cancellable without
+ // re-queuing a buffer after v4l's internal dequeue times out.
+ if received_frame && can_poll_before_requeue {
+ match stream.handle().poll(POLLIN, CAMERA_POLL_INTERVAL_MS) {
+ Ok(0) => continue,
+ Ok(_) => {}
+ Err(error) if error.kind() == std::io::ErrorKind::Interrupted => continue,
+ Err(error) => {
+ tracing::warn!(%error, "Linux camera polling failed");
+ break;
+ }
+ }
}
- Err(_) => {
- thread::sleep(Duration::from_millis(20));
+
+ match stream.next() {
+ Ok((bytes, meta)) => {
+ received_frame = true;
+ let used = meta.bytesused as usize;
+ let bytes = bytes.get(..used).unwrap_or(bytes);
+ callback(CapturedFrame {
+ native: NativeCapturedFrame {
+ bytes: bytes.to_vec(),
+ format: frame_format,
+ },
+ timestamp: started.elapsed(),
+ });
+ }
+ Err(error) => {
+ tracing::warn!(%error, "Linux camera capture ended");
+ break;
+ }
}
}
- }
- });
+ })
+ .map_err(|error| StartCapturingError::Native(error.to_string()))?;
match ready_rx.recv_timeout(Duration::from_secs(2)) {
Ok(Ok(())) => Ok(NativeCaptureHandle {
@@ -261,6 +280,25 @@ pub fn start_capturing_impl(
}
}
+fn has_multiple_capture_buffers(stream: &MmapStream<'_>) -> bool {
+ let mut buffer = v4l::v4l_sys::v4l2_buffer {
+ index: 1,
+ type_: Type::VideoCapture as u32,
+ memory: v4l::memory::Memory::Mmap as u32,
+ ..unsafe { std::mem::zeroed() }
+ };
+ // A driver may grant only one buffer; pre-polling then waits on a buffer
+ // still held by next(), so that case must queue before polling.
+ unsafe {
+ v4l::v4l2::ioctl(
+ stream.handle().fd(),
+ v4l::v4l2::vidioc::VIDIOC_QUERYBUF,
+ &mut buffer as *mut _ as *mut std::ffi::c_void,
+ )
+ }
+ .is_ok()
+}
+
fn video_device_paths() -> Vec<PathBuf> {
let mut paths = fs::read_dir("/dev")
.ok()
diff --git a/crates/recording/src/cursor.rs b/crates/recording/src/cursor.rs
index fec8000a1..908da0373 100644
--- a/crates/recording/src/cursor.rs
+++ b/crates/recording/src/cursor.rs
@@ -560,20 +560,44 @@ struct CursorData {
#[cfg(target_os = "macos")]
fn get_cursor_data() -> Option<CursorData> {
use objc::rc::autoreleasepool;
+ use objc2::{ClassType, msg_send, rc::Retained};
use objc2_app_kit::NSCursor;
- use sha2::{Digest, Sha256};
autoreleasepool(|| unsafe {
#[allow(deprecated)]
- let cursor = NSCursor::currentSystemCursor().unwrap_or(NSCursor::currentCursor());
+ let cursor = NSCursor::currentSystemCursor().or_else(|| {
+ let cursor: Option<Retained<NSCursor>> = msg_send![NSCursor::class(), currentCursor];
+ cursor
+ })?;
+
+ macos_cursor_data(&cursor)
+ })
+}
- let image = cursor.image();
+#[cfg(target_os = "macos")]
+fn macos_cursor_data(cursor: &objc2_app_kit::NSCursor) -> Option<CursorData> {
+ use objc2::{msg_send, rc::Retained};
+ use objc2_app_kit::NSImage;
+ use sha2::{Digest, Sha256};
+
+ unsafe {
+ // AppKit can return nil for transient system cursors despite NSCursor.image's nonnull annotation.
+ let image: Option<Retained<NSImage>> = msg_send![cursor, image];
+ let image = image?;
let size = image.size();
let hotspot = cursor.hotSpot();
- let image_data = image.TIFFRepresentation()?;
+ if !size.width.is_finite()
+ || !size.height.is_finite()
+ || size.width <= 0.0
+ || size.height <= 0.0
+ || !hotspot.x.is_finite()
+ || !hotspot.y.is_finite()
+ {
+ return None;
+ }
+ let image_data = image.TIFFRepresentation()?;
let image = image_data.as_bytes_unchecked().to_vec();
-
let shape =
cap_cursor_info::CursorShapeMacOS::from_hash(&hex::encode(Sha256::digest(&image)));
@@ -582,7 +606,56 @@ fn get_cursor_data() -> Option<CursorData> {
hotspot: XY::new(hotspot.x / size.width, hotspot.y / size.height),
shape: shape.map(Into::into),
})
- })
+ }
+}
+
+#[cfg(all(test, target_os = "macos"))]
+mod macos_cursor_tests {
+ use super::macos_cursor_data;
+ use objc2::{AllocAnyThread, class, msg_send, rc::Retained, runtime::AnyObject};
+ use objc2_app_kit::{NSCursor, NSImage};
+
+ #[test]
+ fn cursor_without_image_is_skipped() {
+ let cursor = unsafe { NSCursor::new() };
+ assert!(macos_cursor_data(&cursor).is_none());
+ }
+
+ #[test]
+ fn zero_sized_cursor_is_skipped() {
+ let image = unsafe { NSImage::initWithSize(NSImage::alloc(), Default::default()) };
+ let cursor = NSCursor::initWithImage_hotSpot(NSCursor::alloc(), &image, Default::default());
+ assert!(macos_cursor_data(&cursor).is_none());
+ }
+
+ #[test]
+ fn valid_cursor_keeps_image_and_hotspot() {
+ let mut png = std::io::Cursor::new(Vec::new());
+ image::RgbaImage::from_pixel(8, 8, image::Rgba([20, 40, 80, 255]))
+ .write_to(&mut png, image::ImageFormat::Png)
+ .unwrap();
+ let png = png.into_inner();
+ let data: Retained<AnyObject> = unsafe {
+ msg_send![class!(NSData), dataWithBytes: png.as_ptr().cast::<std::ffi::c_void>(), length: png.len()]
+ };
+ let image: Retained<NSImage> = unsafe { msg_send![NSImage::alloc(), initWithData: &*data] };
+ let cursor = NSCursor::initWithImage_hotSpot(NSCursor::alloc(), &image, Default::default());
+ let image = unsafe { cursor.image() };
+ let expected_image = unsafe {
+ image
+ .TIFFRepresentation()
+ .unwrap()
+ .as_bytes_unchecked()
+ .to_vec()
+ };
+ let size = unsafe { image.size() };
+ let hotspot = unsafe { cursor.hotSpot() };
+ let actual = macos_cursor_data(&cursor).unwrap();
+
+ assert_eq!(actual.image, expected_image);
+ assert_eq!(actual.hotspot.x, hotspot.x / size.width);
+ assert_eq!(actual.hotspot.y, hotspot.y / size.height);
+ }
}
#[cfg(target_os = "linux")]
diff --git a/crates/recording/src/feeds/camera.rs b/crates/recording/src/feeds/camera.rs
index 97af69b19..bf40a88b4 100644
--- a/crates/recording/src/feeds/camera.rs
+++ b/crates/recording/src/feeds/camera.rs
@@ -31,6 +31,7 @@ const CAMERA_INIT_TIMEOUT: Duration = Duration::from_secs(4);
/// Outer deadline for camera readiness. Must cover both capture attempts on
/// macOS (native + compatibility fallback) plus session teardown in between.
const CAMERA_READY_TIMEOUT: Duration = Duration::from_secs(10);
+const MAX_CONCURRENT_CAMERA_SETUPS: usize = 2;
#[cfg(target_os = "macos")]
static CAMERA_CAPTURE_LIFECYCLE_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
@@ -44,6 +45,9 @@ fn camera_capture_lifecycle_guard() -> std::sync::MutexGuard<'static, ()> {
#[derive(Actor)]
pub struct CameraFeed {
+ setup_slots: Arc<tokio::sync::Semaphore>,
+ setup_cancel: tokio_util::sync::CancellationToken,
+ _cancel_setup: tokio_util::sync::DropGuard,
lock_generation: u64,
setup_generation: u64,
state: State,
@@ -53,7 +57,6 @@ pub struct CameraFeed {
native_sender_count: Arc<std::sync::atomic::AtomicUsize>,
on_ready: Vec<oneshot::Sender<()>>,
on_disconnect: Vec<Box<dyn Fn() + Send>>,
- previous_thread: Option<std::thread::JoinHandle<()>>,
}
enum State {
@@ -170,7 +173,7 @@ impl AttachedState {
fn stage_pending_release(&mut self) {
if let Some(pending) = self.pending_release.take() {
- let _ = pending.send(());
+ let _ = pending.try_send(());
}
self.pending_release = Some(self.done_tx.clone());
@@ -178,14 +181,18 @@ impl AttachedState {
fn finalize_pending_release(&mut self) {
if let Some(pending) = self.pending_release.take() {
- let _ = pending.send(());
+ let _ = pending.try_send(());
}
}
}
impl Default for CameraFeed {
fn default() -> Self {
+ let setup_cancel = tokio_util::sync::CancellationToken::new();
Self {
+ setup_slots: Arc::new(tokio::sync::Semaphore::new(MAX_CONCURRENT_CAMERA_SETUPS)),
+ _cancel_setup: setup_cancel.clone().drop_guard(),
+ setup_cancel,
lock_generation: 0,
setup_generation: 0,
state: State::Open(OpenState {
@@ -198,7 +205,6 @@ impl Default for CameraFeed {
native_sender_count: Arc::new(std::sync::atomic::AtomicUsize::new(0)),
on_ready: Vec::new(),
on_disconnect: Vec::new(),
- previous_thread: None,
}
}
}
@@ -308,7 +314,7 @@ type ReadyFuture = Shared<BoxFuture<'static, Result<InputConnected, SetInputErro
#[derive(Clone, Copy)]
enum CameraSetupFlow {
Open,
- Locked,
+ Locked { lock_generation: u64 },
}
struct InputConnectFailed {
@@ -317,6 +323,8 @@ struct InputConnectFailed {
}
struct LockedCameraInputReconnected {
+ generation: u64,
+ lock_generation: u64,
id: DeviceOrModelID,
camera_info: cap_camera::CameraInfo,
video_info: VideoInfo,
@@ -332,10 +340,13 @@ struct Unlock {
}
struct FinalizePendingRelease {
+ generation: u64,
id: DeviceOrModelID,
}
struct CameraSetupArgs {
+ setup_slots: Arc<tokio::sync::Semaphore>,
+ setup_cancel: tokio_util::sync::CancellationToken,
id: DeviceOrModelID,
generation: u64,
settings: Option<CameraDeviceSettings>,
@@ -347,10 +358,58 @@ struct CameraSetupArgs {
flow: CameraSetupFlow,
}
-fn spawn_camera_setup(
- args: CameraSetupArgs,
-) -> (ReadyFuture, SyncSender<()>, std::thread::JoinHandle<()>) {
+fn bounded_camera_ready(
+ ready: BoxFuture<'static, Result<InputConnected, SetInputError>>,
+ cancel: tokio_util::sync::CancellationToken,
+ timeout: Duration,
+) -> ReadyFuture {
+ let deadline = tokio::time::Instant::now() + timeout;
+ let cancel_on_drop = cancel.clone().drop_guard();
+ async move {
+ let result = tokio::select! {
+ biased;
+ _ = cancel.cancelled() => Err(SetInputError::SetupCancelled),
+ result = tokio::time::timeout_at(deadline, ready) => {
+ result.unwrap_or_else(|error| Err(SetInputError::Timeout(error.to_string())))
+ }
+ };
+ if result.is_ok() {
+ drop(cancel_on_drop.disarm());
+ }
+ result
+ }
+ .boxed()
+ .shared()
+}
+
+async fn spawn_camera_worker(
+ slots: Arc<tokio::sync::Semaphore>,
+ cancel: tokio_util::sync::CancellationToken,
+ worker: impl FnOnce(tokio::sync::OwnedSemaphorePermit) + Send + 'static,
+) -> Result<(), SetInputError> {
+ let permit = tokio::select! {
+ biased;
+ _ = cancel.cancelled() => return Err(SetInputError::SetupCancelled),
+ permit = slots.acquire_owned() => permit.map_err(|error| {
+ SetInputError::StartCapturing(format!("Camera setup is unavailable: {error}"))
+ })?,
+ };
+ if cancel.is_cancelled() {
+ return Err(SetInputError::SetupCancelled);
+ }
+ std::thread::Builder::new()
+ .name("camera-capture".into())
+ .spawn(move || worker(permit))
+ .map(drop)
+ .map_err(|error| {
+ SetInputError::StartCapturing(format!("Could not start camera worker: {error}"))
+ })
+}
+
+fn spawn_camera_setup(args: CameraSetupArgs) -> (ReadyFuture, SyncSender<()>) {
let CameraSetupArgs {
+ setup_slots,
+ setup_cancel,
id,
generation,
settings,
@@ -365,41 +424,56 @@ fn spawn_camera_setup(
let (ready_tx, ready_rx) = oneshot::channel::<Result<InputConnected, SetInputError>>();
let (done_tx, done_rx) = std::sync::mpsc::sync_channel(1);
- let ready = ready_rx
- .map(|v| {
- v.map_err(|_| SetInputError::BuildStreamCrashed)
- .and_then(|v| v)
- })
- .boxed()
- .shared();
+ let ready = bounded_camera_ready(
+ ready_rx
+ .map(|v| {
+ v.map_err(|_| SetInputError::BuildStreamCrashed)
+ .and_then(|v| v)
+ })
+ .boxed(),
+ setup_cancel.clone(),
+ CAMERA_READY_TIMEOUT,
+ );
+
+ if matches!(flow, CameraSetupFlow::Open) {
+ let ready = ready.clone();
+ let actor = actor_ref.clone();
+ let id = id.clone();
+ tokio::spawn(async move {
+ if ready.await.is_err() {
+ let _ = actor.tell(InputConnectFailed { id, generation }).await;
+ }
+ });
+ }
let done_rx_thread = done_rx;
let done_tx_thread = done_tx.clone();
let ready_tx_thread = ready_tx;
- let join_handle = std::thread::spawn(move || {
- let runtime = tokio::runtime::Builder::new_current_thread()
- .enable_all()
- .build()
- .expect("Failed to build camera tokio runtime");
+ tokio::spawn(async move {
+ let worker = spawn_camera_worker(setup_slots, setup_cancel.clone(), move |setup_permit| {
+ if setup_cancel.is_cancelled() {
+ return;
+ }
+ let runtime = match tokio::runtime::Builder::new_current_thread()
+ .enable_all()
+ .build()
+ {
+ Ok(runtime) => runtime,
+ Err(error) => {
+ let _ = ready_tx_thread.send(Err(SetInputError::StartCapturing(format!(
+ "Could not initialize the camera worker: {error}"
+ ))));
+ return;
+ }
+ };
- {
- #[cfg(target_os = "macos")]
- let _capture_lifecycle_guard = camera_capture_lifecycle_guard();
-
- LocalSet::new().block_on(&runtime, async move {
- if done_rx_thread.try_recv().is_ok() {
- let _ = ready_tx_thread.send(Err(SetInputError::BuildStreamCrashed));
-
- if matches!(flow, CameraSetupFlow::Open) {
- let _ = actor_ref
- .tell(InputConnectFailed {
- id: id.clone(),
- generation,
- })
- .await;
- }
+ {
+ #[cfg(target_os = "macos")]
+ let _capture_lifecycle_guard = camera_capture_lifecycle_guard();
+ LocalSet::new().block_on(&runtime, async move {
+ if setup_cancel.is_cancelled() || done_rx_thread.try_recv().is_ok() {
return;
}
@@ -422,6 +496,11 @@ fn spawn_camera_setup(
video_info,
} = result;
+ if setup_cancel.is_cancelled() {
+ let _ = handle.stop_capturing();
+ return;
+ }
+
let ready_payload = InputConnected {
generation,
id: id.clone(),
@@ -432,12 +511,17 @@ fn spawn_camera_setup(
match flow {
CameraSetupFlow::Open => {
- let _ = ready_tx_thread.send(Ok(ready_payload.clone()));
+ if ready_tx_thread.send(Ok(ready_payload.clone())).is_err() {
+ let _ = handle.stop_capturing();
+ return;
+ }
let _ = actor_ref.ask(ready_payload).await;
}
- CameraSetupFlow::Locked => {
+ CameraSetupFlow::Locked { lock_generation } => {
let reconnect_result = actor_ref
.ask(LockedCameraInputReconnected {
+ generation,
+ lock_generation,
id: id.clone(),
camera_info,
video_info,
@@ -449,7 +533,10 @@ fn spawn_camera_setup(
Ok(true) => {
let _ = ready_tx_thread.send(Ok(ready_payload));
let _ = actor_ref
- .tell(FinalizePendingRelease { id: id.clone() })
+ .tell(FinalizePendingRelease {
+ generation,
+ id: id.clone(),
+ })
.await;
}
Ok(false) => {
@@ -481,19 +568,16 @@ fn spawn_camera_setup(
Err(e) => {
let _ = ready_tx_thread.send(Err(e.clone()));
- if matches!(flow, CameraSetupFlow::Open) {
- let _ = actor_ref
- .tell(InputConnectFailed {
- id: id.clone(),
- generation,
- })
- .await;
- }
-
return;
}
};
+ if setup_cancel.is_cancelled() {
+ let _ = handle.stop_capturing();
+ return;
+ }
+ drop(setup_permit);
+
debug!(
"Camera capture thread: waiting for done signal for {:?}",
&id
@@ -514,49 +598,25 @@ fn spawn_camera_setup(
debug!("Camera capture thread: capture closed for {:?}", &id);
});
- }
+ }
- drop(runtime);
+ drop(runtime);
+ })
+ .await;
+ if let Err(error) = worker {
+ debug!(%error, "Camera setup worker did not start");
+ }
});
- (ready, done_tx, join_handle)
-}
-
-fn release_camera_thread(handle: std::thread::JoinHandle<()>) {
- if handle.is_finished() {
- let _ = handle.join();
- } else {
- debug!("Camera setup thread is still running after cancellation");
- if let Err(err) = std::thread::Builder::new()
- .name("camera-setup-reaper".to_string())
- .spawn(move || {
- let _ = handle.join();
- })
- {
- warn!(?err, "Failed to spawn camera-setup-reaper thread");
- }
- }
+ (ready, done_tx)
}
fn camera_ready_future(
ready: ReadyFuture,
- actor_ref: ActorRef<CameraFeed>,
- id: DeviceOrModelID,
- generation: u64,
- flow: CameraSetupFlow,
) -> BoxFuture<'static, Result<(CameraInfo, VideoInfo), SetInputError>> {
- async move {
- match tokio::time::timeout(CAMERA_READY_TIMEOUT, ready).await {
- Ok(result) => result.map(|v| (v.camera_info, v.video_info)),
- Err(err) => {
- if matches!(flow, CameraSetupFlow::Open) {
- let _ = actor_ref.tell(InputConnectFailed { id, generation }).await;
- }
- Err(SetInputError::Timeout(err.to_string()))
- }
- }
- }
- .boxed()
+ ready
+ .map(|result| result.map(|v| (v.camera_info, v.video_info)))
+ .boxed()
}
// Impls
@@ -573,6 +633,8 @@ pub enum SetInputError {
DeviceNotFound,
#[error("BuildStreamCrashed")]
BuildStreamCrashed, // TODO: Maybe rename this?
+ #[error("Camera setup was cancelled by a newer selection")]
+ SetupCancelled,
#[error("InvalidFormat")]
InvalidFormat,
#[error("CameraTimeout")]
@@ -1126,24 +1188,29 @@ impl Message<SetInput> for CameraFeed {
SetInputError::Initialisation
);
+ if let State::Locked { inner, .. } = &self.state
+ && inner.id != msg.id
+ {
+ return Err(SetInputError::Locked(FeedLockedError));
+ }
+
match &self.state {
State::Open(state) => {
if let Some(connecting) = &state.connecting {
- let _ = connecting.done_tx.send(());
+ let _ = connecting.done_tx.try_send(());
}
if let Some(attached) = &state.attached {
- let _ = attached.done_tx.send(());
+ let _ = attached.done_tx.try_send(());
}
}
State::Locked { inner, .. } => {
- let _ = inner.done_tx.send(());
+ let _ = inner.done_tx.try_send(());
}
}
- if let Some(handle) = self.previous_thread.take() {
- release_camera_thread(handle);
- }
-
+ self.setup_cancel.cancel();
+ self.setup_cancel = tokio_util::sync::CancellationToken::new();
+ self._cancel_setup = self.setup_cancel.clone().drop_guard();
let generation = self.next_setup_generation();
match &mut self.state {
@@ -1153,7 +1220,9 @@ impl Message<SetInput> for CameraFeed {
let native_frame_recipient = actor_ref.clone().recipient();
let id = msg.id.clone();
- let (ready, done_tx, join_handle) = spawn_camera_setup(CameraSetupArgs {
+ let (ready, done_tx) = spawn_camera_setup(CameraSetupArgs {
+ setup_slots: self.setup_slots.clone(),
+ setup_cancel: self.setup_cancel.clone(),
id: id.clone(),
generation,
settings: msg.settings,
@@ -1165,8 +1234,6 @@ impl Message<SetInput> for CameraFeed {
flow: CameraSetupFlow::Open,
});
- self.previous_thread = Some(join_handle);
-
state.connecting = Some(ConnectingState {
id: id.clone(),
generation,
@@ -1174,24 +1241,16 @@ impl Message<SetInput> for CameraFeed {
done_tx,
});
- Ok(camera_ready_future(
- ready,
- ctx.actor_ref(),
- id,
- generation,
- CameraSetupFlow::Open,
- ))
+ Ok(camera_ready_future(ready))
}
- State::Locked { inner, .. } => {
- if inner.id != msg.id {
- return Err(SetInputError::Locked(FeedLockedError));
- }
-
+ State::Locked { .. } => {
let actor_ref = ctx.actor_ref();
let new_frame_recipient = actor_ref.clone().recipient();
let native_frame_recipient = actor_ref.clone().recipient();
- let (ready, _done_tx, join_handle) = spawn_camera_setup(CameraSetupArgs {
+ let (ready, _done_tx) = spawn_camera_setup(CameraSetupArgs {
+ setup_slots: self.setup_slots.clone(),
+ setup_cancel: self.setup_cancel.clone(),
id: msg.id.clone(),
generation,
settings: msg.settings,
@@ -1200,18 +1259,12 @@ impl Message<SetInput> for CameraFeed {
native_frame_recipient,
ffmpeg_sender_count: self.ffmpeg_sender_count.clone(),
native_sender_count: self.native_sender_count.clone(),
- flow: CameraSetupFlow::Locked,
+ flow: CameraSetupFlow::Locked {
+ lock_generation: self.lock_generation,
+ },
});
- self.previous_thread = Some(join_handle);
-
- Ok(camera_ready_future(
- ready,
- ctx.actor_ref(),
- msg.id,
- generation,
- CameraSetupFlow::Locked,
- ))
+ Ok(camera_ready_future(ready))
}
}
}
@@ -1224,14 +1277,15 @@ impl Message<RemoveInput> for CameraFeed {
trace!("CameraFeed.RemoveInput");
let state = self.state.try_as_open()?;
+ self.setup_cancel.cancel();
if let Some(connecting) = state.connecting.take() {
- let _ = connecting.done_tx.send(());
+ let _ = connecting.done_tx.try_send(());
}
if let Some(mut attached) = state.attached.take() {
attached.finalize_pending_release();
- let _ = attached.done_tx.send(());
+ let _ = attached.done_tx.try_send(());
}
self.senders.clear();
@@ -1241,10 +1295,6 @@ impl Message<RemoveInput> for CameraFeed {
self.native_sender_count
.store(0, std::sync::atomic::Ordering::Release);
- if let Some(handle) = self.previous_thread.take() {
- release_camera_thread(handle);
- }
-
for cb in &self.on_disconnect {
(cb)();
}
@@ -1514,11 +1564,17 @@ impl Message<Lock> for CameraFeed {
if let Some(connecting) = &mut state.connecting {
let ready = &mut connecting.ready;
- let data = tokio::time::timeout(CAMERA_READY_TIMEOUT, ready)
+ let result = tokio::time::timeout(CAMERA_READY_TIMEOUT, ready)
.await
- .map_err(|err| {
- LockFeedError::InitializeFailed(SetInputError::Timeout(err.to_string()))
- })??;
+ .unwrap_or_else(|error| Err(SetInputError::Timeout(error.to_string())));
+ let data = match result {
+ Ok(data) => data,
+ Err(error) => {
+ connecting.ready = futures::future::ready(Err(error.clone())).boxed();
+ self.setup_cancel.cancel();
+ return Err(error.into());
+ }
+ };
if state.handle_input_connected(data) {
if let Some(attached) = &mut state.attached {
@@ -1576,6 +1632,10 @@ impl Message<InputConnected> for CameraFeed {
) -> Self::Reply {
trace!("CameraFeed.InputConnected");
+ if self.setup_cancel.is_cancelled() {
+ return;
+ }
+
// Lock can consume this connection before the notification reaches the mailbox.
let Ok(state) = self.state.try_as_open() else {
return;
@@ -1613,7 +1673,11 @@ impl Message<InputConnectFailed> for CameraFeed {
if should_clear {
if let Some(connecting) = state.connecting.take() {
- let _ = connecting.done_tx.send(());
+ let _ = connecting.done_tx.try_send(());
+ }
+ if let Some(mut attached) = state.attached.take() {
+ attached.finalize_pending_release();
+ let _ = attached.done_tx.try_send(());
}
for tx in &mut self.on_ready.drain(..) {
@@ -1631,15 +1695,19 @@ impl Message<LockedCameraInputReconnected> for CameraFeed {
msg: LockedCameraInputReconnected,
_: &mut Context<Self, Self::Reply>,
) -> Self::Reply {
- if let State::Locked { inner, .. } = &mut self.state
+ if self.setup_generation == msg.generation
+ && self.lock_generation == msg.lock_generation
+ && !self.setup_cancel.is_cancelled()
+ && let State::Locked { inner, token } = &mut self.state
&& inner.id == msg.id
+ && token.strong_count() > 0
{
let id = msg.id;
inner.stage_pending_release();
inner.overwrite(
id.clone(),
InputConnected {
- generation: 0,
+ generation: msg.generation,
id,
done_tx: msg.done_tx,
camera_info: msg.camera_info,
@@ -1661,6 +1729,9 @@ impl Message<FinalizePendingRelease> for CameraFeed {
msg: FinalizePendingRelease,
_: &mut Context<Self, Self::Reply>,
) -> Self::Reply {
+ if self.setup_generation != msg.generation {
+ return;
+ }
match &mut self.state {
State::Open(OpenState { attached, .. }) => {
if let Some(attached) = attached
@@ -1709,17 +1780,12 @@ impl Message<Unlock> for CameraFeed {
mod tests {
use super::*;
- async fn locked_test_camera() -> (
- ActorRef<CameraFeed>,
- CameraFeedLock,
- InputConnected,
- oneshot::Receiver<()>,
- ) {
- let (done_tx, _done_rx) = mpsc::sync_channel(1);
+ fn test_camera_connection(generation: u64) -> (InputConnected, mpsc::Receiver<()>) {
+ let (done_tx, done_rx) = mpsc::sync_channel(1);
let connection = InputConnected {
id: DeviceOrModelID::DeviceID("test-camera".to_string()),
- generation: 1,
- done_tx: done_tx.clone(),
+ generation,
+ done_tx,
camera_info: serde_json::from_value(serde_json::json!({
"device_id": "test-camera",
"model_id": null,
@@ -1728,6 +1794,243 @@ mod tests {
.unwrap(),
video_info: VideoInfo::from_raw_ffmpeg(ffmpeg::format::Pixel::BGRA, 16, 16, 30),
};
+ (connection, done_rx)
+ }
+
+ struct AttachedCamera;
+
+ impl Message<AttachedCamera> for CameraFeed {
+ type Reply = Option<DeviceOrModelID>;
+
+ async fn handle(
+ &mut self,
+ _: AttachedCamera,
+ _: &mut Context<Self, Self::Reply>,
+ ) -> Self::Reply {
+ match &self.state {
+ State::Open(state) => state.attached.as_ref().map(|attached| attached.id.clone()),
+ State::Locked { inner, .. } => Some(inner.id.clone()),
+ }
+ }
+ }
+
+ #[tokio::test]
+ async fn camera_readiness_timeout_cancels_native_work_and_success_stays_attached() {
+ let cancel = tokio_util::sync::CancellationToken::new();
+ let (native_tx, native_rx) = oneshot::channel();
+ let ready = bounded_camera_ready(
+ async move { native_rx.await.unwrap() }.boxed(),
+ cancel.clone(),
+ Duration::from_millis(20),
+ );
+ assert!(matches!(ready.await, Err(SetInputError::Timeout(_))));
+ assert!(cancel.is_cancelled());
+ assert!(native_tx.is_closed());
+
+ let cancel = tokio_util::sync::CancellationToken::new();
+ let (connection, done_rx) = test_camera_connection(1);
+ let ready = bounded_camera_ready(
+ futures::future::ready(Ok(connection)).boxed(),
+ cancel.clone(),
+ CAMERA_READY_TIMEOUT,
+ );
+ let attached = ready.await.unwrap();
+ assert!(!cancel.is_cancelled());
+ assert!(matches!(done_rx.try_recv(), Err(mpsc::TryRecvError::Empty)));
+ drop(attached);
+ }
+
+ #[tokio::test]
+ async fn dropping_camera_readiness_cancels_queued_work_before_native_spawn() {
+ let slots = Arc::new(tokio::sync::Semaphore::new(0));
+ let cancel = tokio_util::sync::CancellationToken::new();
+ let ready = bounded_camera_ready(
+ futures::future::pending().boxed(),
+ cancel.clone(),
+ CAMERA_READY_TIMEOUT,
+ );
+ let (started_tx, started_rx) = flume::bounded(1);
+ let queued = tokio::spawn(spawn_camera_worker(slots.clone(), cancel, move |_| {
+ started_tx.send(()).unwrap();
+ }));
+ tokio::task::yield_now().await;
+ drop(ready);
+ assert!(matches!(
+ tokio::time::timeout(Duration::from_secs(1), queued)
+ .await
+ .unwrap()
+ .unwrap(),
+ Err(SetInputError::SetupCancelled)
+ ));
+ slots.add_permits(1);
+ assert!(started_rx.is_empty());
+ }
+
+ #[tokio::test]
+ async fn camera_stuck_setups_bound_workers_without_holding_slots_for_live_capture() {
+ let slots = Arc::new(tokio::sync::Semaphore::new(MAX_CONCURRENT_CAMERA_SETUPS));
+ let (started_tx, started_rx) = flume::bounded(MAX_CONCURRENT_CAMERA_SETUPS + 1);
+ let (stopped_tx, stopped_rx) = flume::bounded(MAX_CONCURRENT_CAMERA_SETUPS + 1);
+ let mut release = Vec::new();
+ for _ in 0..MAX_CONCURRENT_CAMERA_SETUPS {
+ let (release_tx, release_rx) = mpsc::channel();
+ release.push(release_tx);
+ let started = started_tx.clone();
+ let stopped = stopped_tx.clone();
+ spawn_camera_worker(
+ slots.clone(),
+ tokio_util::sync::CancellationToken::new(),
+ move |permit| {
+ started.send(()).unwrap();
+ release_rx.recv().unwrap();
+ drop(permit);
+ stopped.send(()).unwrap();
+ },
+ )
+ .await
+ .unwrap();
+ }
+ for _ in 0..MAX_CONCURRENT_CAMERA_SETUPS {
+ started_rx.recv_async().await.unwrap();
+ }
+ assert_eq!(slots.available_permits(), 0);
+ for _ in 0..32 {
+ let cancel = tokio_util::sync::CancellationToken::new();
+ let started = started_tx.clone();
+ let queued = tokio::spawn(spawn_camera_worker(
+ slots.clone(),
+ cancel.clone(),
+ move |_| started.send(()).unwrap(),
+ ));
+ tokio::task::yield_now().await;
+ cancel.cancel();
+ assert!(matches!(
+ tokio::time::timeout(Duration::from_secs(1), queued)
+ .await
+ .unwrap()
+ .unwrap(),
+ Err(SetInputError::SetupCancelled)
+ ));
+ }
+ assert!(started_rx.is_empty());
+ release[0].send(()).unwrap();
+ stopped_rx.recv_async().await.unwrap();
+
+ let (capture_stop_tx, capture_stop_rx) = mpsc::channel();
+ spawn_camera_worker(
+ slots.clone(),
+ tokio_util::sync::CancellationToken::new(),
+ move |permit| {
+ drop(permit);
+ started_tx.send(()).unwrap();
+ capture_stop_rx.recv().unwrap();
+ stopped_tx.send(()).unwrap();
+ },
+ )
+ .await
+ .unwrap();
+ started_rx.recv_async().await.unwrap();
+ assert_eq!(slots.available_permits(), 1);
+ capture_stop_tx.send(()).unwrap();
+ stopped_rx.recv_async().await.unwrap();
+ for release in &release[1..] {
+ release.send(()).unwrap();
+ stopped_rx.recv_async().await.unwrap();
+ }
+ assert_eq!(slots.available_permits(), MAX_CONCURRENT_CAMERA_SETUPS);
+ assert!(started_rx.is_empty());
+ }
+
+ #[tokio::test]
+ async fn camera_reselection_and_removal_cancel_queued_attempts() {
+ let slots = Arc::new(tokio::sync::Semaphore::new(0));
+ let camera = CameraFeed {
+ setup_slots: slots.clone(),
+ ..CameraFeed::default()
+ };
+ let feed = CameraFeed::spawn(camera);
+ let mut pending = Vec::new();
+ for _ in 0..32 {
+ pending.push(
+ feed.ask(SetInput {
+ id: DeviceOrModelID::DeviceID("queued-camera".into()),
+ settings: None,
+ })
+ .await
+ .unwrap(),
+ );
+ }
+ feed.ask(RemoveInput).await.unwrap();
+ for ready in pending {
+ assert!(matches!(
+ tokio::time::timeout(Duration::from_secs(1), ready)
+ .await
+ .unwrap(),
+ Err(SetInputError::SetupCancelled)
+ ));
+ }
+ assert!(feed.ask(AttachedCamera).await.unwrap().is_none());
+ assert_eq!(slots.available_permits(), 0);
+ feed.kill();
+ feed.wait_for_stop().await;
+ }
+
+ #[tokio::test]
+ async fn stopping_camera_actor_cancels_queued_setup() {
+ let feed = CameraFeed::spawn(CameraFeed {
+ setup_slots: Arc::new(tokio::sync::Semaphore::new(0)),
+ ..CameraFeed::default()
+ });
+ let ready = feed
+ .ask(SetInput {
+ id: DeviceOrModelID::DeviceID("queued-camera".into()),
+ settings: None,
+ })
+ .await
+ .unwrap();
+ feed.kill();
+ feed.wait_for_stop().await;
+ assert!(matches!(
+ tokio::time::timeout(Duration::from_secs(1), ready)
+ .await
+ .unwrap(),
+ Err(SetInputError::SetupCancelled)
+ ));
+ }
+
+ #[tokio::test]
+ async fn cancelled_camera_setup_cannot_attach_a_late_success() {
+ let (connection, done_rx) = test_camera_connection(1);
+ let camera = CameraFeed {
+ setup_generation: 1,
+ state: State::Open(OpenState {
+ connecting: Some(ConnectingState {
+ id: connection.id.clone(),
+ generation: 1,
+ ready: futures::future::pending().boxed(),
+ done_tx: connection.done_tx.clone(),
+ }),
+ attached: None,
+ }),
+ ..CameraFeed::default()
+ };
+ camera.setup_cancel.cancel();
+ let feed = CameraFeed::spawn(camera);
+ feed.ask(connection).await.unwrap();
+ assert!(feed.ask(AttachedCamera).await.unwrap().is_none());
+ feed.ask(RemoveInput).await.unwrap();
+ assert!(done_rx.try_recv().is_ok());
+ feed.kill();
+ feed.wait_for_stop().await;
+ }
+
+ async fn locked_test_camera() -> (
+ ActorRef<CameraFeed>,
+ CameraFeedLock,
+ InputConnected,
+ oneshot::Receiver<()>,
+ ) {
+ let (connection, _done_rx) = test_camera_connection(1);
let (ready_tx, ready_rx) = oneshot::channel();
let camera = CameraFeed {
setup_generation: 1,
@@ -1736,7 +2039,7 @@ mod tests {
id: connection.id.clone(),
generation: connection.generation,
ready: futures::future::ready(Ok(connection.clone())).boxed(),
- done_tx,
+ done_tx: connection.done_tx.clone(),
}),
attached: None,
}),
@@ -1748,6 +2051,254 @@ mod tests {
(feed, lock, connection, ready_rx)
}
+ #[tokio::test]
+ async fn failed_camera_reselection_cannot_lock_a_stopped_attachment() {
+ let (connection, stopped) = test_camera_connection(0);
+ let id = connection.id.clone();
+ let camera = CameraFeed {
+ setup_slots: Arc::new(tokio::sync::Semaphore::new(0)),
+ state: State::Open(OpenState {
+ connecting: None,
+ attached: Some(AttachedState::new(id.clone(), connection)),
+ }),
+ ..CameraFeed::default()
+ };
+ let feed = CameraFeed::spawn(camera);
+ let selection = feed
+ .ask(SetInput {
+ id: id.clone(),
+ settings: None,
+ })
+ .await
+ .unwrap();
+ assert!(stopped.try_recv().is_ok());
+ feed.ask(InputConnectFailed { id, generation: 1 })
+ .await
+ .unwrap();
+
+ let mut unavailable = Vec::new();
+ for _ in 0..2 {
+ let result = feed.ask(Lock).await;
+ unavailable.push(matches!(
+ &result,
+ Err(kameo::error::SendError::HandlerError(
+ LockFeedError::NoInput
+ ))
+ ));
+ drop(result);
+ }
+ feed.ask(RemoveInput).await.unwrap();
+ feed.kill();
+ feed.wait_for_stop().await;
+ assert!(matches!(
+ selection.await,
+ Err(SetInputError::SetupCancelled)
+ ));
+ assert_eq!(unavailable, [true, true]);
+ }
+
+ #[tokio::test]
+ async fn failed_camera_selection_preserves_a_newer_attached_camera() {
+ let (connection, still_running) = test_camera_connection(2);
+ let id = connection.id.clone();
+ let feed = CameraFeed::spawn(CameraFeed {
+ setup_slots: Arc::new(tokio::sync::Semaphore::new(0)),
+ ..CameraFeed::default()
+ });
+ let first_selection = feed
+ .ask(SetInput {
+ id: id.clone(),
+ settings: None,
+ })
+ .await
+ .unwrap();
+ let second_selection = feed
+ .ask(SetInput {
+ id: id.clone(),
+ settings: None,
+ })
+ .await
+ .unwrap();
+ feed.ask(connection).await.unwrap();
+ for generation in [1, 2] {
+ feed.ask(InputConnectFailed {
+ id: id.clone(),
+ generation,
+ })
+ .await
+ .unwrap();
+ }
+ let lock = feed.ask(Lock).await;
+ let connected = lock.is_ok();
+ let running = matches!(still_running.try_recv(), Err(mpsc::TryRecvError::Empty));
+ drop(lock);
+ feed.ask(RemoveInput).await.unwrap();
+ feed.kill();
+ feed.wait_for_stop().await;
+ drop(first_selection);
+ drop(second_selection);
+ assert!(connected);
+ assert!(running);
+ }
+
+ #[tokio::test]
+ async fn queued_locks_keep_camera_setup_failure_without_locking_the_previous_camera() {
+ let (connection, _previous_rx) = test_camera_connection(1);
+ let (done_tx, _done_rx) = mpsc::sync_channel(1);
+ let ready = futures::future::ready(Err(SetInputError::BuildStreamCrashed))
+ .boxed()
+ .shared();
+ let camera = CameraFeed {
+ setup_generation: 2,
+ state: State::Open(OpenState {
+ connecting: Some(ConnectingState {
+ id: DeviceOrModelID::DeviceID("requested-camera".into()),
+ generation: 2,
+ ready: ready.boxed(),
+ done_tx,
+ }),
+ attached: Some(AttachedState::new(connection.id.clone(), connection)),
+ }),
+ ..CameraFeed::default()
+ };
+ let feed = CameraFeed::spawn(camera);
+ let results = tokio::time::timeout(Duration::from_secs(1), async {
+ tokio::join!(feed.ask(Lock), feed.ask(Lock), feed.ask(Lock))
+ })
+ .await
+ .expect("repeated camera locks blocked the actor mailbox");
+ for result in [results.0, results.1, results.2] {
+ assert!(matches!(
+ result,
+ Err(kameo::error::SendError::HandlerError(
+ LockFeedError::InitializeFailed(SetInputError::BuildStreamCrashed)
+ ))
+ ));
+ }
+ let (sender, _receiver) = flume::bounded(1);
+ feed.ask(AddSender(sender)).await.unwrap();
+ feed.kill();
+ feed.wait_for_stop().await;
+ }
+
+ #[tokio::test]
+ async fn rejected_locked_camera_selection_does_not_stop_the_recording_camera() {
+ let (connection, done_rx) = test_camera_connection(1);
+ let token = Arc::new(());
+ let camera = CameraFeed {
+ lock_generation: 7,
+ setup_generation: 1,
+ state: State::Locked {
+ inner: AttachedState::new(connection.id.clone(), connection),
+ token: Arc::downgrade(&token),
+ },
+ ..CameraFeed::default()
+ };
+ let feed = CameraFeed::spawn(camera);
+ let result = feed
+ .ask(SetInput {
+ id: DeviceOrModelID::DeviceID("different-camera".into()),
+ settings: None,
+ })
+ .await;
+ assert!(matches!(
+ result,
+ Err(kameo::error::SendError::HandlerError(
+ SetInputError::Locked(_)
+ ))
+ ));
+ assert!(matches!(done_rx.try_recv(), Err(mpsc::TryRecvError::Empty)));
+ drop(token);
+ feed.kill();
+ feed.wait_for_stop().await;
+ }
+
+ #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+ async fn camera_removal_does_not_block_on_an_already_queued_stop() {
+ let (connection, done_rx) = test_camera_connection(1);
+ connection.done_tx.try_send(()).unwrap();
+ let camera = CameraFeed {
+ state: State::Open(OpenState {
+ connecting: None,
+ attached: Some(AttachedState::new(connection.id.clone(), connection)),
+ }),
+ ..CameraFeed::default()
+ };
+ let feed = CameraFeed::spawn(camera);
+ let result = tokio::time::timeout(Duration::from_millis(250), feed.ask(RemoveInput)).await;
+ drop(done_rx);
+ feed.kill();
+ feed.wait_for_stop().await;
+ assert!(matches!(result, Ok(Ok(()))));
+ }
+
+ #[tokio::test]
+ async fn camera_reconnect_requires_current_setup_and_a_live_recording_lock() {
+ for (generation, lock_generation, live, cancelled, expected) in [
+ (11, 8, true, false, false),
+ (12, 7, true, false, false),
+ (12, 8, false, false, false),
+ (12, 8, true, true, false),
+ (12, 8, true, false, true),
+ ] {
+ let (connection, original_rx) = test_camera_connection(10);
+ let (replacement, replacement_rx) = test_camera_connection(generation);
+ let mut token = Some(Arc::new(()));
+ let camera = CameraFeed {
+ lock_generation: 8,
+ setup_generation: 12,
+ state: State::Locked {
+ inner: AttachedState::new(connection.id.clone(), connection),
+ token: Arc::downgrade(token.as_ref().unwrap()),
+ },
+ ..CameraFeed::default()
+ };
+ if !live {
+ drop(token.take());
+ }
+ if cancelled {
+ camera.setup_cancel.cancel();
+ }
+ let feed = CameraFeed::spawn(camera);
+ let id = replacement.id.clone();
+ let accepted = feed
+ .ask(LockedCameraInputReconnected {
+ generation,
+ lock_generation,
+ id: replacement.id,
+ camera_info: replacement.camera_info,
+ video_info: replacement.video_info,
+ done_tx: replacement.done_tx,
+ })
+ .await
+ .unwrap();
+ assert_eq!(accepted, expected);
+ assert_eq!(
+ matches!(replacement_rx.try_recv(), Err(mpsc::TryRecvError::Empty)),
+ expected,
+ );
+ if accepted {
+ feed.ask(FinalizePendingRelease {
+ generation: 11,
+ id: id.clone(),
+ })
+ .await
+ .unwrap();
+ assert!(matches!(
+ original_rx.try_recv(),
+ Err(mpsc::TryRecvError::Empty)
+ ));
+ feed.ask(FinalizePendingRelease { generation: 12, id })
+ .await
+ .unwrap();
+ assert!(original_rx.try_recv().is_ok());
+ }
+ drop(token);
+ feed.kill();
+ feed.wait_for_stop().await;
+ }
+ }
+
#[tokio::test]
async fn camera_late_connection_notification_keeps_locked_feed_alive() {
let (feed, lock, connection, _ready) = locked_test_camera().await;
diff --git a/crates/recording/src/feeds/microphone.rs b/crates/recording/src/feeds/microphone.rs
index cef3f91aa..6eadd4053 100644
--- a/crates/recording/src/feeds/microphone.rs
+++ b/crates/recording/src/feeds/microphone.rs
@@ -28,6 +28,57 @@ pub type MicrophonesMap = IndexMap<String, (Device, SupportedStreamConfig)>;
type StreamReadyFuture =
BoxFuture<'static, Result<(SupportedStreamConfig, Option<u32>), SetInputError>>;
+pub const SETUP_TIMEOUT: Duration = Duration::from_secs(10);
+const MAX_CONCURRENT_SETUPS: usize = 2;
+
+fn bounded_stream_ready(
+ ready: StreamReadyFuture,
+ cancel: tokio_util::sync::CancellationToken,
+ timeout: Duration,
+) -> StreamReadyFuture {
+ let deadline = tokio::time::Instant::now() + timeout;
+ let cancel_on_drop = cancel.clone().drop_guard();
+ async move {
+ let _cancel_on_drop = cancel_on_drop;
+ tokio::select! {
+ biased;
+ _ = cancel.cancelled() => Err(SetInputError::SetupCancelled),
+ result = tokio::time::timeout_at(deadline, ready) => {
+ result.unwrap_or_else(|_| {
+ cancel.cancel();
+ Err(SetInputError::SetupTimedOut)
+ })
+ }
+ }
+ }
+ .boxed()
+}
+
+async fn spawn_setup_worker(
+ name: String,
+ slots: Arc<tokio::sync::Semaphore>,
+ cancel: tokio_util::sync::CancellationToken,
+ worker: impl FnOnce(tokio::sync::OwnedSemaphorePermit) + Send + 'static,
+) -> Result<(), SetInputError> {
+ let permit = tokio::select! {
+ biased;
+ _ = cancel.cancelled() => return Err(SetInputError::SetupCancelled),
+ permit = slots.acquire_owned() => permit.map_err(|error| {
+ SetInputError::BuildStream(format!("Microphone setup is unavailable: {error}"))
+ })?,
+ };
+ if cancel.is_cancelled() {
+ return Err(SetInputError::SetupCancelled);
+ }
+ std::thread::Builder::new()
+ .name(name)
+ .spawn(move || worker(permit))
+ .map(drop)
+ .map_err(|error| {
+ SetInputError::BuildStream(format!("Could not start microphone worker: {error}"))
+ })
+}
+
const SAMPLE_RATE_ESTIMATE_MIN_INTERVALS: u32 = 4;
const SAMPLE_RATE_ESTIMATE_MIN_DELTA: Duration = Duration::from_millis(2);
const SAMPLE_RATE_ESTIMATE_MAX_DELTA: Duration = Duration::from_millis(250);
@@ -551,6 +602,7 @@ impl RecordingSourceHealth {
state.pending = None;
}
+ #[cfg(test)]
fn fail_current(&self, generation: u64, id: u32, error: String) {
let mut state = self.0.lock().unwrap();
if state.generation == generation && state.current.id == id {
@@ -780,6 +832,7 @@ impl WindowsReconnect {
let done_tx = self.done_tx.clone();
ConnectingState {
id,
+ _cancel_setup: None,
ready: self
.ready
.clone()
@@ -799,6 +852,7 @@ impl WindowsReconnect {
#[derive(Actor)]
pub struct MicrophoneFeed {
+ setup_slots: Arc<tokio::sync::Semaphore>,
#[cfg(windows)]
selection_generation: u64,
#[cfg(windows)]
@@ -942,6 +996,7 @@ impl OpenState {
struct ConnectingState {
id: u32,
+ _cancel_setup: Option<tokio_util::sync::DropGuard>,
ready: BoxFuture<'static, Result<InputConnected, SetInputError>>,
}
@@ -1054,6 +1109,7 @@ fn list_input_device_names() -> Vec<String> {
impl MicrophoneFeed {
pub fn new(error_sender: flume::Sender<StreamError>) -> Self {
Self {
+ setup_slots: Arc::new(tokio::sync::Semaphore::new(MAX_CONCURRENT_SETUPS)),
#[cfg(target_os = "linux")]
pulse_input_role: crate::sources::screen_capture::PulseInputRole::Microphone,
#[cfg(target_os = "linux")]
@@ -1130,6 +1186,32 @@ impl MicrophoneFeed {
device_map
}
+ fn device_with_settings(
+ label: &str,
+ settings: Option<&MicrophoneDeviceSettings>,
+ ) -> Option<(Device, SupportedStreamConfig)> {
+ let host = cpal::default_host();
+ let configure = |device| {
+ get_usable_device(device, settings).map(|(_, device, config)| (device, config))
+ };
+ if let Some(device) = configure_named_device(
+ host.default_input_device(),
+ label,
+ |device| device.name().ok(),
+ configure,
+ ) {
+ return Some(device);
+ }
+ let devices = match host.devices() {
+ Ok(devices) => devices,
+ Err(error) => {
+ error!("Could not access audio input devices: {error}");
+ return None;
+ }
+ };
+ configure_named_device(devices, label, |device| device.name().ok(), configure)
+ }
+
fn spawn_input_stream(params: StreamSpawnParams) -> (StreamReadyFuture, SyncSender<()>) {
let StreamSpawnParams {
#[cfg(any(target_os = "linux", windows))]
@@ -1140,58 +1222,59 @@ impl MicrophoneFeed {
system_stream_cancel,
id,
label,
- device,
- config,
- stream_config,
- buffer_size_frames,
- sample_format,
+ settings,
+ setup_cancel,
+ setup_slots,
+ previous_input,
actor_ref,
error_sender,
dropped_message_count,
log_action,
} = params;
- let (ready_tx, ready_rx) = oneshot::channel::<Result<Option<u32>, SetInputError>>();
+ let (ready_tx, ready_rx) = oneshot::channel();
+ let (started_tx, started_rx) = oneshot::channel();
let (done_tx, done_rx) = mpsc::sync_channel(0);
- let ready = {
- let config_for_ready = config.clone();
- ready_rx
- .map(move |v| {
- let config = config_for_ready.clone();
- v.map_err(|_| SetInputError::BuildStreamCrashed)
- .and_then(|inner| inner)
- .map(|buffer_size| (config, buffer_size))
- })
- .boxed()
- };
+ let ready = bounded_stream_ready(
+ async move {
+ started_rx
+ .await
+ .unwrap_or(Err(SetInputError::BuildStreamCrashed))?;
+ ready_rx
+ .await
+ .unwrap_or(Err(SetInputError::BuildStreamCrashed))
+ }
+ .boxed(),
+ setup_cancel.clone(),
+ SETUP_TIMEOUT,
+ );
- std::thread::spawn({
- let stream_config = stream_config.clone();
- 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 || {
+ tokio::spawn(async move {
+ let worker = spawn_setup_worker(
+ format!("microphone-input-{id}"),
+ setup_slots,
+ setup_cancel.clone(),
+ move |setup_permit| {
#[cfg(windows)]
let mut exit_health = StreamExitHealth {
health: health.clone(),
expected: false,
};
- let device_name_for_log = device.name().ok();
-
- if let Some(ref name) = device_name_for_log {
- info!("Device '{}' available configs:", name);
- for config in device.supported_input_configs().into_iter().flatten() {
- info!(
- " Format: {:?}, Min rate: {}, Max rate: {}, Sample size: {}",
- config.sample_format(),
- config.min_sample_rate().0,
- config.max_sample_rate().0,
- config.sample_format().sample_size()
- );
- }
+ if setup_cancel.is_cancelled() || ready_tx.is_canceled() {
+ return;
}
+ let Some((device, config)) = Self::device_with_settings(&label, settings.as_ref())
+ else {
+ let _ = ready_tx.send(Err(SetInputError::DeviceNotFound));
+ return;
+ };
+ if setup_cancel.is_cancelled() || ready_tx.is_canceled() {
+ return;
+ }
+ let sample_format = config.sample_format();
+ let (stream_config, buffer_size_frames) =
+ stream_config_with_latency(&config, Some(&label));
let buffer_size_description = match &stream_config.buffer_size {
BufferSize::Default => "default".to_string(),
@@ -1203,11 +1286,10 @@ impl MicrophoneFeed {
};
info!(
- "🎤 {} stream (id {}, label '{}') for '{:?}' with config: rate={}, channels={}, format={:?}, buffer_size={}",
+ "🎤 {} stream (id {}, label '{}') with config: rate={}, channels={}, format={:?}, buffer_size={}",
log_action.verb(),
id,
label,
- device_name_for_log,
config.sample_rate().0,
config.channels(),
sample_format,
@@ -1262,6 +1344,12 @@ impl MicrophoneFeed {
#[cfg(target_os = "linux")]
let routed_at = Arc::new(std::sync::OnceLock::<cap_timestamp::Timestamps>::new());
+ if setup_cancel.is_cancelled() || ready_tx.is_canceled() {
+ return;
+ }
+ if let Some(previous_input) = previous_input {
+ let _ = previous_input.send(());
+ }
let stream = match device.build_input_stream_raw(
&stream_config,
sample_format,
@@ -1395,6 +1483,9 @@ impl MicrophoneFeed {
}
};
+ if setup_cancel.is_cancelled() || ready_tx.is_canceled() {
+ return;
+ }
if let Err(e) = stream.play() {
let _ = ready_tx.send(Err(SetInputError::PlayStream(e.to_string())));
return;
@@ -1417,7 +1508,10 @@ impl MicrophoneFeed {
return;
}
- let _ = ready_tx.send(Ok(buffer_size_frames));
+ if ready_tx.send(Ok((config, buffer_size_frames))).is_err() {
+ return;
+ }
+ drop(setup_permit);
match done_rx.recv() {
Ok(_) => debug!("Microphone actor shut down, ending stream"),
@@ -1427,13 +1521,29 @@ impl MicrophoneFeed {
{
exit_health.expected = true;
}
- }
+ },
+ )
+ .await;
+ let _ = started_tx.send(worker);
});
(ready, done_tx)
}
}
+fn configure_named_device<T, C>(
+ devices: impl IntoIterator<Item = T>,
+ label: &str,
+ mut name: impl FnMut(&T) -> Option<String>,
+ mut configure: impl FnMut(T) -> Option<C>,
+) -> Option<C> {
+ devices.into_iter().find_map(|device| {
+ (name(&device).as_deref() == Some(label))
+ .then(|| configure(device))
+ .flatten()
+ })
+}
+
fn get_usable_device(
device: Device,
settings: Option<&MicrophoneDeviceSettings>,
@@ -1795,9 +1905,7 @@ struct InputConnected {
}
struct LockedInputReconnected {
- #[cfg(any(target_os = "linux", windows))]
previous_id: u32,
- #[cfg(any(target_os = "linux", windows))]
generation: u64,
id: u32,
label: String,
@@ -1856,11 +1964,10 @@ struct StreamSpawnParams {
system_stream_cancel: tokio_util::sync::CancellationToken,
id: u32,
label: String,
- device: Device,
- config: SupportedStreamConfig,
- stream_config: cpal::StreamConfig,
- buffer_size_frames: Option<u32>,
- sample_format: SampleFormat,
+ settings: Option<MicrophoneDeviceSettings>,
+ setup_cancel: tokio_util::sync::CancellationToken,
+ setup_slots: Arc<tokio::sync::Semaphore>,
+ previous_input: Option<SyncSender<()>>,
actor_ref: ActorRef<MicrophoneFeed>,
error_sender: flume::Sender<StreamError>,
dropped_message_count: Arc<AtomicU64>,
@@ -1881,6 +1988,10 @@ pub enum SetInputError {
DeviceNotFound,
#[error("BuildStreamCrashed")]
BuildStreamCrashed,
+ #[error("Microphone setup was cancelled by a newer selection")]
+ SetupCancelled,
+ #[error("Timed out opening the microphone. Reconnect it or choose another microphone.")]
+ SetupTimedOut,
// we use strings for these as the cpal errors aren't Clone
#[error("BuildStream: {0}")]
BuildStream(String),
@@ -1912,11 +2023,6 @@ impl MicrophoneFeed {
self.input_id_counter += 1;
let label = msg.label.clone();
- let Some((device, config)) =
- Self::list_with_settings(msg.settings.as_ref()).swap_remove(&label)
- else {
- return Err(SetInputError::DeviceNotFound);
- };
#[cfg(target_os = "linux")]
if self.pulse_input_role
@@ -1930,11 +2036,8 @@ impl MicrophoneFeed {
self.selection_generation = self.selection_generation.wrapping_add(1);
self.recording_reconnect = None;
}
- let sample_format = config.sample_format();
- let (stream_config, buffer_size_frames) =
- stream_config_with_latency(&config, Some(&label));
-
let actor_ref = actor_ref.clone();
+ let setup_cancel = tokio_util::sync::CancellationToken::new();
#[cfg(any(target_os = "linux", windows))]
let health = {
let health = Arc::new(StreamHealth::new(id));
@@ -1952,11 +2055,10 @@ impl MicrophoneFeed {
system_stream_cancel: self.system_stream_cancel.clone(),
id,
label: label.clone(),
- device,
- config,
- stream_config,
- buffer_size_frames,
- sample_format,
+ settings: msg.settings,
+ setup_cancel: setup_cancel.clone(),
+ setup_slots: self.setup_slots.clone(),
+ previous_input: None,
actor_ref: actor_ref.clone(),
error_sender: self.error_sender.clone(),
dropped_message_count: self.dropped_message_count.clone(),
@@ -1966,6 +2068,7 @@ impl MicrophoneFeed {
state.connecting = Some(ConnectingState {
id,
+ _cancel_setup: Some(setup_cancel.drop_guard()),
ready: {
let done_tx = done_tx.clone();
ready
@@ -2050,30 +2153,11 @@ impl MicrophoneFeed {
}
let label = msg.label.clone();
- let Some((device, config)) =
- Self::list_with_settings(msg.settings.as_ref()).swap_remove(&label)
- else {
- #[cfg(target_os = "linux")]
- if let Some(recording) = &self.recording_health {
- recording.fail_current(
- self.lock_generation,
- inner.id,
- "Requested audio device unavailable during reconnect".into(),
- );
- }
- return Err(SetInputError::DeviceNotFound);
- };
-
- let sample_format = config.sample_format();
- let (stream_config, buffer_size_frames) =
- stream_config_with_latency(&config, Some(&label));
let new_id = self.input_id_counter;
self.input_id_counter += 1;
- #[cfg(any(target_os = "linux", windows))]
let previous_id = inner.id;
- #[cfg(any(target_os = "linux", windows))]
let generation = self.lock_generation;
#[cfg(target_os = "linux")]
if self.pulse_input_role
@@ -2082,8 +2166,6 @@ impl MicrophoneFeed {
self.system_stream_cancel.cancel();
self.system_stream_cancel = tokio_util::sync::CancellationToken::new();
}
- let _ = inner.done_tx.send(());
-
#[cfg(any(target_os = "linux", windows))]
let health = {
let health = Arc::new(StreamHealth::new(new_id));
@@ -2107,11 +2189,10 @@ impl MicrophoneFeed {
system_stream_cancel: self.system_stream_cancel.clone(),
id: new_id,
label: label.clone(),
- device,
- config,
- stream_config,
- buffer_size_frames,
- sample_format,
+ settings: msg.settings,
+ setup_cancel: tokio_util::sync::CancellationToken::new(),
+ setup_slots: self.setup_slots.clone(),
+ previous_input: Some(inner.done_tx.clone()),
actor_ref: actor_ref.clone(),
error_sender: self.error_sender.clone(),
dropped_message_count: self.dropped_message_count.clone(),
@@ -2171,9 +2252,7 @@ impl MicrophoneFeed {
Ok((config, buffer_size_frames)) => {
let _ = actor
.tell(LockedInputReconnected {
- #[cfg(any(target_os = "linux", windows))]
previous_id,
- #[cfg(any(target_os = "linux", windows))]
generation,
id: new_id,
label,
@@ -2553,7 +2632,13 @@ impl Message<Lock> for MicrophoneFeed {
if let Some(connecting) = &mut state.connecting {
let ready = &mut connecting.ready;
- let data = ready.await?;
+ let data = match ready.await {
+ Ok(data) => data,
+ Err(error) => {
+ connecting.ready = futures::future::ready(Err(error.clone())).boxed();
+ return Err(error.into());
+ }
+ };
state.handle_input_connected(data);
}
@@ -2709,6 +2794,13 @@ fn recording_reconnect_is_current(
impl MicrophoneFeed {
fn handle_locked_input_reconnected(&mut self, msg: LockedInputReconnected) {
+ #[cfg(target_os = "macos")]
+ if self.lock_generation != msg.generation
+ || !matches!(&self.state, State::Locked { inner, token }
+ if inner.id == msg.previous_id && inner.label == msg.label && token.strong_count() > 0)
+ {
+ return;
+ }
#[cfg(windows)]
{
let current = match &self.state {
@@ -2967,6 +3059,356 @@ impl Message<Unlock> for MicrophoneFeed {
mod tests {
use super::*;
+ #[tokio::test]
+ async fn dropping_microphone_readiness_cancels_queued_native_work() {
+ let slots = Arc::new(tokio::sync::Semaphore::new(0));
+ let cancel = tokio_util::sync::CancellationToken::new();
+ let ready = bounded_stream_ready(
+ futures::future::pending().boxed(),
+ cancel.clone(),
+ SETUP_TIMEOUT,
+ );
+ let (started_tx, started_rx) = flume::bounded(1);
+ let queued = tokio::spawn(spawn_setup_worker(
+ "test-dropped-readiness".into(),
+ slots.clone(),
+ cancel,
+ move |_| started_tx.send(()).unwrap(),
+ ));
+ tokio::task::yield_now().await;
+ drop(ready);
+ assert!(matches!(
+ tokio::time::timeout(Duration::from_secs(1), queued)
+ .await
+ .unwrap()
+ .unwrap(),
+ Err(SetInputError::SetupCancelled)
+ ));
+ slots.add_permits(1);
+ assert!(started_rx.is_empty());
+ }
+
+ #[tokio::test]
+ async fn stuck_microphone_setups_bound_workers_and_cancel_queued_selections() {
+ let slots = Arc::new(tokio::sync::Semaphore::new(MAX_CONCURRENT_SETUPS));
+ let (started_tx, started_rx) = flume::bounded(MAX_CONCURRENT_SETUPS + 1);
+ let (stopped_tx, stopped_rx) = flume::bounded(MAX_CONCURRENT_SETUPS);
+ let mut release = Vec::new();
+ for index in 0..MAX_CONCURRENT_SETUPS {
+ let (release_tx, release_rx) = mpsc::channel();
+ release.push(release_tx);
+ let started = started_tx.clone();
+ let stopped = stopped_tx.clone();
+ spawn_setup_worker(
+ format!("test-stuck-microphone-{index}"),
+ slots.clone(),
+ tokio_util::sync::CancellationToken::new(),
+ move |permit| {
+ started.send(()).unwrap();
+ release_rx.recv().unwrap();
+ drop(permit);
+ stopped.send(()).unwrap();
+ },
+ )
+ .await
+ .unwrap();
+ }
+ for _ in 0..MAX_CONCURRENT_SETUPS {
+ started_rx.recv_async().await.unwrap();
+ }
+ assert_eq!(slots.available_permits(), 0);
+ for _ in 0..32 {
+ let cancel = tokio_util::sync::CancellationToken::new();
+ let started = started_tx.clone();
+ let queued = tokio::spawn(spawn_setup_worker(
+ "test-cancelled-microphone".into(),
+ slots.clone(),
+ cancel.clone(),
+ move |_| started.send(()).unwrap(),
+ ));
+ tokio::task::yield_now().await;
+ cancel.cancel();
+ assert!(matches!(
+ tokio::time::timeout(Duration::from_secs(1), queued)
+ .await
+ .unwrap()
+ .unwrap(),
+ Err(SetInputError::SetupCancelled)
+ ));
+ }
+ assert!(started_rx.is_empty());
+ release[0].send(()).unwrap();
+ stopped_rx.recv_async().await.unwrap();
+ spawn_setup_worker(
+ "test-healthy-microphone".into(),
+ slots,
+ tokio_util::sync::CancellationToken::new(),
+ move |_| started_tx.send(()).unwrap(),
+ )
+ .await
+ .unwrap();
+ started_rx.recv_async().await.unwrap();
+ for release in &release[1..] {
+ release.send(()).unwrap();
+ stopped_rx.recv_async().await.unwrap();
+ }
+ assert!(started_rx.is_empty());
+ }
+
+ #[test]
+ fn selecting_a_microphone_does_not_configure_unrelated_devices() {
+ let mut configured = Vec::new();
+ let selected = configure_named_device(
+ ["slow unrelated microphone", "requested microphone", "other"],
+ "requested microphone",
+ |name| Some((*name).to_string()),
+ |name| {
+ configured.push(name);
+ Some(name)
+ },
+ );
+ assert_eq!(selected, Some("requested microphone"));
+ assert_eq!(configured, ["requested microphone"]);
+ }
+
+ #[test]
+ fn named_microphone_selection_preserves_first_usable_duplicate() {
+ let mut configured = Vec::new();
+ let selected = configure_named_device(
+ [
+ ("requested", 0),
+ ("other", 1),
+ ("requested", 2),
+ ("requested", 3),
+ ],
+ "requested",
+ |(name, _)| Some((*name).to_string()),
+ |(_, index)| {
+ configured.push(index);
+ (index != 0).then_some(index)
+ },
+ );
+ assert_eq!(selected, Some(2));
+ assert_eq!(configured, [0, 2]);
+ }
+
+ #[tokio::test]
+ async fn stalled_microphone_setup_releases_lock_mailbox_and_native_readiness() {
+ let (error_tx, _error_rx) = flume::bounded(1);
+ let (native_tx, native_rx) = oneshot::channel();
+ let cancel = tokio_util::sync::CancellationToken::new();
+ let ready = bounded_stream_ready(
+ async move { native_rx.await.unwrap() }.boxed(),
+ cancel.clone(),
+ Duration::from_millis(20),
+ );
+ let (done_tx, _done_rx) = mpsc::sync_channel(1);
+ let mut microphone = MicrophoneFeed::new(error_tx);
+ microphone.state = State::Open(OpenState {
+ connecting: Some(ConnectingState {
+ id: 1,
+ _cancel_setup: Some(cancel.drop_guard()),
+ ready: ready
+ .map(move |result| {
+ result.map(|(config, buffer_size_frames)| InputConnected {
+ id: 1,
+ label: "requested".into(),
+ config,
+ buffer_size_frames,
+ done_tx,
+ })
+ })
+ .boxed(),
+ }),
+ attached: None,
+ });
+ let actor = MicrophoneFeed::spawn(microphone);
+ let locked = tokio::time::timeout(Duration::from_secs(1), actor.ask(Lock))
+ .await
+ .expect("microphone setup blocked the actor mailbox");
+ assert!(matches!(
+ locked,
+ Err(kameo::error::SendError::HandlerError(
+ LockFeedError::InitializeFailed(SetInputError::SetupTimedOut)
+ ))
+ ));
+ assert!(native_tx.is_canceled());
+ actor.ask(RemoveInput).await.unwrap();
+ assert!(matches!(
+ actor.ask(Lock).await,
+ Err(kameo::error::SendError::HandlerError(
+ LockFeedError::NoInput
+ ))
+ ));
+ actor.kill();
+ actor.wait_for_stop().await;
+ }
+
+ #[tokio::test]
+ async fn queued_locks_keep_setup_failure_without_locking_the_previous_microphone() {
+ let (error_tx, _error_rx) = flume::bounded(1);
+ let (native_tx, native_rx) = oneshot::channel();
+ let cancel = tokio_util::sync::CancellationToken::new();
+ let ready = bounded_stream_ready(
+ async move { native_rx.await.unwrap() }.boxed(),
+ cancel.clone(),
+ Duration::from_millis(20),
+ )
+ .shared();
+ let (previous_tx, _previous_rx) = mpsc::sync_channel(1);
+ let (done_tx, _done_rx) = mpsc::sync_channel(1);
+ let mut microphone = MicrophoneFeed::new(error_tx);
+ microphone.state = State::Open(OpenState {
+ connecting: Some(ConnectingState {
+ id: 2,
+ _cancel_setup: Some(cancel.drop_guard()),
+ ready: ready
+ .map(move |result| {
+ result.map(|(config, buffer_size_frames)| InputConnected {
+ id: 2,
+ label: "requested".into(),
+ config,
+ buffer_size_frames,
+ done_tx,
+ })
+ })
+ .boxed(),
+ }),
+ attached: Some(AttachedState {
+ id: 1,
+ label: "previous".into(),
+ config: SupportedStreamConfig::new(
+ 1,
+ cpal::SampleRate(48_000),
+ cpal::SupportedBufferSize::Unknown,
+ SampleFormat::F32,
+ ),
+ buffer_size_frames: None,
+ done_tx: previous_tx,
+ }),
+ });
+ let actor = MicrophoneFeed::spawn(microphone);
+ let results = tokio::time::timeout(Duration::from_secs(1), async {
+ tokio::join!(actor.ask(Lock), actor.ask(Lock), actor.ask(Lock))
+ })
+ .await
+ .expect("repeated microphone locks blocked the actor mailbox");
+ for result in [results.0, results.1, results.2] {
+ assert!(matches!(
+ result,
+ Err(kameo::error::SendError::HandlerError(
+ LockFeedError::InitializeFailed(SetInputError::SetupTimedOut)
+ ))
+ ));
+ }
+ assert!(native_tx.is_canceled());
+ assert_eq!(actor.ask(GetDroppedMessageCount).await.unwrap(), 0);
+ actor.ask(InputConnectFailed { id: 2 }).await.unwrap();
+ let previous = actor.ask(Lock).await.unwrap();
+ assert_eq!(previous.device_name(), "previous");
+ drop(previous);
+ actor.kill();
+ actor.wait_for_stop().await;
+ }
+
+ #[tokio::test]
+ async fn deselecting_pending_microphone_cancels_all_readiness_waiters() {
+ let (error_tx, _error_rx) = flume::bounded(1);
+ let (native_tx, native_rx) = oneshot::channel();
+ let cancel = tokio_util::sync::CancellationToken::new();
+ let ready = bounded_stream_ready(
+ async move { native_rx.await.unwrap() }.boxed(),
+ cancel.clone(),
+ SETUP_TIMEOUT,
+ )
+ .shared();
+ let (done_tx, _done_rx) = mpsc::sync_channel(1);
+ let mut microphone = MicrophoneFeed::new(error_tx);
+ microphone.state = State::Open(OpenState {
+ connecting: Some(ConnectingState {
+ id: 1,
+ _cancel_setup: Some(cancel.drop_guard()),
+ ready: ready
+ .clone()
+ .map(move |result| {
+ result.map(|(config, buffer_size_frames)| InputConnected {
+ id: 1,
+ label: "requested".into(),
+ config,
+ buffer_size_frames,
+ done_tx,
+ })
+ })
+ .boxed(),
+ }),
+ attached: None,
+ });
+ let actor = MicrophoneFeed::spawn(microphone);
+ actor.ask(RemoveInput).await.unwrap();
+ assert!(matches!(
+ tokio::time::timeout(Duration::from_secs(1), ready)
+ .await
+ .expect("deselection left setup running"),
+ Err(SetInputError::SetupCancelled)
+ ));
+ assert!(native_tx.is_canceled());
+ assert_eq!(actor.ask(GetDroppedMessageCount).await.unwrap(), 0);
+ actor.kill();
+ actor.wait_for_stop().await;
+ }
+
+ #[cfg(target_os = "macos")]
+ #[test]
+ fn macos_reconnect_requires_the_original_live_recording_and_stream() {
+ for (generation, previous_id, live, accepted) in [
+ (7, 41, true, false),
+ (8, 40, true, false),
+ (8, 41, false, false),
+ (8, 41, true, true),
+ ] {
+ let (error_tx, _error_rx) = flume::bounded(1);
+ let (original_tx, _original_rx) = mpsc::sync_channel(1);
+ let (replacement_tx, replacement_rx) = mpsc::sync_channel(1);
+ let config = SupportedStreamConfig::new(
+ 1,
+ cpal::SampleRate(48_000),
+ cpal::SupportedBufferSize::Unknown,
+ SampleFormat::F32,
+ );
+ let mut token = Some(Arc::new(()));
+ let mut microphone = MicrophoneFeed::new(error_tx);
+ microphone.lock_generation = 8;
+ microphone.state = State::Locked {
+ inner: AttachedState {
+ id: 41,
+ label: "requested".into(),
+ config: config.clone(),
+ buffer_size_frames: None,
+ done_tx: original_tx,
+ },
+ token: Arc::downgrade(token.as_ref().unwrap()),
+ };
+ if !live {
+ drop(token.take());
+ }
+ microphone.handle_locked_input_reconnected(LockedInputReconnected {
+ previous_id,
+ generation,
+ id: 42,
+ label: "requested".into(),
+ config,
+ buffer_size_frames: None,
+ done_tx: replacement_tx,
+ });
+ assert!(matches!(&microphone.state, State::Locked { inner, .. }
+ if inner.id == if accepted { 42 } else { 41 }));
+ assert_eq!(
+ matches!(replacement_rx.try_recv(), Err(mpsc::TryRecvError::Empty)),
+ accepted,
+ );
+ }
+ }
+
#[test]
fn repeated_stream_errors_are_coalesced_while_a_notification_is_pending() {
let (sender, receiver) = flume::unbounded();
@@ -3363,6 +3805,7 @@ mod tests {
microphone.state = State::Open(OpenState {
connecting: Some(ConnectingState {
id: 1,
+ _cancel_setup: None,
ready: futures::future::ready(Ok(InputConnected {
id: 1,
label: "test microphone".to_string(),
@@ -4208,7 +4651,11 @@ mod recording_subscription_tests {
let ready: BoxFuture<'static, Result<InputConnected, SetInputError>> =
futures::future::pending().boxed();
feed.state = State::Open(OpenState {
- connecting: Some(ConnectingState { id: 9, ready }),
+ connecting: Some(ConnectingState {
+ id: 9,
+ _cancel_setup: None,
+ ready,
+ }),
attached: None,
});
let actor = MicrophoneFeed::spawn(feed);
diff --git a/crates/recording/src/output_pipeline/oop_muxer.rs b/crates/recording/src/output_pipeline/oop_muxer.rs
index a047101d1..26baa205a 100644
--- a/crates/recording/src/output_pipeline/oop_muxer.rs
+++ b/crates/recording/src/output_pipeline/oop_muxer.rs
@@ -640,6 +640,7 @@ fn spawn_stderr_reader(
pub struct RespawningMuxerSubprocess {
current: Option<MuxerSubprocess>,
+ disk_full_reason: Option<String>,
bin_path: PathBuf,
config: MuxerSubprocessConfig,
health_tx: Option<HealthSender>,
@@ -664,6 +665,7 @@ impl RespawningMuxerSubprocess {
)?);
Ok(Self {
current,
+ disk_full_reason: None,
bin_path,
config,
health_tx,
@@ -702,6 +704,10 @@ impl RespawningMuxerSubprocess {
where
F: FnMut(&mut MuxerSubprocess) -> Result<(), MuxerSubprocessError>,
{
+ if let Some(reason) = &self.disk_full_reason {
+ return Err(MuxerSubprocessError::DiskFull(reason.clone()));
+ }
+
loop {
let Some(current) = self.current.as_mut() else {
if self.consecutive_fast_failures > self.max_consecutive_fast_failures {
@@ -716,7 +722,7 @@ impl RespawningMuxerSubprocess {
match op(current) {
Ok(()) => return Ok(()),
Err(MuxerSubprocessError::DiskFull(reason)) => {
- self.current = None;
+ self.disk_full_reason = Some(reason.clone());
return Err(MuxerSubprocessError::DiskFull(reason));
}
Err(MuxerSubprocessError::Crashed(reason)) => {
@@ -822,3 +828,83 @@ pub fn feature_enabled() -> bool {
pub fn output_path_from_dir(dir: &Path) -> PathBuf {
dir.to_path_buf()
}
+
+#[cfg(all(test, unix))]
+mod tests {
+ use super::*;
+ use std::os::unix::fs::PermissionsExt;
+
+ fn exited_subprocess(
+ exit_code: u8,
+ max_failures: u32,
+ ) -> (tempfile::TempDir, RespawningMuxerSubprocess) {
+ let directory = tempfile::tempdir().unwrap();
+ let binary = directory.path().join("muxer");
+ std::fs::write(
+ &binary,
+ format!(
+ "#!/bin/sh\nwhile [ ! -f \"$0.exit\" ]; do sleep 0.01; done\nexit {exit_code}\n"
+ ),
+ )
+ .unwrap();
+ std::fs::set_permissions(&binary, std::fs::Permissions::from_mode(0o700)).unwrap();
+ let config = MuxerSubprocessConfig {
+ output_directory: directory.path().join("video"),
+ init_segment_name: "init.mp4".into(),
+ media_segment_pattern: "segment_$Number%03d$.m4s".into(),
+ video_init: None,
+ audio_init: None,
+ };
+ let mut subprocess =
+ RespawningMuxerSubprocess::new(binary, config, None, max_failures).unwrap();
+ std::fs::write(directory.path().join("muxer.exit"), b"").unwrap();
+ let status = subprocess
+ .current
+ .as_mut()
+ .unwrap()
+ .child
+ .as_mut()
+ .unwrap()
+ .wait()
+ .unwrap();
+ assert_eq!(status.code(), Some(i32::from(exit_code)));
+ (directory, subprocess)
+ }
+
+ #[test]
+ fn disk_full_stays_terminal_and_finish_confirms_shutdown() {
+ let (_directory, mut subprocess) = exited_subprocess(EXIT_DISK_FULL, 2);
+ let error = subprocess
+ .write_video_packet(0, 0, 1, true, &vec![0; 2 * 1024 * 1024])
+ .unwrap_err();
+ assert!(matches!(error, MuxerSubprocessError::DiskFull(_)));
+
+ for _ in 0..3 {
+ assert!(matches!(
+ subprocess.write_video_packet(1, 1, 1, false, &[0]),
+ Err(MuxerSubprocessError::DiskFull(_))
+ ));
+ assert!(matches!(
+ subprocess.write_audio_packet(1, 1, 1, &[0]),
+ Err(MuxerSubprocessError::DiskFull(_))
+ ));
+ }
+ assert_eq!(subprocess.respawn_attempts(), 0);
+
+ let error = subprocess.finish().unwrap_err();
+ assert!(error.child_reaped());
+ assert!(matches!(
+ error,
+ MuxerSubprocessFinishError::Reaped(MuxerSubprocessError::DiskFull(_))
+ ));
+ }
+
+ #[test]
+ fn missing_child_does_not_claim_confirmed_shutdown() {
+ let (_directory, mut subprocess) = exited_subprocess(EXIT_DISK_FULL, 2);
+ drop(subprocess.current.take());
+ let error = subprocess.finish().unwrap_err();
+ assert!(!error.child_reaped());
+ assert!(matches!(error, MuxerSubprocessFinishError::Unconfirmed(_)));
+ }
+}
diff --git a/crates/recording/src/sources/screen_capture/macos.rs b/crates/recording/src/sources/screen_capture/macos.rs
index 462b83a58..66972d65e 100644
--- a/crates/recording/src/sources/screen_capture/macos.rs
+++ b/crates/recording/src/sources/screen_capture/macos.rs
@@ -28,6 +28,45 @@ use tracing::{debug, error, info, warn};
const MAX_CAPTURE_RESTARTS: u32 = 3;
const RESTART_DELAY: Duration = Duration::from_secs(2);
+fn excluded_shareable_windows(
+ excluded_windows: &[WindowId],
+ content: &sc::ShareableContent,
+ capture_phase: &'static str,
+) -> Vec<arc::R<sc::Window>> {
+ if excluded_windows.is_empty() {
+ return Vec::new();
+ }
+
+ let windows = content.windows();
+ let mut collected = Vec::new();
+ for window_id in excluded_windows {
+ let Ok(native_id) = window_id.to_string().parse::<u32>() else {
+ warn!(%window_id, capture_phase, "Excluded window has an invalid native id");
+ continue;
+ };
+
+ // New or protected panels can be absent from the CG on-screen list
+ // while still belonging to the snapshot used to build this filter.
+ if let Some(window) = windows.iter().find(|window| window.id() == native_id) {
+ collected.push(window.retained());
+ } else {
+ warn!(
+ %window_id,
+ capture_phase,
+ "Excluded window missing from ScreenCaptureKit shareable content"
+ );
+ }
+ }
+
+ info!(
+ capture_phase,
+ configured_excluded_windows = excluded_windows.len(),
+ mapped_excluded_windows = collected.len(),
+ "Mapped ScreenCaptureKit excluded windows"
+ );
+ collected
+}
+
struct FrameScaler {
session: arc::R<cidre::vt::PixelTransferSession>,
pool: arc::R<cv::PixelBufPool>,
@@ -180,37 +219,8 @@ impl ScreenCaptureConfig<CMSampleBufferCapture> {
let display = Display::from_id(&self.config.display)
.ok_or_else(|| SourceError::NoDisplay(self.config.display.clone()))?;
- let excluded_sc_windows = if self.excluded_windows.is_empty() {
- Vec::new()
- } else {
- let mut collected = Vec::new();
-
- for window_id in &self.excluded_windows {
- let Some(window) = Window::from_id(window_id) else {
- warn!(%window_id, "Excluded window id no longer resolves");
- continue;
- };
-
- if let Some(sc_window) = window.raw_handle().as_sc(self.shareable_content.clone()) {
- collected.push(sc_window);
- } else {
- warn!(
- %window_id,
- window_title = ?window.name(),
- owner_name = ?window.owner_name(),
- "Excluded window missing from ScreenCaptureKit shareable content"
- );
- }
- }
-
- info!(
- configured_excluded_windows = self.excluded_windows.len(),
- mapped_excluded_windows = collected.len(),
- "Mapped ScreenCaptureKit excluded windows"
- );
-
- collected
- };
+ let excluded_sc_windows =
+ excluded_shareable_windows(&self.excluded_windows, &self.shareable_content, "initial");
let content_filter = display
.raw_handle()
@@ -938,33 +948,8 @@ async fn rebuild_capturer(params: &CapturerRebuildParams) -> anyhow::Result<Capt
let display = Display::from_id(&params.display_id)
.ok_or_else(|| anyhow!("Display not found during restart: {:?}", params.display_id))?;
- let excluded_sc_windows = if params.excluded_windows.is_empty() {
- Vec::new()
- } else {
- let mut collected = Vec::new();
- for window_id in &params.excluded_windows {
- let Some(window) = Window::from_id(window_id) else {
- warn!(%window_id, "Excluded screenshot window id no longer resolves");
- continue;
- };
- if let Some(sc_window) = window.raw_handle().as_sc(shareable_content.clone()) {
- collected.push(sc_window);
- } else {
- warn!(
- %window_id,
- window_title = ?window.name(),
- owner_name = ?window.owner_name(),
- "Excluded screenshot window missing from ScreenCaptureKit shareable content"
- );
- }
- }
- info!(
- configured_excluded_windows = params.excluded_windows.len(),
- mapped_excluded_windows = collected.len(),
- "Mapped screenshot ScreenCaptureKit excluded windows"
- );
- collected
- };
+ let excluded_sc_windows =
+ excluded_shareable_windows(&params.excluded_windows, &shareable_content, "restart");
let content_filter = display
.raw_handle()
diff --git a/crates/scap-screencapturekit/src/capture.rs b/crates/scap-screencapturekit/src/capture.rs
index 6d8dcc1de..877a43300 100644
--- a/crates/scap-screencapturekit/src/capture.rs
+++ b/crates/scap-screencapturekit/src/capture.rs
@@ -4,9 +4,44 @@ use cidre::{
};
define_obj_type!(
- pub CapturerCallbacks + StreamOutputImpl + StreamDelegateImpl, CapturerCallbacksInner, CAPTURER
+ pub CapturerCallbacks + StreamOutputImpl + StreamDelegateImpl + CapturerCallbacksDeallocation,
+ CapturerCallbacksInner,
+ CAPTURER
);
+trait CapturerCallbacksDeallocation {
+ fn cls_add_methods(cls: &objc::Class<objc::Id>) {
+ extern "C" fn dealloc(callbacks: &mut CapturerCallbacks, selector: &objc::Sel) {
+ let object = callbacks as *mut CapturerCallbacks;
+ unsafe {
+ let superclass_dealloc: unsafe extern "C" fn(*mut CapturerCallbacks, &objc::Sel) =
+ std::mem::transmute(objc::NS_OBJECT.method_impl(selector));
+ std::ptr::drop_in_place(callbacks.inner_mut());
+ superclass_dealloc(object, selector);
+ }
+ }
+
+ // The pinned cidre macro drops only the Rust payload. Its later
+ // class_addMethod cannot replace this complete NSObject deallocator.
+ let added = unsafe {
+ objc::class_addMethod(
+ cls,
+ objc::sel_reg_name(c"dealloc".as_ptr().cast()),
+ std::mem::transmute::<
+ extern "C" fn(&mut CapturerCallbacks, &objc::Sel),
+ extern "C" fn(),
+ >(dealloc),
+ c"v@:".as_ptr().cast(),
+ )
+ };
+ assert!(added, "Capture delegate deallocator already registered");
+ }
+
+ fn cls_add_protocol(_: &objc::Class<objc::Id>) {}
+}
+
+impl CapturerCallbacksDeallocation for CapturerCallbacks {}
+
unsafe impl Send for CapturerCallbacks {}
unsafe impl Sync for CapturerCallbacks {}
@@ -214,3 +249,66 @@ impl CapturerBuilder {
})
}
}
+
+#[cfg(test)]
+mod deallocation_tests {
+ use super::*;
+ use std::{
+ ffi::c_void,
+ sync::{
+ Arc,
+ atomic::{AtomicUsize, Ordering},
+ },
+ };
+
+ #[link(name = "objc")]
+ unsafe extern "C" {
+ #[link_name = "objc_setAssociatedObject"]
+ fn set_associated_object(
+ object: *const c_void,
+ key: *const c_void,
+ value: *const c_void,
+ policy: usize,
+ );
+ }
+
+ static ASSOCIATION_KEY: u8 = 0;
+
+ struct DropCounter(Arc<AtomicUsize>);
+
+ impl Drop for DropCounter {
+ fn drop(&mut self) {
+ self.0.fetch_add(1, Ordering::SeqCst);
+ }
+ }
+
+ fn delegate(counter: DropCounter) -> arc::R<CapturerCallbacks> {
+ CapturerCallbacks::with(CapturerCallbacksInner {
+ did_output_sample_buf_cb: Some(Box::new(move |_| {
+ let _ = &counter;
+ })),
+ did_stop_with_err_cb: None,
+ })
+ }
+
+ #[test]
+ fn final_release_drops_payload_and_native_associated_objects_once() {
+ let drops = Arc::new(AtomicUsize::new(0));
+ for cycle in 0..100 {
+ let outer = delegate(DropCounter(drops.clone()));
+ let associated = delegate(DropCounter(drops.clone()));
+ unsafe {
+ set_associated_object(
+ std::ptr::from_ref(outer.as_ref()).cast(),
+ std::ptr::from_ref(&ASSOCIATION_KEY).cast(),
+ std::ptr::from_ref(associated.as_ref()).cast(),
+ 1,
+ );
+ }
+ drop(associated);
+ assert_eq!(drops.load(Ordering::SeqCst), cycle * 2);
+ drop(outer);
+ assert_eq!(drops.load(Ordering::SeqCst), (cycle + 1) * 2);
+ }
+ }
+}
diff --git a/crates/scap-targets/src/platform/macos.rs b/crates/scap-targets/src/platform/macos.rs
index 699ad57ca..a31e5a992 100644
--- a/crates/scap-targets/src/platform/macos.rs
+++ b/crates/scap-targets/src/platform/macos.rs
@@ -267,7 +267,7 @@ impl DisplayImpl {
fn get_cursor_position() -> Option<LogicalPosition> {
let event_source = core_graphics::event_source::CGEventSource::new(
- core_graphics::event_source::CGEventSourceStateID::Private,
+ core_graphics::event_source::CGEventSourceStateID::CombinedSessionState,
)
.ok()?;
diff --git a/crates/utils/src/linux_recording_stop.rs b/crates/utils/src/linux_recording_stop.rs
index 73ea4507d..660fd9240 100644
--- a/crates/utils/src/linux_recording_stop.rs
+++ b/crates/utils/src/linux_recording_stop.rs
@@ -64,6 +64,21 @@ impl StopTrayIcon {
argb,
})
}
+
+ fn with_visible_template_color(mut self) -> Self {
+ // StatusNotifier hosts render pixmaps literally; the macOS black template
+ // otherwise disappears on dark panels. This red contrasts on light and dark.
+ if self
+ .argb
+ .chunks_exact(4)
+ .all(|pixel| pixel[0] == 0 || pixel[1..] == [0, 0, 0])
+ {
+ for pixel in self.argb.chunks_exact_mut(4) {
+ pixel[1..].copy_from_slice(&[220, 38, 38]);
+ }
+ }
+ self
+ }
}
struct ActivationState {
@@ -235,7 +250,7 @@ impl StopTray {
}));
let item = StopItem {
generation,
- icon,
+ icon: icon.with_visible_template_color(),
events: sender.clone(),
state: state.clone(),
};
@@ -442,6 +457,43 @@ mod tests {
}
}
+ #[test]
+ fn black_stop_template_is_visible_on_dark_and_light_panels() {
+ let icon = StopTrayIcon::from_rgba(
+ 2,
+ 2,
+ &[0, 0, 0, 255, 0, 0, 0, 128, 0, 0, 0, 0, 0, 0, 0, 255],
+ )
+ .unwrap()
+ .with_visible_template_color();
+ let linear = |value: u8| {
+ let value = f64::from(value) / 255.;
+ if value <= 0.04045 {
+ value / 12.92
+ } else {
+ ((value + 0.055) / 1.055).powf(2.4)
+ }
+ };
+ let pixel = &icon.argb[..4];
+ let luminance =
+ 0.2126 * linear(pixel[1]) + 0.7152 * linear(pixel[2]) + 0.0722 * linear(pixel[3]);
+ assert!((luminance + 0.05) / 0.05 > 3.);
+ assert!(1.05 / (luminance + 0.05) > 3.);
+ assert_eq!(
+ icon.argb.iter().step_by(4).copied().collect::<Vec<_>>(),
+ [255, 128, 0, 255]
+ );
+ }
+
+ #[test]
+ fn colored_stop_icons_preserve_their_pixels() {
+ let original = StopTrayIcon::from_rgba(1, 1, &[10, 20, 30, 40]).unwrap();
+ assert_eq!(
+ original.clone().with_visible_template_color().argb,
+ original.argb
+ );
+ }
+
#[test]
fn stop_activation_is_bound_to_its_generation_and_first_host() {
let (item, receiver) = item();