Skip to content

Lightweight native Discord client for Windows, Linux and macOS, written in Rust. No Electron, no browser engine.

11.7 KB
Raw Blame
//! Your camera: turning it on in a call (its picture on your own tile), the
//! settings' camera list and test, and the preview asked for before turning
//! it on ("Always preview video"). Capture, encoding and sending are the voice
//! crate's (`voice::Camera`, `VoiceHandle::set_camera`).

use crate::app::RustCord;
use crate::backend::Command;
use eframe::egui::{self, vec2, Align2, Button, Color32, Frame, Order, RichText, Sense};
use std::sync::mpsc::Receiver;
use std::sync::Arc;

/// The camera glyph (Segoe icons' "Video").
pub const CAMERA: &str = "\u{E714}";

#[derive(Default)]
pub struct CameraState {
    /// The camera being sent to the call.
    pub on: Option<Arc<voice::Camera>>,
    /// Asked to turn on; the backend is opening it.
    pub pending: bool,
    texture: Option<egui::TextureHandle>,
    seq: u64,
    /// Connected cameras, listed (on a thread) the first time something asks.
    devices: Option<Vec<voice::CameraDevice>>,
    devices_rx: Option<Receiver<Vec<voice::CameraDevice>>>,
    /// A camera open only to look at (the settings' test, the preview dialog).
    test: Option<voice::Camera>,
    test_rx: Option<Receiver<Result<voice::Camera, String>>>,
    test_texture: Option<egui::TextureHandle>,
    test_seq: u64,
    pub test_error: Option<String>,
    /// The "turn on your camera?" preview dialog is open.
    pub confirm: bool,
    /// Other people's cameras in the running call, and their pictures as textures
    /// (with the number of the frame each one shows).
    feeds: Option<Arc<voice::CameraFeeds>>,
    remote: std::collections::HashMap<u64, (Option<egui::TextureHandle>, u64)>,
}

impl CameraState {
    pub fn testing(&self) -> bool {
        self.test.is_some() || self.test_rx.is_some()
    }

    /// A new call: its cameras replace the last call's.
    pub fn set_feeds(&mut self, feeds: Arc<voice::CameraFeeds>) {
        self.feeds = Some(feeds);
        self.remote.clear();
    }

    /// `user`'s camera picture, while their camera is on and a picture has arrived.
    pub fn remote_texture(&mut self, ctx: &egui::Context, user: u64) -> Option<egui::TextureHandle> {
        let Some(frame) = self.feeds.as_ref().and_then(|f| f.latest(user)) else {
            self.remote.remove(&user);
            return None;
        };
        let slot = self.remote.entry(user).or_insert((None, u64::MAX));
        if slot.1 != frame.seq {
            slot.1 = frame.seq;
            crate::golive::upload(ctx, &mut slot.0, &format!("camera-{user}"), &frame);
        }
        slot.0.clone()
    }
}

impl RustCord {
    /// The camera button: on ↔ off (through the preview dialog when
    /// "Always preview video" is on).
    pub fn toggle_camera(&mut self) {
        if self.camera.on.is_some() || self.camera.pending {
            self.stop_camera();
        } else if self.voice_ui.prefs.always_preview_video {
            self.camera.confirm = true;
            self.start_camera_test();
        } else {
            self.start_camera();
        }
    }

    pub fn start_camera(&mut self) {
        if !self.voice.as_ref().is_some_and(|v| v.connected) {
            return;
        }
        // One program reads a camera at a time: the test lets go first.
        self.stop_camera_test();
        self.camera.pending = true;
        self.backend.send(Command::Camera(Some(self.voice_ui.prefs.camera_device.clone().unwrap_or_default())));
    }

    pub fn stop_camera(&mut self) {
        self.camera.on = None;
        self.camera.pending = false;
        self.camera.texture = None;
        self.backend.send(Command::Camera(None));
    }

