Skip to content

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

16.2 KB
Raw Blame
//! Inline audio attachment player (one track at a time, like Discord), and Discord's own
//! sounds: the call cues (mute, deafen, join, leave…) and the message sound.

use rodio::{Decoder, DeviceSinkBuilder, MixerDeviceSink, Player as Sink, Source};
use std::collections::HashMap;
use std::io::Cursor;
use std::sync::Arc;
use std::time::Duration;

pub fn is_audio(filename: &str, content_type: Option<&str>) -> bool {
    if content_type.is_some_and(|c| c.starts_with("audio/")) {
        return true;
    }
    let f = filename.to_ascii_lowercase();
    [".mp3", ".wav", ".ogg", ".flac", ".m4a", ".aac"].iter().any(|e| f.ends_with(e))
}

/// Decode audio bytes. Symphonia can't always sniff a bare MP3 (no ID3 tag, which
/// is how Discord serves soundboard sounds), so retry with format hints.
fn decode(bytes: Arc<[u8]>) -> Result<Decoder<Cursor<Arc<[u8]>>>, String> {
    let first = match Decoder::new(Cursor::new(bytes.clone())) {
        Ok(d) => return Ok(d),
        Err(e) => e.to_string(),
    };
    let len = bytes.len() as u64;
    for hint in ["mp3", "ogg", "wav", "flac"] {
        if let Ok(d) = Decoder::builder().with_data(Cursor::new(bytes.clone())).with_byte_len(len).with_hint(hint).build() {
            return Ok(d);
        }
    }
    Err(first)
}

pub struct Playing {
    pub url: String,
    sink: Sink,
    pub duration: Option<Duration>,
}

#[derive(Default)]
pub struct AudioPlayer {
    output: Option<MixerDeviceSink>,
    pub current: Option<Playing>,
    /// Downloaded files by URL.
    pub cache: HashMap<String, Arc<[u8]>>,
    /// URL RustCord is downloading in order to play it.
    pub waiting_for: Option<String>,
    pub muted: bool,
    /// Discord's own sounds by their name in Discord's client ("user_join"…),
    /// downloaded from Discord once and kept in the cache folder.
    cue_sounds: HashMap<&'static str, Arc<[u8]>>,
    /// The looping call sound (outgoing "calling" or incoming "ringing").
    ring: Option<(Cue, Sink)>,
}

/// The sounds Discord's client plays, when it plays them. They are Discord's own files,
/// fetched from Discord (`discord.com/assets`) once and cached; they are not part of
/// RustCord, and nothing else stands in for them: until a file has arrived, that cue is
/// silent.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Cue {
    Mute,
    Unmute,
    Deafen,
    Undeafen,
    /// You joined a call (Discord plays the same sound as for someone else joining).
    Join,
    /// You left (or lost) the call: Discord's "disconnect".
    Leave,
    /// Someone else joined the call you're in.
    UserJoin,
    UserLeave,
    /// You were moved to another voice channel.
    UserMoved,
    /// Someone in your call (or you) went live / stopped.
    StreamStarted,
    StreamEnded,
    /// A viewer joined / left the stream you're in.
    StreamUserJoined,
    StreamUserLeft,
    /// Looping: you're calling someone who hasn't answered yet.
    Calling,
    /// Looping: someone is calling you.
    Ringing,
    /// A DM or a mention arrived: Discord's default "message1".
    Message,
}

impl Cue {
    pub const ALL: [Cue; 15] = [
        Cue::Mute,
        Cue::Unmute,
        Cue::Deafen,
        Cue::Undeafen,
        Cue::Join,
        Cue::Leave,
        Cue::UserJoin,
        Cue::UserLeave,
        Cue::UserMoved,
        Cue::StreamStarted,
        Cue::StreamEnded,
        Cue::StreamUserJoined,
        Cue::StreamUserLeft,
        Cue::Calling,
        Cue::Ringing,
    ];

    /// Every sound RustCord plays: the voice cues above and the message sound.
    pub const FILES: [Cue; 16] = {
        let mut files = [Cue::Message; 16];
        let mut i = 0;
        while i < Cue::ALL.len() {
            files[i] = Cue::ALL[i];
            i += 1;
        }
        files
    };

