BlueGit

ict rusty-teams

Files

rusty-teams / crates / app / src / call / preview.rs

preview.rs

preview.rs 6.6 KiB Download Raw
1use std::sync::atomic::{AtomicU64, Ordering};
2use std::sync::{Arc, Mutex};
3use std::time::{Duration, Instant};
4
5use calling::background::BackgroundPicture;
6use calling::blur::BlurSettings;
7use calling::camera::start_camera;
8use calling::capture::Capture;
9use calling::video_frame::picture_from_i420;
10use calling::{BackgroundChoice, CallUpdate, DeviceChoice, VideoHub, VideoKey};
11use gpui_kit::*;
12use tokio::sync::mpsc::{UnboundedReceiver, unbounded_channel};
13
14use super::background::{BackgroundLibrary, BackgroundPick};
15use super::pictures::CallPictures;
16
17const PREVIEW_MAX_WIDTH: u32 = 640;
18const FPS_WINDOW: Duration = Duration::from_millis(900);
19
20pub struct CameraPreview {
21 hub: Arc<VideoHub>,
22 pictures: CallPictures,
23 blur: Arc<BlurSettings>,
24 background_request: Arc<AtomicU64>,
25 capture: Option<Capture>,
26 frames: Arc<AtomicU64>,
27 failure: Arc<Mutex<Option<String>>>,
28 counted: (Instant, u64),
29 fps: Option<f32>,
30}
31
32impl CameraPreview {
33 pub fn new() -> (Self, UnboundedReceiver<CallUpdate>) {
34 let (sender, receiver) = unbounded_channel();
35 let preview = CameraPreview {
36 hub: VideoHub::new(sender),
37 pictures: CallPictures::default(),
38 blur: Arc::new(BlurSettings::default()),
39 background_request: Arc::new(AtomicU64::new(0)),
40 capture: None,
41 frames: Arc::new(AtomicU64::new(0)),
42 failure: Arc::new(Mutex::new(None)),
43 counted: (Instant::now(), 0),
44 fps: None,
45 };
46 (preview, receiver)
47 }
48
49 pub fn start(&mut self, choice: &DeviceChoice) {
50 self.release_capture();
51 *self.failure.lock().expect("preview failure lock") = None;
52 self.frames.store(0, Ordering::Relaxed);
53 self.counted = (Instant::now(), 0);
54 self.fps = None;
55 let hub = self.hub.clone();
56 let frames = self.frames.clone();
57 let failure = self.failure.clone();
58 let started = start_camera(
59 choice,
60 self.blur.clone(),
61 move |buffer| {
62 frames.fetch_add(1, Ordering::Relaxed);
63 if let Some(picture) = picture_from_i420(buffer, PREVIEW_MAX_WIDTH) {
64 hub.publish(VideoKey::LocalCamera, picture);
65 }
66 },
67 move |reason| *failure.lock().expect("preview failure lock") = Some(reason),
68 );
69 match started {
70 Ok(capture) => self.capture = Some(capture),
71 Err(error) => *self.failure.lock().expect("preview failure lock") = Some(error.to_string()),
72 }
73 }
74
75 pub fn set_background(&self, choice: BackgroundChoice) {
76 let request = self.background_request.fetch_add(1, Ordering::SeqCst) + 1;
77 match choice {
78 BackgroundChoice::None => self.apply_background(false, None),
79 BackgroundChoice::Blur => self.apply_background(true, None),
80 BackgroundChoice::Image(path) => {
81 let blur = self.blur.clone();
82 let latest_request = self.background_request.clone();
83 std::thread::spawn(move || {
84 if let Ok(picture) = BackgroundPicture::load(&path)
85 && latest_request.load(Ordering::SeqCst) == request
86 {
87 blur.set_picture(Some(Arc::new(picture)));
88 blur.set_enabled(true);
89 }
90 });
91 }
92 }
93 }
94
95 fn apply_background(&self, enabled: bool, picture: Option<Arc<BackgroundPicture>>) {
96 self.blur.set_picture(picture);
97 self.blur.set_enabled(enabled);
98 }
99
100 pub fn take_frames(&mut self, cx: &mut App) {
101 self.pictures.apply(&self.hub, cx);
102 }
103
104 pub fn image(&self, now: Instant) -> Option<Arc<RenderImage>> {
105 self.pictures.live(&VideoKey::LocalCamera, now)
106 }
107
108 pub fn failure(&self) -> Option<String> {
109 self.failure.lock().expect("preview failure lock").clone()
110 }
111
112 pub fn fps(&self) -> Option<f32> {
113 self.fps
114 }
115
116 pub fn tick(&mut self, now: Instant) {
117 let total = self.frames.load(Ordering::Relaxed);
118 let (since, previous) = self.counted;
119 let elapsed = now.saturating_duration_since(since);
120 if elapsed < FPS_WINDOW {
121 return;
122 }
123 self.fps = self.capture.is_some().then(|| frames_per_second(total.saturating_sub(previous), elapsed));
124 self.counted = (now, total);
125 }
126
127 pub fn stop(&mut self, cx: &mut App) {
128 self.release_capture();
129 self.pictures.clear(cx);
130 self.fps = None;
131 }
132
133 fn release_capture(&mut self) {
134 if let Some(capture) = self.capture.take() {
135 std::thread::spawn(move || drop(capture));
136 }
137 }
138}
139
140pub fn frames_per_second(frames: u64, elapsed: Duration) -> f32 {
141 if elapsed.is_zero() {
142 return 0.;
143 }
144 frames as f32 / elapsed.as_secs_f32()
145}
146
147pub fn preview_backgrounds(library: &BackgroundLibrary) -> Vec<(BackgroundPick, String)> {
148 let defaults = library
149 .shown()
150 .iter()
151 .filter(|image| library.cached_image(&image.id).is_some())
152 .map(|image| (BackgroundPick::Default(image.id.clone()), image.name.clone()));
153 let customs = library.customs.iter().filter(|path| path.exists()).map(|path| {
154 let name = path.file_name().map_or_else(String::new, |name| name.to_string_lossy().into_owned());
155 (BackgroundPick::Custom(path.clone()), name)
156 });
157 [(BackgroundPick::None, "None".to_owned()), (BackgroundPick::Blur, "Blur".to_owned())]
158 .into_iter()
159 .chain(defaults)
160 .chain(customs)
161 .collect()
162}
163
164#[cfg(test)]
165mod tests {
166 use std::time::{Duration, Instant};
167
168 use super::{BackgroundLibrary, BackgroundPick, CameraPreview, frames_per_second, preview_backgrounds};
169
170 #[test]
171 fn frames_per_second_divides_by_elapsed_time() {
172 assert_eq!(frames_per_second(30, Duration::from_secs(1)), 30.);
173 assert_eq!(frames_per_second(15, Duration::from_millis(500)), 30.);
174 assert_eq!(frames_per_second(10, Duration::ZERO), 0.);
175 }
176
177 #[test]
178 fn the_background_choices_start_with_none_and_blur() {
179 let library = BackgroundLibrary::new(std::env::temp_dir().join("teams-preview-test-no-cache"));
180 let picks: Vec<BackgroundPick> = preview_backgrounds(&library).into_iter().map(|(pick, _)| pick).collect();
181 assert_eq!(picks, vec![BackgroundPick::None, BackgroundPick::Blur]);
182 }
183
184 #[test]
185 fn a_preview_without_a_camera_reports_no_frames() {
186 let (preview, _receiver) = CameraPreview::new();
187 assert_eq!(preview.fps(), None);
188 assert!(preview.image(Instant::now()).is_none());
189 }
190}