Skip to main content

Crate djs_voice

Crate djs_voice 

Source
Expand description

§djs-voice

Discord voice for djs-rs: joining voice channels, playing audio into them and receiving it, with the end-to-end encryption (DAVE) Discord requires for every call since March 2026.

Status: alpha (the API may still change between alpha releases). It follows songbird’s concepts (D-316): a VoiceManager per bot, a Call per guild, and tracks played into it, one at a time, from a queue. It joins voice channels (with DAVE), plays Ogg/Opus, PCM and anything FFmpeg reads, with a queue, volume, loops and seeking, receives each user’s audio, and reports the call’s and the tracks’ events. Measured in docs/PERFORMANCE.md (“Phase 10”): about 700 calls per core passing Ogg/Opus through, 75–100 encoding, and a call receiving 200 speakers at once without a loss.

  • Works on its own through a small gateway adapter, VoiceGateway (D-315, D-324), or through djs-rs’s voice feature, which plugs it into the Client.
  • Plays Ogg/Opus natively, sent as it is at volume 1.0 (Input::ogg, Input::ogg_file), raw 48 kHz PCM (Input::pcm), and any file or URL through FFmpeg (Input::ffmpeg, which needs ffmpeg installed) (D-317, D-354).
  • call.play plays now, call.enqueue after the others (call.queue(): skip, clear); each track’s handle pauses, stops, sets the volume, loops and seeks, and gives its state (info) and events (events) (D-352–D-361).
  • call.subscribe(user) receives a user’s audio as a stream of packets, in order (lost ones reported), as Opus or decoded to 48 kHz stereo i16 (ReceiveOptions; decoded on the reading task, D-374, so a call keeps up with many speakers), ending by itself after silence if asked (EndBehavior); CallEvent::SpeakingStarted and SpeakingStopped say who speaks (D-363–D-373). Join with JoinOptions::self_deaf(false) to receive: Discord sends a deafened bot nobody’s audio.
  • DAVE comes from the davey crate (D-312), Opus from opus2 with libopus 1.5 built from source and linked statically (D-350: CMake and a C compiler are needed to build), and the transport encryption from aes-gcm and chacha20poly1305 (D-314).
use std::{error::Error, time::Duration};

use djs_model::{
    gateway::{DispatchEvent, payload::UpdateVoiceState},
    id::{ChannelId, GuildId, UserId},
};
use djs_voice::{
    CallEvent, EndBehavior, Input, JoinOptions, ReceiveOptions, TrackEvent, VoiceData,
    VoiceGateway, VoiceManager,
};

/// Sends Opcode 4 through the bot's shards (djs-rs's `voice` feature does this for you).
struct Shards;

impl VoiceGateway for Shards {
    fn send(
        &self,
        shard_id: u32,
        command: &UpdateVoiceState,
    ) -> Result<(), Box<dyn Error + Send + Sync>> {
        // e.g. `shards[shard_id].sender().command(command)?`
        Ok(())
    }
}

let manager = VoiceManager::new(UserId::new(1), 1, Shards);
// The main gateway's events go through `process`.
let voice = manager.clone();
tokio::spawn(async move {
    loop {
        voice.process(&next_gateway_event().await);
    }
});

// Not deafened: to hear the channel.
let options = JoinOptions::new().self_deaf(false);
let call = manager
    .join_with(GuildId::new(2), ChannelId::new(3), options)
    .await?;
let intro = call.play(Input::ogg_file("intro.opus").await?);
let song = call.enqueue(Input::ffmpeg("song.mp3"));
song.set_volume(0.5)?;
let mut song_events = song.events();
tokio::spawn(async move {
    while let Some(event) = song_events.next().await {
        if let TrackEvent::Ended(reason) = event {
            println!("the song ended: {reason}");
        }
    }
});
let mut events = call.events();
while let Some(event) = events.next().await {
    match event {
        CallEvent::UserJoined(user) => println!("{user} joined"),
        CallEvent::SpeakingStarted(user) => {
            // Record what they say from now on, decoded, until half a second of silence.
            let options = ReceiveOptions::new()
                .decode(true)
                .end(EndBehavior::AfterSilence(Duration::from_millis(500)));
            let mut voice = call.subscribe_with(user, options);
            tokio::spawn(async move {
                let mut samples = Vec::new();
                while let Some(packet) = voice.next().await {
                    if let VoiceData::Pcm(pcm) = packet.audio {
                        samples.extend(pcm);
                    }
                }
            });
        }
        CallEvent::Disconnected(reason) => println!("the call ended: {reason}"),
        _ => {}
    }
}

§Licenses

djs-voice is MIT OR Apache-2.0 like the rest of djs-rs. DAVE’s MLS stack under davey uses three HPKE crates (hpke-rs*) licensed MPL-2.0, unmodified (D-326): a bot that uses djs-voice links them, and their source stays available on crates.io. libopus, built into the bot, is BSD-3-Clause: a bot distributed as a binary must reproduce its copyright notice (see NOTICE).

discord.js counterpart: @discordjs/voice; the concepts are songbird’s.

Structs§

Call
The bot’s voice connection in one guild, from VoiceManager::join: it plays tracks, reports its events, and leaves.
CallEvents
The stream of a Call’s events. Created by Call::events.
Input
What a track plays, given to Call::play or Call::enqueue.
JoinOptions
How a VoiceManager joins a channel: the bot’s own mute and deafen flags (D-341, D-343), and the bitrate of the audio it encodes (D-357). The default is deafened and not muted, as discord.js’s joinVoiceChannel does (a bot that only plays gets nobody’s audio), at 128 kb/s.
ReceiveOptions
How Call::subscribe_with receives a user’s audio (D-372): the packets as Opus or decoded to PCM (D-364), and when the stream ends (D-365). The default is Opus, ended manually, as discord.js’s VoiceReceiver#subscribe.
TrackEvents
The stream of a track’s events. Created by TrackHandle::events.
TrackHandle
Controls a track that Call::play or Call::enqueue gave the call: pause it, play it again, stop it, change its volume, loop it, seek in it, read its state, follow its events.
TrackInfo
A track’s state, from TrackHandle::info (D-356).
TrackQueue
The queue of a Call, from Call::queue: skip the current track, clear the waiting ones, see what plays (D-352).
VoiceManager
The bot’s voice calls, one per guild: joins voice channels and keeps the calls.
VoicePacket
A packet of a user’s audio, from a VoiceStream (D-368), in the order the user sent them: each one follows the one before, by sequence.
VoiceStream
The packets of one user’s audio, from Call::subscribe (D-371). It ends with its call, or as its EndBehavior says; dropping it unsubscribes.

Enums§

CallEvent
An event of a Call, from Call::events (D-321, D-337).
DisconnectReason
Why a call ended (D-344), in CallEvent::Disconnected.
EndBehavior
When a VoiceStream ends by itself (D-365); it always ends with its call.
InputError
Why an Input cannot be played.
JoinError
Why VoiceManager::join failed.
Loop
Whether a track plays again at its end (D-358), for TrackHandle::set_loop.
PlayState
Where a track is (D-361), in TrackInfo::state.
TrackEnd
Why a track ended (D-355), in TrackEvent::Ended.
TrackError
Why a TrackHandle control did nothing (D-339, D-360).
TrackEvent
An event of a track, from TrackHandle::events (D-355).
VoiceData
The audio of a VoicePacket (D-368).

Traits§

VoiceGateway
Sends Opcode 4 (Update Voice State) through a shard of the main gateway: how a VoiceManager joins, moves between and leaves voice channels.