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