Skip to content

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

5.5 KB
Raw Blame
//! Watching a video quest inside RustCord. The quest's MP4 is downloaded,
//! decoded frame by frame with Windows' Media Foundation at real speed and
//! shown in a player window. While it plays, the watched time is reported to
//! Discord the way its own client does (`POST /quests/{id}/video-progress`
//! with `{"timestamp": seconds}`), so the quest completes when you've watched
//! enough. (No sound yet: RustCord's player is picture-only.)

use discord::model::Id;
use eframe::egui::{self, ColorImage};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};

/// What the decode thread shares with the UI.
#[derive(Default)]
pub struct Shared {
    /// Newest frame not yet shown.
    pub frame: Option<ColorImage>,
    /// Playback position in seconds (where the video is).
    pub position: f64,
    pub loading: bool,
    pub finished: bool,
    pub error: Option<String>,
}

pub struct QuestVideo {
    pub quest: Id,
    pub title: String,
    /// Seconds Discord wants watched.
    pub target: f64,
    pub shared: Arc<Mutex<Shared>>,
    pub stop: Arc<AtomicBool>,
    pub texture: Option<egui::TextureHandle>,
    /// Last position sent to Discord.
    pub reported: f64,
    pub completed: bool,
    pub size: (u32, u32),
    /// Send watch time to Discord (off only for RustCord's own testing).
    pub report: bool,
    /// Not a quest: any clip shown in this pop-up (Discord's "How Boosting
    /// Works" on the Server Boosts page). No quest wording, nothing reported.
    pub plain: bool,
}

impl Drop for QuestVideo {
    fn drop(&mut self) {
        self.stop.store(true, Ordering::Relaxed);
    }
}

/// Largest frame kept (the window is at most this big).
const MAX_W: usize = 960;
const MAX_H: usize = 540;

fn fit(w: usize, h: usize, rgba: Vec<u8>) -> ColorImage {
    let scale = (MAX_W as f32 / w as f32).min(MAX_H as f32 / h as f32);
    if scale >= 1.0 {
        return ColorImage::from_rgba_unmultiplied([w, h], &rgba);
    }
    let (nw, nh) = (((w as f32 * scale) as u32).max(1), ((h as f32 * scale) as u32).max(1));
    match image::RgbaImage::from_raw(w as u32, h as u32, rgba) {
        Some(img) => {
            let small = image::imageops::resize(&img, nw, nh, image::imageops::FilterType::Triangle);
            ColorImage::from_rgba_unmultiplied([nw as usize, nh as usize], small.as_raw())
        }
        None => ColorImage::new([1, 1], egui::Color32::BLACK),
    }
}

impl QuestVideo {
    /// Start downloading and playing `url` (from `start_at` seconds).
    pub fn start(ctx: &egui::Context, quest: Id, title: String, url: String, target: f64, start_at: f64, size: (u32, u32)) -> Self {
        let shared = Arc::new(Mutex::new(Shared { loading: true, position: start_at, ..Default::default() }));
        let stop = Arc::new(AtomicBool::new(false));
        let (sh, st, ctx2) = (shared.clone(), stop.clone(), ctx.clone());
        let _ = std::thread::Builder::new().name("rustcord-quest-video".into()).spawn(move || {
            let fail = |e: String| {
                if let Ok(mut s) = sh.lock() {
                    s.error = Some(e);
                    s.loading = false;
                }
                ctx2.request_repaint();
            };
            // Download (the clips are a few tens of MB).
            let bytes = match tokio::runtime::Builder::new_current_thread().enable_all().build() {
                Ok(rt) => rt.block_on(async {
                    let r = reqwest::get(&url).await.and_then(|r| r.error_for_status());
                    match r {
                        Ok(r) => r.bytes().await.map_err(|e| e.to_string()),
                        Err(e) => Err(e.to_string()),
                    }
                }),
                Err(e) => Err(e.to_string()),
            };
            let bytes = match bytes {
                Ok(b) => b,
                Err(e) => return fail(format!("Couldn't download the video: {e}")),
            };
            if st.load(Ordering::Relaxed) {
                return;
            }
            play(&bytes, start_at, &sh, &st, &ctx2).unwrap_or_else(fail);
        });
        Self { quest, title, target, shared, stop, texture: None, reported: start_at, completed: false, size, report: true, plain: false }
    }
}

/// Decode at real speed, skipping what was already watched.
#[cfg(windows)]
fn play(bytes: &[u8], start_at: f64, shared: &Arc<Mutex<Shared>>, stop: &Arc<AtomicBool>, ctx: &egui::Context) -> Result<(), String> {
    let mut clock: Option<(std::time::Instant, f64)> = None;
    crate::video::mp4_frames(bytes, &fit, &mut |ts, img| {
        if stop.load(Ordering::Relaxed) {
            return false;
        }
        let secs = ts as f64 / 10_000_000.0;
        if secs + 0.05 < start_at {
            return true;
        }
        // Pace to the frame's timestamp.
        let (t0, s0) = *clock.get_or_insert((std::time::Instant::now(), secs));
        let due = std::time::Duration::from_secs_f64((secs - s0).max(0.0));
        let elapsed = t0.elapsed();
        if due > elapsed {
            std::thread::sleep(due - elapsed);
        }
        if let Ok(mut s) = shared.lock() {
            s.loading = false;
            s.frame = Some(img);
            s.position = secs;
        }
        ctx.request_repaint();
        true
    })?;
    if let Ok(mut s) = shared.lock() {
        s.finished = true;
        s.loading = false;
    }
    ctx.request_repaint();
    Ok(())
}

#[cfg(not(windows))]
fn play(_: &[u8], _: f64, _: &Arc<Mutex<Shared>>, _: &Arc<AtomicBool>, _: &egui::Context) -> Result<(), String> {
    Err("Video quests play on Windows only for now.".into())
}