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