    /// The backend's answer: the camera is on (its handle), off, or failed.
    pub fn on_camera(&mut self, result: Result<Option<Arc<voice::Camera>>, String>) {
        let wanted = std::mem::take(&mut self.camera.pending);
        match result {
            Ok(Some(camera)) if wanted => {
                log::info!("camera: on");
                self.camera.on = Some(camera);
                self.camera.seq = 0;
            }
            // Turned off again while it was opening.
            Ok(Some(_)) => self.backend.send(Command::Camera(None)),
            Ok(None) => {
                if self.camera.on.take().is_some() {
                    log::info!("camera: off");
                }
                self.camera.texture = None;
            }
            Err(e) => {
                log::warn!("camera: {e}");
                self.camera.on = None;
                self.camera.texture = None;
                self.toast(format!("Couldn't turn on your camera: {e}"), true);
            }
        }
    }

    /// Your camera's picture while it's on (for your tile in the call).
    pub fn camera_texture(&mut self, ctx: &egui::Context) -> Option<egui::TextureHandle> {
        let camera = self.camera.on.as_ref()?;
        if let Some(f) = camera.preview().filter(|f| f.seq != self.camera.seq) {
            self.camera.seq = f.seq;
            crate::golive::upload(ctx, &mut self.camera.texture, "camera-self", &f);
        }
        self.camera.texture.clone()
    }

    /// Connected cameras (empty until the first listing arrives).
    pub fn camera_devices(&mut self, ctx: &egui::Context) -> Vec<voice::CameraDevice> {
        if let Some(list) = self.camera.devices_rx.as_ref().and_then(|rx| rx.try_recv().ok()) {
            self.camera.devices = Some(list);
            self.camera.devices_rx = None;
        }
        if self.camera.devices.is_none() && self.camera.devices_rx.is_none() {
            self.refresh_camera_devices(ctx);
        }
        self.camera.devices.clone().unwrap_or_default()
    }

    pub fn refresh_camera_devices(&mut self, ctx: &egui::Context) {
        let (tx, rx) = std::sync::mpsc::channel();
        let ctx = ctx.clone();
        std::thread::spawn(move || {
            let _ = tx.send(voice::cameras());
            ctx.request_repaint();
        });
        self.camera.devices_rx = Some(rx);
    }

    pub fn camera_listing(&self) -> bool {
        self.camera.devices.is_none()
    }

    /// Open the chosen camera just to look at it.
    pub fn start_camera_test(&mut self) {
        if self.camera.testing() || self.camera.on.is_some() {
            return;
        }
        self.camera.test_error = None;
        let device = self.voice_ui.prefs.camera_device.clone();
        let (tx, rx) = std::sync::mpsc::channel();
        let ctx = self.ctx.clone();
        std::thread::spawn(move || {
            let wake = ctx.clone();
            let opened = device
                .or_else(|| voice::cameras().into_iter().next().map(|c| c.id))
                .ok_or_else(|| "No camera is connected".to_string())
                .and_then(|id| voice::Camera::open(&id, move || wake.request_repaint()));
            let _ = tx.send(opened);
            ctx.request_repaint();
        });
        self.camera.test_rx = Some(rx);
    }

    pub fn stop_camera_test(&mut self) {
        self.camera.test = None;
        self.camera.test_rx = None;
        self.camera.test_texture = None;
        self.camera.test_seq = 0;
    }

    /// The test camera's picture (None while it opens or when it isn't running).
    pub fn camera_test_texture(&mut self, ctx: &egui::Context) -> Option<egui::TextureHandle> {
        if let Some(result) = self.camera.test_rx.as_ref().and_then(|rx| rx.try_recv().ok()) {
            self.camera.test_rx = None;
            match result {
                Ok(camera) => self.camera.test = Some(camera),
                Err(e) => self.camera.test_error = Some(e),
            }
        }
        let camera = self.camera.test.as_ref()?;
        if let Some(f) = camera.preview().filter(|f| f.seq != self.camera.test_seq) {
            self.camera.test_seq = f.seq;
            crate::golive::upload(ctx, &mut self.camera.test_texture, "camera-test", &f);
        }
        self.camera.test_texture.clone()
    }