    /// Discord's sound for this cue: its name in Discord's client and its file under
    /// `discord.com/assets` (read from Discord web's bundle, 2026-11-15).
    fn asset(self) -> (&'static str, &'static str) {
        match self {
            Cue::Mute => ("mute", "2d3b4ba32c34c862"),
            Cue::Unmute => ("unmute", "e74c4a06134a20e4"),
            Cue::Deafen => ("deafen", "529ff198eac567af"),
            Cue::Undeafen => ("undeafen", "b150f03c89944403"),
            Cue::Join | Cue::UserJoin => ("user_join", "b135ff6c8e091b43"),
            Cue::Leave => ("disconnect", "dd0911025fe00b2e"),
            Cue::UserLeave => ("user_leave", "7b9a183742515fc2"),
            Cue::UserMoved => ("user_moved", "4003230e4086b680"),
            Cue::StreamStarted => ("stream_started", "abe52a3c92953edb"),
            Cue::StreamEnded => ("stream_ended", "cbff07b5a83e0321"),
            Cue::StreamUserJoined => ("stream_user_joined", "3d2af2764581bb2e"),
            Cue::StreamUserLeft => ("stream_user_left", "24ae9dc0184bd570"),
            Cue::Calling => ("call_calling", "5146737af413d88e"),
            Cue::Ringing => ("call_ringing", "c2a7111bb44b8da0"),
            Cue::Message => ("message1", "3ed22d14f3c30bc4"),
        }
    }

    pub fn url(self) -> String {
        format!("https://discord.com/assets/{}.mp3", self.asset().1)
    }

    /// Discord's name for the sound ("mute", "user_join"…): the key it's switched off by.
    pub fn name(self) -> &'static str {
        self.asset().0
    }

    /// What Discord's sound list calls it.
    pub fn label(self) -> &'static str {
        match self {
            Cue::Mute => "Mute",
            Cue::Unmute => "Unmute",
            Cue::Deafen => "Deafen",
            Cue::Undeafen => "Undeafen",
            Cue::Join | Cue::UserJoin => "User Join",
            Cue::Leave => "Voice Disconnected",
            Cue::UserLeave => "User Leave",
            Cue::UserMoved => "User Moved",
            Cue::StreamStarted => "Stream Started",
            Cue::StreamEnded => "Stream Stopped",
            Cue::StreamUserJoined => "Viewer Join",
            Cue::StreamUserLeft => "Viewer Leave",
            Cue::Calling => "Outgoing Ring",
            Cue::Ringing => "Incoming Ring",
            Cue::Message => "Message",
        }
    }

    /// The cue whose sound file `url` is.
    pub fn from_url(url: &str) -> Option<Cue> {
        Cue::FILES.into_iter().find(|c| c.url() == url)
    }

    /// Where the downloaded sound is kept.
    fn file(self) -> Option<std::path::PathBuf> {
        directories::ProjectDirs::from("dev", "RustCord", "RustCord").map(|d| d.cache_dir().join("sounds").join(format!("{}.mp3", self.asset().0)))
    }
}

pub struct TrackState {
    pub playing: bool,
    pub loading: bool,
    pub position: Duration,
    pub duration: Option<Duration>,
}

impl AudioPlayer {
    pub fn state(&self, url: &str) -> TrackState {
        let loading = self.waiting_for.as_deref() == Some(url);
        match self.current.as_ref().filter(|p| p.url == url) {
            Some(p) if !p.sink.empty() => TrackState {
                playing: !p.sink.is_paused(),
                loading,
                position: p.sink.get_pos(),
                duration: p.duration,
            },
            Some(p) => TrackState { playing: false, loading, position: Duration::ZERO, duration: p.duration },
            None => TrackState { playing: false, loading, position: Duration::ZERO, duration: None },
        }
    }

    pub fn is_playing(&self) -> bool {
        self.current.as_ref().is_some_and(|p| !p.sink.empty() && !p.sink.is_paused())
    }

