| 1 | use std::collections::HashMap; |
| 2 | use std::sync::Arc; |
| 3 | use std::time::{Duration, Instant}; |
| 4 | |
| 5 | use calling::{VideoHub, VideoKey, VideoPicture}; |
| 6 | use gpui_kit::*; |
| 7 | use image::{Frame, RgbaImage}; |
| 8 | |
| 9 | const STALE_AFTER: Duration = Duration::from_millis(2500); |
| 10 | |
| 11 | struct Shown { |
| 12 | image: Arc<RenderImage>, |
| 13 | updated: Instant, |
| 14 | } |
| 15 | |
| 16 | #[derive(Default)] |
| 17 | pub struct CallPictures { |
| 18 | shown: HashMap<VideoKey, Shown>, |
| 19 | } |
| 20 | |
| 21 | pub(crate) fn render_image(picture: VideoPicture) -> Option<Arc<RenderImage>> { |
| 22 | let bytes = RgbaImage::from_raw(picture.width, picture.height, picture.bgra)?; |
| 23 | Some(Arc::new(RenderImage::new(vec![Frame::new(bytes)]))) |
| 24 | } |
| 25 | |
| 26 | impl CallPictures { |
| 27 | pub fn apply(&mut self, hub: &VideoHub, cx: &mut App) { |
| 28 | let now = Instant::now(); |
| 29 | for (key, picture) in hub.drain() { |
| 30 | let picture = Arc::try_unwrap(picture).unwrap_or_else(|shared| (*shared).clone()); |
| 31 | let Some(image) = render_image(picture) else { |
| 32 | continue; |
| 33 | }; |
| 34 | if let Some(previous) = self.shown.insert( |
| 35 | key, |
| 36 | Shown { |
| 37 | image, |
| 38 | updated: now, |
| 39 | }, |
| 40 | ) { |
| 41 | cx.drop_image(previous.image, None); |
| 42 | } |
| 43 | } |
| 44 | } |
| 45 | |
| 46 | pub fn live(&self, key: &VideoKey, now: Instant) -> Option<Arc<RenderImage>> { |
| 47 | self.shown |
| 48 | .get(key) |
| 49 | .filter(|shown| { |
| 50 | *key == VideoKey::Screen |
| 51 | || now.saturating_duration_since(shown.updated) < STALE_AFTER |
| 52 | }) |
| 53 | .map(|shown| shown.image.clone()) |
| 54 | } |
| 55 | |
| 56 | pub fn forget(&mut self, key: &VideoKey, cx: &mut App) { |
| 57 | if let Some(previous) = self.shown.remove(key) { |
| 58 | cx.drop_image(previous.image, None); |
| 59 | } |
| 60 | } |
| 61 | |
| 62 | pub fn clear(&mut self, cx: &mut App) { |
| 63 | for (_, previous) in self.shown.drain() { |
| 64 | cx.drop_image(previous.image, None); |
| 65 | } |
| 66 | } |
| 67 | } |