BlueGit

ict rusty-teams

Files

rusty-teams / crates / calling / src / capture.rs

capture.rs

capture.rs 2.6 KiB Download Raw
1use std::sync::Arc;
2use std::sync::atomic::{AtomicBool, Ordering};
3use std::thread::JoinHandle;
4use std::time::{Duration, Instant};
5
6use tokio::task::JoinHandle as TaskHandle;
7
8const STOP_WAIT: Duration = Duration::from_secs(2);
9const STOP_POLL: Duration = Duration::from_millis(5);
10
11/// A running frame source; dropping it stops the capture.
12pub enum Capture {
13 Thread {
14 stop: Arc<AtomicBool>,
15 thread: Option<JoinHandle<()>>,
16 },
17 Task(TaskHandle<()>),
18}
19
20impl 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
37impl 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)]
60mod 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}