    /// Start playing `url` from bytes. Errors are human-readable.
    pub fn start(&mut self, url: &str, bytes: Arc<[u8]>) -> Result<(), String> {
        self.waiting_for = None;
        if let Some(old) = self.current.take() {
            old.sink.stop();
        }
        if self.output.is_none() {
            let mut out = DeviceSinkBuilder::open_default_sink().map_err(|e| format!("No audio output device: {e}"))?;
            out.log_on_drop(false);
            self.output = Some(out);
        }
        let output = self.output.as_ref().expect("output initialised");
        let decoder = decode(bytes).map_err(|e| format!("Can't play this file: {e}"))?;
        let duration = decoder.total_duration();
        let sink = Sink::connect_new(output.mixer());
        sink.set_volume(if self.muted { 0.0 } else { 1.0 });
        sink.append(decoder);
        self.current = Some(Playing { url: url.to_string(), sink, duration });
        Ok(())
    }

    /// A paused sink playing `source` (a video's sound, decoded as it plays).
    pub fn open_source_sink<S>(&mut self, source: S) -> Result<Sink, String>
    where
        S: Source + Send + 'static,
    {
        if self.output.is_none() {
            let mut out = DeviceSinkBuilder::open_default_sink().map_err(|e| format!("No audio output device: {e}"))?;
            out.log_on_drop(false);
            self.output = Some(out);
        }
        let output = self.output.as_ref().expect("output initialised");
        let sink = Sink::connect_new(output.mixer());
        sink.pause();
        sink.append(source);
        Ok(sink)
    }

    /// Remember a downloaded audio file. Only the last few are kept: each
    /// is the whole file, and they used to pile up for the whole session.
    pub fn remember(&mut self, url: String, bytes: Arc<[u8]>) {
        if self.cache.len() >= 3 {
            let playing = self.current.as_ref().map(|p| p.url.clone());
            self.cache.retain(|u, _| Some(u) == playing.as_ref());
        }
        self.cache.insert(url, bytes);
    }

    /// Play/pause. Returns `Some(url)` if the bytes still need downloading.
    pub fn toggle(&mut self, url: &str) -> Result<Option<String>, String> {
        if let Some(p) = self.current.as_ref().filter(|p| p.url == url && !p.sink.empty()) {
            if p.sink.is_paused() {
                p.sink.play();
            } else {
                p.sink.pause();
            }
            return Ok(None);
        }
        match self.cache.get(url).cloned() {
            Some(bytes) => self.start(url, bytes).map(|_| None),
            None => {
                self.waiting_for = Some(url.to_string());
                Ok(Some(url.to_string()))
            }
        }
    }

    pub fn seek(&mut self, url: &str, fraction: f32) {
        if let Some(p) = self.current.as_ref().filter(|p| p.url == url) {
            if let Some(d) = p.duration {
                let _ = p.sink.try_seek(d.mul_f32(fraction.clamp(0.0, 1.0)));
            }
        }
    }

    pub fn toggle_mute(&mut self) {
        self.muted = !self.muted;
        if let Some(p) = &self.current {
            p.sink.set_volume(if self.muted { 0.0 } else { 1.0 });
        }
    }

    /// Play a soundboard sound (fire and forget; several may overlap).
    pub fn play_effect(&mut self, bytes: Arc<[u8]>, volume: f32) {
        if self.output.is_none() {
            match DeviceSinkBuilder::open_default_sink() {
                Ok(mut out) => {
                    out.log_on_drop(false);
                    self.output = Some(out);
                }
                Err(e) => {
                    log::warn!("soundboard: no audio output: {e}");
                    return;
                }
            }
        }
        let Some(output) = self.output.as_ref() else { return };
        let bytes_for_opus = bytes.clone();
        match decode(bytes) {
            Ok(decoder) => {
                let sink = Sink::connect_new(output.mixer());
                sink.set_volume(volume.clamp(0.0, 2.0));
                sink.append(decoder);
                sink.detach();
            }
            // Ogg Opus (rodio has no Opus): decode it with the calls' libopus.
            Err(e) => match voice::decode_ogg_opus(&bytes_for_opus) {
                Some((channels, pcm)) => {
                    let (Some(ch), Some(rate)) = (std::num::NonZero::new(channels), std::num::NonZero::new(48_000)) else { return };
                    let sink = Sink::connect_new(output.mixer());
                    sink.set_volume(volume.clamp(0.0, 2.0));
                    sink.append(rodio::buffer::SamplesBuffer::new(ch, rate, pcm));
                    sink.detach();
                }
                None => {
                    let magic: String = bytes_for_opus.iter().take(12).map(|b| if b.is_ascii_graphic() { *b as char } else { '.' }).collect();
                    log::warn!("soundboard: can't decode the sound ({} bytes, starts {magic:?}): {e}", bytes_for_opus.len());
                }
            },
        }
    }

