| 1 | use std::sync::Arc; |
| 2 | use std::sync::atomic::{AtomicBool, Ordering}; |
| 3 | use std::thread::JoinHandle; |
| 4 | use std::time::{Duration, Instant}; |
| 5 | |
| 6 | use tokio::task::JoinHandle as TaskHandle; |
| 7 | |
| 8 | const STOP_WAIT: Duration = Duration::from_secs(2); |
| 9 | const STOP_POLL: Duration = Duration::from_millis(5); |
| 10 | |
| 11 | /// A running frame source; dropping it stops the capture. |
| 12 | pub enum Capture { |
| 13 | Thread { |
| 14 | stop: Arc<AtomicBool>, |
| 15 | thread: Option<JoinHandle<()>>, |
| 16 | }, |
| 17 | Task(TaskHandle<()>), |
| 18 | } |
| 19 | |
| 20 | impl Capture { |
| 21 | pub fn spawn_thread( |
| 22 | name: &str, |
| 23 | body: impl FnOnce(Arc<AtomicBool>) + Send + 'static, |
| 24 | ) -> std::io::Result<Self> { |
| 25 | let stop = Arc::new(AtomicBool::new(false)); |
| 26 | let thread_stop = stop.clone(); |
| 27 | let thread = std::thread::Builder::new() |
| 28 | .name(name.to_owned()) |
| 29 | .spawn(move || body(thread_stop))?; |
| 30 | Ok(Capture::Thread { |
| 31 | stop, |
| 32 | thread: Some(thread), |
| 33 | }) |
| 34 | } |
| 35 | } |
| 36 | |
| 37 | impl Drop for Capture { |
| 38 | fn drop(&mut self) { |
| 39 | match self { |
| 40 | Capture::Thread { stop, thread } => { |
| 41 | stop.store(true, Ordering::SeqCst); |
| 42 | let Some(thread) = thread.take() else { return }; |
| 43 | // Join off the call task so stop_camera / hangup stay responsive. |
| 44 | std::thread::spawn(move || { |
| 45 | let started = Instant::now(); |
| 46 | while !thread.is_finished() && started.elapsed() < STOP_WAIT { |
| 47 | std::thread::sleep(STOP_POLL); |
| 48 | } |
| 49 | if thread.is_finished() { |
| 50 | let _ = thread.join(); |
| 51 | } |
| 52 | }); |
| 53 | } |
| 54 | Capture::Task(task) => task.abort(), |
| 55 | } |
| 56 | } |
| 57 | } |
| 58 | |
| 59 | #[cfg(test)] |
| 60 | mod tests { |
| 61 | use std::time::{Duration, Instant}; |
| 62 | |
| 63 | use super::Capture; |
| 64 | |
| 65 | #[test] |
| 66 | fn a_stuck_capture_thread_does_not_hold_up_the_caller() { |
| 67 | let capture = Capture::spawn_thread("stuck", |_| { |
| 68 | loop { |
| 69 | std::thread::sleep(Duration::from_secs(60)); |
| 70 | } |
| 71 | }) |
| 72 | .unwrap(); |
| 73 | let started = Instant::now(); |
| 74 | drop(capture); |
| 75 | assert!(started.elapsed() < Duration::from_secs(5)); |
| 76 | } |
| 77 | |
| 78 | #[test] |
| 79 | fn a_stopped_capture_thread_is_joined() { |
| 80 | let capture = Capture::spawn_thread("quick", |stop| { |
| 81 | while !stop.load(std::sync::atomic::Ordering::SeqCst) { |
| 82 | std::thread::sleep(Duration::from_millis(5)); |
| 83 | } |
| 84 | }) |
| 85 | .unwrap(); |
| 86 | let started = Instant::now(); |
| 87 | drop(capture); |
| 88 | assert!(started.elapsed() < Duration::from_secs(1)); |
| 89 | } |
| 90 | } |