BlueGit

ict rusty-teams

Files

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

preview.rs

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