    /// Load Discord's cached sounds; returns the URLs of those still to download.
    pub fn load_cues(&mut self) -> Vec<String> {
        let mut missing = Vec::new();
        for cue in Cue::FILES {
            let name = cue.asset().0;
            if self.cue_sounds.contains_key(name) {
                continue;
            }
            match cue.file().and_then(|p| std::fs::read(p).ok()).filter(|b| b.len() > 256) {
                Some(bytes) => {
                    self.cue_sounds.insert(name, Arc::from(bytes));
                }
                None if !missing.contains(&cue.url()) => missing.push(cue.url()),
                None => {}
            }
        }
        missing
    }

    /// A sound arrived from Discord: use it from now on and keep it on disk.
    pub fn cue_downloaded(&mut self, cue: Cue, bytes: Arc<[u8]>) {
        if decode(bytes.clone()).is_err() {
            log::warn!("voice cue: Discord's {} sound didn't decode; it stays silent", cue.asset().0);
            return;
        }
        if let Some(path) = cue.file() {
            if let Some(dir) = path.parent() {
                let _ = std::fs::create_dir_all(dir);
            }
            let _ = std::fs::write(path, &bytes[..]);
        }
        self.cue_sounds.insert(cue.asset().0, bytes);
    }

    fn open_output(&mut self) -> Option<&MixerDeviceSink> {
        if self.output.is_none() {
            match DeviceSinkBuilder::open_default_sink() {
                Ok(mut out) => {
                    out.log_on_drop(false);
                    self.output = Some(out);
                }
                Err(e) => {
                    log::warn!("voice cue: no audio output: {e}");
                    return None;
                }
            }
        }
        self.output.as_ref()
    }

    /// Play one of Discord's sounds on the system's default speakers. Independent of the
    /// call's own audio, so a deafen cue is heard even though the call just went silent.
    /// Silent until Discord's file has been downloaded.
    pub fn cue(&mut self, cue: Cue, volume: f32) {
        let Some(decoder) = self.cue_sounds.get(cue.asset().0).cloned().and_then(|bytes| decode(bytes).ok()) else { return };
        let Some(output) = self.open_output() else { return };
        let sink = Sink::connect_new(output.mixer());
        sink.set_volume(volume.clamp(0.0, 2.0));
        sink.append(decoder);
        sink.detach();
    }

    /// The looping call sound that should be playing now (`None`: silence). Cheap to call
    /// every frame; a sound that hasn't been downloaded yet starts once it has.
    pub fn set_ring(&mut self, cue: Option<Cue>, volume: f32) {
        if self.ring.as_ref().map(|(c, _)| *c) == cue {
            return;
        }
        if let Some((_, sink)) = self.ring.take() {
            sink.stop();
        }
        let Some(cue) = cue else { return };
        let Some(decoder) = self.cue_sounds.get(cue.asset().0).cloned().and_then(|bytes| decode(bytes).ok()) else { return };
        let Some(output) = self.open_output() else { return };
        let sink = Sink::connect_new(output.mixer());
        sink.set_volume(volume.clamp(0.0, 2.0));
        sink.append(decoder.repeat_infinite());
        self.ring = Some((cue, sink));
    }
}

pub fn fmt_time(d: Duration) -> String {
    let s = d.as_secs();
    format!("{}:{:02}", s / 60, s % 60)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn every_sound_is_one_of_discords_files() {
        for cue in Cue::FILES {
            let hash = cue.asset().1;
            assert!(hash.len() == 16 && hash.bytes().all(|b| b.is_ascii_hexdigit()), "{cue:?}");
            assert!(cue.url().starts_with("https://discord.com/assets/") && cue.url().ends_with(".mp3"));
            assert_eq!(Cue::from_url(&cue.url()).map(|c| c.asset()), Some(cue.asset()));
        }
        assert_eq!(Cue::FILES[..Cue::ALL.len()], Cue::ALL);
        assert_eq!(Cue::from_url(&Cue::Message.url()), Some(Cue::Message));
        assert_eq!(Cue::from_url("https://discord.com/assets/other.mp3"), None);
    }
}