Lightweight native Discord client for Windows, Linux and macOS, written in Rust. No Electron, no browser engine.
Rust desktop-appdiscorddiscord-clienteguielectron-alternativelightweightlinuxmacosnative-apprustwindows
//! Discord's inline video player, natively: video attachments and embeds that
//! carry a real video file (`embed.video.proxy_url`). Windows' Media
//! Foundation reads the video straight from its address (streaming it, with
//! range requests for seeking), so playback starts without waiting for a
//! download and the file is never held in RustCord's memory. The picture is
//! decoded at real speed on one thread, the sound on another as the audio
//! output asks for it; play / pause, seeking, mute and a window-filling
//! mode are driven from the chat.
//!
//! One video plays at a time, like Discord.
use crate::audio::AudioPlayer;
use eframe::egui::{self, ColorImage};
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::mpsc::{sync_channel, Receiver, SyncSender, TryRecvError};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
/// Largest frame kept (bigger videos are scaled down while decoding).
const MAX_W: usize = 1280;
const MAX_H: usize = 720;
/// Decoded sound waiting to be played: this many blocks at most (~0.5 s).
const AUDIO_QUEUE: usize = 24;
#[derive(Default)]
struct Shared {
/// Newest frame not yet shown.
frame: Option<ColorImage>,
position: f64,
duration: Option<f64>,
loading: bool,
finished: bool,
/// A first frame has been shown (the sound may start).
started: bool,
error: Option<String>,
/// The sound, once its format is known: (channels, rate, blocks).
audio: Option<(u16, u32, Receiver<(u64, Vec<f32>)>)>,
}
#[derive(Default)]
struct Ctl {
stop: AtomicBool,
paused: AtomicBool,
/// Position (seconds) the picture should jump to.
seek: Mutex<Option<f64>>,
/// Bumped on every seek: sound decoded for an older position is dropped.
audio_gen: AtomicU64,
/// Where the sound should resume: (seconds, generation). Set when the
/// picture has caught up with a seek, so the two restart together.
audio_seek: Mutex<Option<(f64, u64)>>,
}
pub struct VideoState {
pub playing: bool,
pub loading: bool,
pub position: f64,
pub duration: Option<f64>,
pub error: Option<String>,
}
pub struct VideoPlayer {
pub url: String,
shared: Arc<Mutex<Shared>>,
ctl: Arc<Ctl>,
pub texture: Option<egui::TextureHandle>,
sink: Option<rodio::Player>,
audio_started: bool,
pub muted: bool,
/// Fill the window (Discord's full-screen button).
pub fullscreen: bool,
}
impl Drop for VideoPlayer {
fn drop(&mut self) {
self.ctl.stop.store(true, Ordering::Relaxed);
if let Some(s) = self.sink.take() {
s.stop();
}
}
}
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),
}
}
/// The video's sound as an audio source: blocks arrive from the decoding
/// thread; silence while none is ready (never blocking the audio output),
/// and blocks decoded before the latest seek are skipped.
struct StreamSource {
rx: Receiver<(u64, Vec<f32>)>,
ctl: Arc<Ctl>,
current: std::vec::IntoIter<f32>,
channels: rodio::ChannelCount,
rate: rodio::SampleRate,
}
impl Iterator for StreamSource {
type Item = f32;
fn next(&mut self) -> Option<f32> {
loop {
if let Some(s) = self.current.next() {
return Some(s);
}
match self.rx.try_recv() {
Ok((gen, block)) => {
if gen == self.ctl.audio_gen.load(Ordering::Relaxed) {
self.current = block.into_iter();
}
}
// Nothing decoded yet: a moment of silence, in whole frames
// so the channels stay in step.
Err(TryRecvError::Empty) => self.current = vec![0.0; self.channels.get() as usize * 256].into_iter(),
Err(TryRecvError::Disconnected) => return None,
}
}
}
}
impl rodio::Source for StreamSource {
fn current_span_len(&self) -> Option<usize> {
None
}
fn channels(&self) -> rodio::ChannelCount {
self.channels
}
fn sample_rate(&self) -> rodio::SampleRate {
self.rate
}
fn total_duration(&self) -> Option<Duration> {
None
}
}
impl VideoPlayer {
/// Start playing `url`.
pub fn start(ctx: &egui::Context, url: String, muted: bool) -> Self {
let shared = Arc::new(Mutex::new(Shared { loading: true, ..Default::default() }));
let ctl = Arc::new(Ctl::default());
let (sh, c, ctx2, u) = (shared.clone(), ctl.clone(), ctx.clone(), url.clone());
let _ = std::thread::Builder::new().name("rustcord-video".into()).spawn(move || {
if let Err(e) = run(&u, &sh, &c, &ctx2) {
if let Ok(mut s) = sh.lock() {
s.error = Some(e);
s.loading = false;
}
ctx2.request_repaint();
}
});
Self { url, shared, ctl, texture: None, sink: None, audio_started: false, muted, fullscreen: false }
}
pub fn state(&self) -> VideoState {
let s = self.shared.lock().unwrap_or_else(|e| e.into_inner());
VideoState {
playing: !self.ctl.paused.load(Ordering::Relaxed) && !s.finished && s.error.is_none(),
loading: s.loading,
position: s.position,
duration: s.duration,
error: s.error.clone(),
}
}
/// Once a frame: show the newest picture and keep the sound in step.
pub fn pump(&mut self, ctx: &egui::Context, audio: &mut AudioPlayer) {
let (frame, sound, started, finished) = {
let mut s = self.shared.lock().unwrap_or_else(|e| e.into_inner());
(s.frame.take(), s.audio.take(), s.started, s.finished)
};
if let Some(img) = frame {
match &mut self.texture {
Some(t) => t.set(img, egui::TextureOptions::LINEAR),
None => self.texture = Some(ctx.load_texture("rustcord-video", img, egui::TextureOptions::LINEAR)),
}
}
if let Some((channels, rate, rx)) = sound {
if let (Some(channels), Some(rate)) = (std::num::NonZero::new(channels), std::num::NonZero::new(rate)) {
let source = StreamSource { rx, ctl: self.ctl.clone(), current: Vec::new().into_iter(), channels, rate };
match audio.open_source_sink(source) {
Ok(sink) => {
sink.set_volume(if self.muted { 0.0 } else { 1.0 });
self.sink = Some(sink);
self.audio_started = false;
}
// No output device: picture only.
Err(e) => log::debug!("video: no audio for {}: {e}", crate::net_images::log_url(&self.url)),
}
}
}
if let Some(sink) = &self.sink {
let paused = self.ctl.paused.load(Ordering::Relaxed);
if started && !self.audio_started && !paused {
self.audio_started = true;
sink.play();
}
if finished && !sink.is_paused() {
sink.pause();
}
}
}
/// Play / pause (a finished video starts over).
pub fn toggle(&mut self) {
let finished = self.shared.lock().map(|s| s.finished).unwrap_or(false);
if finished {
self.seek_to(0.0);
self.ctl.paused.store(false, Ordering::Relaxed);
if let Some(s) = &self.sink {
s.play();
}
return;
}
let paused = !self.ctl.paused.load(Ordering::Relaxed);
self.ctl.paused.store(paused, Ordering::Relaxed);
if let Some(s) = self.sink.as_ref().filter(|_| self.audio_started) {
if paused {
s.pause();
} else {
s.play();
}
}
}
/// Jump to `fraction` (0–1) of the video.
pub fn seek(&mut self, fraction: f32) {
let Some(d) = self.shared.lock().ok().and_then(|s| s.duration) else { return };
self.seek_to(d * fraction.clamp(0.0, 1.0) as f64);
}
fn seek_to(&mut self, secs: f64) {
// The sound falls silent now and resumes when the picture gets there.
self.ctl.audio_gen.fetch_add(1, Ordering::Relaxed);
if let Ok(mut s) = self.ctl.seek.lock() {
*s = Some(secs);
}
if let Ok(mut s) = self.shared.lock() {
s.position = secs;
}
}
pub fn toggle_mute(&mut self) {
self.muted = !self.muted;
if let Some(s) = &self.sink {
s.set_volume(if self.muted { 0.0 } else { 1.0 });
}
}
}
/// Where downloaded copies go when a video can't be streamed.
fn temp_dir() -> Option<std::path::PathBuf> {
Some(directories::ProjectDirs::from("dev", "RustCord", "RustCord")?.cache_dir().join("video-tmp"))
}
/// Remove leftover downloaded copies (at start, and before a new one).
pub fn clear_temp() {
if let Some(dir) = temp_dir() {
crate::cache::remove_tree(&dir);
}
}
/// A downloaded copy stops here (Discord's biggest uploads are 500 MB).
const MAX_VIDEO_DOWNLOAD: u64 = 1024 * 1024 * 1024;
/// The temporary copy's extension: the link's, when it is a video format
/// Windows plays (it picks the reader by it), else mp4. Never anything else.
fn video_extension(url: &str) -> &'static str {
let ext = url.split(['?', '#']).next().and_then(|p| p.rsplit('.').next()).unwrap_or_default().to_ascii_lowercase();
["mp4", "m4v", "mov", "webm", "mkv", "avi"].into_iter().find(|e| *e == ext).unwrap_or("mp4")
}
/// Download `url` to a temporary file, in pieces (never whole in memory).
fn download_to_file(url: &str, stop: &AtomicBool) -> Result<String, String> {
use std::io::Write;
let dir = temp_dir().ok_or("no cache folder")?;
std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?;
let path = dir.join(format!("{:016x}.{}", rand::random::<u64>(), video_extension(url)));
let rt = tokio::runtime::Builder::new_current_thread().enable_all().build().map_err(|e| e.to_string())?;
// (Errors without the address: attachment links are signed.)
rt.block_on(async {
let mut r = reqwest::get(url).await.and_then(|r| r.error_for_status()).map_err(|e| e.without_url().to_string())?;
let mut file = std::fs::File::create(&path).map_err(|e| e.to_string())?;
let mut written = 0u64;
while let Some(piece) = r.chunk().await.map_err(|e| e.without_url().to_string())? {
if stop.load(Ordering::Relaxed) {
return Err("stopped".to_string());
}
written += piece.len() as u64;
if written > MAX_VIDEO_DOWNLOAD {
return Err("the video is too big to download".to_string());
}
file.write_all(&piece).map_err(|e| e.to_string())?;
}
Ok(())
})?;
Ok(path.to_string_lossy().into_owned())
}
fn run(url: &str, shared: &Arc<Mutex<Shared>>, ctl: &Arc<Ctl>, ctx: &egui::Context) -> Result<(), String> {
// Stream it; if Windows can't open the address itself, fall back to a
// downloaded copy on disk.
let mut source = url.to_string();
let mut audio_running = false;
loop {
if !audio_running {
audio_running = true;
spawn_audio(source.clone(), shared.clone(), ctl.clone());
}
match play_once(&source, shared, ctl, ctx) {
Ok(()) => {}
Err(e) => {
let never_started = shared.lock().map(|s| !s.started).unwrap_or(false);
if never_started && source == url && !ctl.stop.load(Ordering::Relaxed) {
log::info!("video: couldn't stream ({e}); downloading it instead");
clear_temp();
source = download_to_file(url, &ctl.stop).map_err(|e| format!("Couldn't load the video: {e}"))?;
audio_running = false;
continue;
}
return Err(format!("Couldn't play the video: {e}"));
}
}
if ctl.stop.load(Ordering::Relaxed) {
return Ok(());
}
// The end: wait for a replay (a seek).
if let Ok(mut s) = shared.lock() {
s.finished = true;
s.loading = false;
}
ctx.request_repaint();
loop {
if ctl.stop.load(Ordering::Relaxed) {
return Ok(());
}
if ctl.seek.lock().map(|s| s.is_some()).unwrap_or(false) {
break;
}
std::thread::sleep(Duration::from_millis(30));
}
if let Ok(mut s) = shared.lock() {
s.finished = false;
}
}
}
/// The sound thread: decodes blocks into a small queue the audio output
/// drains; a full queue (paused, or simply ahead) makes it wait.
#[cfg(windows)]
fn spawn_audio(source: String, shared: Arc<Mutex<Shared>>, ctl: Arc<Ctl>) {
let _ = std::thread::Builder::new().name("rustcord-video-audio".into()).spawn(move || {
let (tx, rx) = sync_channel::<(u64, Vec<f32>)>(AUDIO_QUEUE);
let mut rx = Some(rx);
let gen = std::cell::Cell::new(ctl.audio_gen.load(Ordering::Relaxed));
let stopped = || ctl.stop.load(Ordering::Relaxed);
let mut seek = || {
let (secs, g) = ctl.audio_seek.lock().ok()?.take()?;
gen.set(g);
Some((secs * 10_000_000.0) as i64)
};
let mut on_format = |channels: u16, rate: u32| {
if let (Some(rx), Ok(mut s)) = (rx.take(), shared.lock()) {
s.audio = Some((channels, rate, rx));
}
};
let send = |tx: &SyncSender<(u64, Vec<f32>)>, mut block: (u64, Vec<f32>)| -> bool {
// Wait for room without blocking for good (stop / seek stay prompt).
loop {
if stopped() {
return false;
}
match tx.try_send(block) {
Ok(()) => return true,
Err(std::sync::mpsc::TrySendError::Full(b)) => {
// A seek is waiting: this block is stale anyway.
if ctl.audio_seek.lock().map(|s| s.is_some()).unwrap_or(false) {
return true;
}
block = b;
std::thread::sleep(Duration::from_millis(10));
}
Err(std::sync::mpsc::TrySendError::Disconnected(_)) => return false,
}
}
};
let mut on_chunk = |pcm: Vec<f32>| {
if stopped() {
return false;
}
if pcm.is_empty() {
return true;
}
send(&tx, (gen.get(), pcm))
};
if let Err(e) = crate::video::mp4_audio_stream(crate::video::MediaSrc::Url(&source), &mut seek, &mut on_format, &mut on_chunk) {
log::debug!("video: no sound ({e})");
}
});
}
#[cfg(not(windows))]
fn spawn_audio(_: String, _: Arc<Mutex<Shared>>, _: Arc<Ctl>) {}
/// Decode from the start (or the pending seek) to the end, at real speed.
#[cfg(windows)]
fn play_once(source: &str, shared: &Arc<Mutex<Shared>>, ctl: &Arc<Ctl>, ctx: &egui::Context) -> Result<(), String> {
use std::cell::Cell;
// (wall clock, video time) that frames are paced against.
let clock: Cell<Option<(Instant, f64)>> = Cell::new(None);
// After a seek: frames before this are decoded but not shown, and the
// sound restarts at the first one that is.
let skip_until = Cell::new(0.0f64);
let sync_audio = Cell::new(false);
let stopped = || ctl.stop.load(Ordering::Relaxed);
let seek_pending = || ctl.seek.lock().map(|s| s.is_some()).unwrap_or(false);
let mut seek = || {
let s = ctl.seek.lock().ok()?.take()?;
clock.set(None);
skip_until.set(s);
sync_audio.set(true);
Some((s * 10_000_000.0) as i64)
};
let mut on_duration = |d: i64| {
if let Ok(mut s) = shared.lock() {
s.duration = Some(d as f64 / 10_000_000.0);
}
};
let mut on_frame = |ts: i64, img: ColorImage| {
if stopped() {
return false;
}
let secs = ts as f64 / 10_000_000.0;
if secs + 0.02 < skip_until.get() {
return true;
}
if sync_audio.replace(false) {
if let Ok(mut a) = ctl.audio_seek.lock() {
*a = Some((secs, ctl.audio_gen.load(Ordering::Relaxed)));
}
}
let (t0, s0) = match clock.get() {
Some(c) => c,
None => {
let c = (Instant::now(), secs);
clock.set(Some(c));
c
}
};
// Wait for this frame's time (in short naps, so stop / seek are prompt).
let due = Duration::from_secs_f64((secs - s0).max(0.0));
while t0.elapsed() < due {
if stopped() {
return false;
}
if seek_pending() {
return true;
}
std::thread::sleep((due - t0.elapsed().min(due)).min(Duration::from_millis(15)));
}
if let Ok(mut s) = shared.lock() {
s.loading = false;
s.started = true;
s.frame = Some(img);
s.position = secs;
}
ctx.request_repaint();
// Paused: hold this frame.
if ctl.paused.load(Ordering::Relaxed) {
while ctl.paused.load(Ordering::Relaxed) && !stopped() && !seek_pending() {
std::thread::sleep(Duration::from_millis(20));
}
clock.set(None);
}
!stopped()
};
crate::video::mp4_frames_ctl(crate::video::MediaSrc::Url(source), &fit, &mut seek, &mut on_duration, &mut on_frame)
}
#[cfg(not(windows))]
fn play_once(_: &str, _: &Arc<Mutex<Shared>>, _: &Arc<Ctl>, _: &egui::Context) -> Result<(), String> {
Err("Videos play on Windows only for now.".into())
}
/// Is this attachment a video Discord would play inline?
pub fn is_video(filename: &str, content_type: Option<&str>) -> bool {
if content_type.is_some_and(|c| c.starts_with("video/")) {
return true;
}
let f = filename.to_ascii_lowercase();
[".mp4", ".mov", ".webm", ".m4v"].iter().any(|e| f.ends_with(e))
}
/// "1:05" / "1:02:03".
pub fn fmt_time(secs: f64) -> String {
let s = secs.max(0.0) as u64;
if s >= 3600 {
format!("{}:{:02}:{:02}", s / 3600, s / 60 % 60, s % 60)
} else {
format!("{}:{:02}", s / 60, s % 60)
}
}