BlueGit

ict rusty-teams

Files

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

preview.rs

preview.rs 7.1 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<Mutex<u64>>,
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(Mutex::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) => {
72 *self.failure.lock().expect("preview failure lock") = Some(error.to_string())
73 }
74 }
75 }
76
77 pub fn set_background(&self, choice: BackgroundChoice) {
78 let mut latest = self
79 .background_request
80 .lock()
81 .expect("background request lock");
82 *latest += 1;
83 let request = *latest;
84 match choice {
85 BackgroundChoice::None => self.apply_background(false, None),
86 BackgroundChoice::Blur => self.apply_background(true, None),
87 BackgroundChoice::Image(path) => {
88 let blur = self.blur.clone();
89 let latest_request = self.background_request.clone();
90 std::thread::spawn(move || {
91 let Ok(picture) = BackgroundPicture::load(&path) else {
92 return;
93 };
94 let latest = latest_request.lock().expect("background request lock");
95 if *latest == request {
96 blur.set_picture(Some(Arc::new(picture)));
97 blur.set_enabled(true);
98 }
99 });
100 }
101 }
102 }
103
104 fn apply_background(&self, enabled: bool, picture: Option<Arc<BackgroundPicture>>) {
105 self.blur.set_picture(picture);
106 self.blur.set_enabled(enabled);
107 }
108
109 pub fn take_frames(&mut self, cx: &mut App) {
110 self.pictures.apply(&self.hub, cx);
111 }
112
113 pub fn image(&self, now: Instant) -> Option<Arc<RenderImage>> {
114 self.pictures.live(&VideoKey::LocalCamera, now)
115 }
116
117 pub fn failure(&self) -> Option<String> {
118 self.failure.lock().expect("preview failure lock").clone()
119 }
120
121 pub fn fps(&self) -> Option<f32> {
122 self.fps
123 }
124
125 pub fn tick(&mut self, now: Instant) {
126 let total = self.frames.load(Ordering::Relaxed);
127 let (since, previous) = self.counted;
128 let elapsed = now.saturating_duration_since(since);
129 if elapsed < FPS_WINDOW {
130 return;
131 }
132 self.fps = self
133 .capture
134 .is_some()
135 .then(|| frames_per_second(total.saturating_sub(previous), elapsed));
136 self.counted = (now, total);
137 }
138
139 pub fn stop(&mut self, cx: &mut App) {
140 self.release_capture();
141 self.pictures.clear(cx);
142 self.fps = None;
143 }
144
145 fn release_capture(&mut self) {
146 if let Some(capture) = self.capture.take() {
147 std::thread::spawn(move || drop(capture));
148 }
149 }
150}
151
152pub fn frames_per_second(frames: u64, elapsed: Duration) -> f32 {
153 if elapsed.is_zero() {
154 return 0.;
155 }
156 frames as f32 / elapsed.as_secs_f32()
157}
158
159pub fn preview_backgrounds(library: &BackgroundLibrary) -> Vec<(BackgroundPick, String)> {
160 let defaults = library
161 .shown()
162 .iter()
163 .filter(|image| library.cached_image(&image.id).is_some())
164 .map(|image| {
165 (
166 BackgroundPick::Default(image.id.clone()),
167 image.name.clone(),
168 )
169 });
170 let customs = library
171 .customs
172 .iter()
173 .filter(|path| path.exists())
174 .map(|path| {
175 let name = path
176 .file_name()
177 .map_or_else(String::new, |name| name.to_string_lossy().into_owned());
178 (BackgroundPick::Custom(path.clone()), name)
179 });
180 [
181 (BackgroundPick::None, "None".to_owned()),
182 (BackgroundPick::Blur, "Blur".to_owned()),
183 ]
184 .into_iter()
185 .chain(defaults)
186 .chain(customs)
187 .collect()
188}
189
190#[cfg(test)]
191mod tests {
192 use std::time::{Duration, Instant};
193
194 use super::{
195 BackgroundLibrary, BackgroundPick, CameraPreview, frames_per_second, preview_backgrounds,
196 };
197
198 #[test]
199 fn frames_per_second_divides_by_elapsed_time() {
200 assert_eq!(frames_per_second(30, Duration::from_secs(1)), 30.);
201 assert_eq!(frames_per_second(15, Duration::from_millis(500)), 30.);
202 assert_eq!(frames_per_second(10, Duration::ZERO), 0.);
203 }
204
205 #[test]
206 fn the_background_choices_start_with_none_and_blur() {
207 let library =
208 BackgroundLibrary::new(std::env::temp_dir().join("teams-preview-test-no-cache"));
209 let picks: Vec<BackgroundPick> = preview_backgrounds(&library)
210 .into_iter()
211 .map(|(pick, _)| pick)
212 .collect();
213 assert_eq!(picks, vec![BackgroundPick::None, BackgroundPick::Blur]);
214 }
215
216 #[test]
217 fn a_preview_without_a_camera_reports_no_frames() {
218 let (preview, _receiver) = CameraPreview::new();
219 assert_eq!(preview.fps(), None);
220 assert!(preview.image(Instant::now()).is_none());
221 }
222}