    /// Each frame: a test nobody is looking at lets go of the camera.
    pub fn camera_tick(&mut self) {
        let looking = self.camera.confirm || (self.settings_open && self.settings_tab == crate::app::SettingsTab::VoiceVideo);
        if self.camera.testing() && !looking {
            self.stop_camera_test();
        }
        if self.camera.confirm && !self.voice.as_ref().is_some_and(|v| v.connected) {
            self.camera.confirm = false;
        }
    }

    /// "Always preview video": your picture, and Turn On Camera / Cancel.
    pub fn camera_confirm_ui(&mut self, ctx: &egui::Context) {
        if !self.camera.confirm {
            return;
        }
        let t = self.theme.clone();
        let screen = ctx.screen_rect();
        let mut close = ctx.input(|i| i.key_pressed(egui::Key::Escape));
        let mut turn_on = false;
        egui::Area::new(egui::Id::new("camera_confirm_bg")).order(Order::Foreground).fixed_pos(screen.min).show(ctx, |ui| {
            let (r, resp) = ui.allocate_exact_size(screen.size(), Sense::click());
            ui.painter().rect_filled(r, 0.0, Color32::from_black_alpha(170));
            close |= resp.clicked();
        });
        let picture = self.camera_test_texture(ctx);
        let error = self.camera.test_error.clone();
        egui::Area::new(egui::Id::new("camera_confirm")).order(Order::Foreground).anchor(Align2::CENTER_CENTER, vec2(0.0, 0.0)).show(ctx, |ui| {
            ui.ctx().move_to_top(ui.layer_id());
            Frame::none().fill(t.bg_primary).rounding(12.0).stroke(egui::Stroke::new(1.0_f32, t.border_subtle)).inner_margin(24.0).show(ui, |ui| {
                ui.set_width(440.0);
                ui.label(RichText::new("Camera Preview").font(crate::style::medium(20.0)).color(t.header_primary));
                ui.add_space(4.0);
                ui.label(RichText::new("This is what others in the call will see.").size(14.0).color(t.text_muted));
                ui.add_space(16.0);
                let (rect, _) = ui.allocate_exact_size(vec2(440.0, 247.5), Sense::hover());
                ui.painter().rect_filled(rect, 8.0, Color32::BLACK);
                match (&picture, &error) {
                    (Some(tex), _) => {
                        let size = tex.size_vec2();
                        let fit = (rect.width() / size.x).min(rect.height() / size.y);
                        egui::Image::new((tex.id(), size * fit)).rounding(8.0).paint_at(ui, egui::Rect::from_center_size(rect.center(), size * fit));
                    }
                    (None, Some(e)) => {
                        ui.painter().text(rect.center(), Align2::CENTER_CENTER, e, egui::FontId::proportional(14.0), t.text_muted);
                    }
                    (None, None) => {
                        ui.painter().text(rect.center(), Align2::CENTER_CENTER, "Starting your camera…", egui::FontId::proportional(14.0), t.text_muted);
                        ui.ctx().request_repaint_after(std::time::Duration::from_millis(100));
                    }
                }
                ui.add_space(20.0);
                ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
                    let go = ui.add_enabled(error.is_none(), Button::new(RichText::new("Turn On Camera").font(crate::style::medium(14.0)).color(Color32::WHITE)).fill(Color32::from_rgb(88, 101, 242)).rounding(8.0).min_size(vec2(0.0, 38.0)));
                    turn_on = go.clicked();
                    ui.add_space(8.0);
                    if ui.add(Button::new(RichText::new("Cancel").font(crate::style::medium(14.0)).color(t.header_primary)).frame(false).min_size(vec2(70.0, 38.0))).on_hover_cursor(egui::CursorIcon::PointingHand).clicked() {
                        close = true;
                    }
                });
            });
        });
        if turn_on {
            self.camera.confirm = false;
            self.start_camera();
        } else if close {
            self.camera.confirm = false;
            self.stop_camera_test();
        }
    }
}