djs_voice/manager.rs
1//! The voice manager: the bot's calls, one per guild (D-319, D-322, D-324, D-340–D-343).
2
3use core::{
4 fmt,
5 sync::atomic::{AtomicU64, Ordering},
6};
7use std::{collections::HashMap, sync::Arc};
8
9use djs_model::{
10 gateway::{DispatchEvent, payload::UpdateVoiceState},
11 id::{ChannelId, GuildId, UserId},
12};
13use tokio::sync::oneshot;
14
15use crate::{
16 Call, JoinError, VoiceGateway,
17 call::{CallCommand, Calls, Spawn, lock},
18 codec::DEFAULT_BITRATE,
19 connection::Config,
20};
21
22/// How a [`VoiceManager`] joins a channel: the bot's own mute and deafen flags (D-341,
23/// D-343), and the bitrate of the audio it encodes (D-357). The default is deafened and not
24/// muted, as discord.js's `joinVoiceChannel` does (a bot that only plays gets nobody's
25/// audio), at 128 kb/s.
26///
27/// discord.js counterpart: the `selfDeaf` and `selfMute` options of `joinVoiceChannel`.
28///
29/// # Examples
30///
31/// ```
32/// use djs_voice::JoinOptions;
33///
34/// // Hear the channel (to receive audio, later), and start muted.
35/// let options = JoinOptions::new().self_deaf(false).self_mute(true);
36/// assert_ne!(options, JoinOptions::default());
37/// // Encode at 96 kb/s, a common voice-channel bitrate.
38/// let options = JoinOptions::new().bitrate(96_000);
39/// ```
40#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
41#[non_exhaustive]
42pub struct JoinOptions {
43 self_mute: bool,
44 self_deaf: bool,
45 bitrate: u32,
46}
47
48impl Default for JoinOptions {
49 fn default() -> Self {
50 Self::new()
51 }
52}
53
54impl JoinOptions {
55 /// The default options: deafened, not muted, 128 kb/s.
56 ///
57 /// discord.js counterpart: `JoinVoiceChannelOptions` (`@discordjs/voice`).
58 #[must_use]
59 pub const fn new() -> Self {
60 Self {
61 self_mute: false,
62 self_deaf: true,
63 bitrate: DEFAULT_BITRATE,
64 }
65 }
66
67 /// Whether the bot mutes itself (others see it muted; it can still send audio, which
68 /// Discord drops).
69 ///
70 /// discord.js counterpart: the `selfMute` option of `joinVoiceChannel` (`@discordjs/voice`).
71 #[must_use]
72 pub const fn self_mute(mut self, self_mute: bool) -> Self {
73 self.self_mute = self_mute;
74 self
75 }
76
77 /// Whether the bot deafens itself: Discord sends it nobody's audio.
78 ///
79 /// discord.js counterpart: the `selfDeaf` option of `joinVoiceChannel` (`@discordjs/voice`).
80 #[must_use]
81 pub const fn self_deaf(mut self, self_deaf: bool) -> Self {
82 self.self_deaf = self_deaf;
83 self
84 }
85
86 /// The bitrate, in bits per second, of the audio the call encodes (D-357): PCM, FFmpeg,
87 /// and Ogg/Opus at a volume other than 1.0 (Ogg/Opus at 1.0 is sent as it is). 128 kb/s
88 /// by default, as songbird; clamped to what libopus accepts, 500 b/s to 512 kb/s. A
89 /// channel's own bitrate (8 to 96 kb/s, more with boosts) does not limit what the bot
90 /// sends.
91 ///
92 /// Joining again with other options changes the bitrate of the call's next frames.
93 ///
94 /// songbird counterpart: `Call::set_bitrate`.
95 ///
96 /// discord.js counterpart: none (`@discordjs/voice` encodes at a fixed rate).
97 #[must_use]
98 pub const fn bitrate(mut self, bits_per_second: u32) -> Self {
99 self.bitrate = bits_per_second;
100 self
101 }
102}
103
104/// The bot's voice calls, one per guild: joins voice channels and keeps the calls.
105///
106/// The manager sends Opcode 4 through a [`VoiceGateway`] and learns Discord's answers from
107/// the main gateway's events, which the bot passes to [`process`](Self::process) (D-324).
108/// djs-rs's `voice` feature does both and gives the manager as `client.voice()`. A cheap-clone
109/// handle: clones share the calls.
110///
111/// discord.js counterpart: `joinVoiceChannel` and `getVoiceConnection` of `@discordjs/voice`;
112/// songbird: `Songbird`.
113///
114/// # Examples
115///
116/// ```no_run
117/// # use std::error::Error;
118/// # use djs_model::{gateway::{DispatchEvent, payload::UpdateVoiceState}, id::{ChannelId, GuildId, UserId}};
119/// # struct Shards;
120/// # impl djs_voice::VoiceGateway for Shards {
121/// # fn send(&self, _: u32, _: &UpdateVoiceState) -> Result<(), Box<dyn Error + Send + Sync>> { Ok(()) }
122/// # }
123/// # async fn next_event() -> DispatchEvent { unimplemented!() }
124/// # async fn run(bot: UserId, guild: GuildId, channel: ChannelId) -> Result<(), Box<dyn Error + Send + Sync>> {
125/// use djs_voice::{Input, VoiceManager};
126///
127/// let manager = VoiceManager::new(bot, 1, Shards);
128/// // Every event of the main gateway goes through `process`.
129/// let events = manager.clone();
130/// tokio::spawn(async move {
131/// loop {
132/// events.process(&next_event().await);
133/// }
134/// });
135/// let call = manager.join(guild, channel).await?;
136/// call.play(Input::ogg_file("hello.opus").await?);
137/// # Ok(()) }
138/// ```
139#[derive(Clone)]
140pub struct VoiceManager {
141 inner: Arc<Inner>,
142}
143
144struct Inner {
145 user_id: UserId,
146 shard_count: u32,
147 gateway: Arc<dyn VoiceGateway>,
148 calls: Arc<Calls>,
149 config: Config,
150 next_call: AtomicU64,
151}
152
153impl fmt::Debug for VoiceManager {
154 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
155 f.debug_struct("VoiceManager")
156 .field("user_id", &self.inner.user_id)
157 .field("shard_count", &self.inner.shard_count)
158 .field("calls", &lock(&self.inner.calls).len())
159 .finish_non_exhaustive()
160 }
161}
162
163impl VoiceManager {
164 /// A manager of the bot `bot_user_id`, whose main gateway has `shard_count` shards (0 is
165 /// taken as 1), sending Opcode 4 through `gateway`.
166 ///
167 /// discord.js counterpart: none (the adapter of each `joinVoiceChannel` call).
168 #[must_use]
169 pub fn new(bot_user_id: UserId, shard_count: u32, gateway: impl VoiceGateway) -> Self {
170 Self::with_config(bot_user_id, shard_count, gateway, Config::default())
171 }
172
173 pub(crate) fn with_config(
174 bot_user_id: UserId,
175 shard_count: u32,
176 gateway: impl VoiceGateway,
177 config: Config,
178 ) -> Self {
179 Self {
180 inner: Arc::new(Inner {
181 user_id: bot_user_id,
182 shard_count: shard_count.max(1),
183 gateway: Arc::new(gateway),
184 calls: Arc::new(Calls::new(HashMap::new())),
185 config,
186 next_call: AtomicU64::new(0),
187 }),
188 }
189 }
190
191 /// Takes in an event of the main gateway. Only the bot's own `VOICE_STATE_UPDATE`s and
192 /// the `VOICE_SERVER_UPDATE`s of guilds with a call matter; everything else is ignored,
193 /// so passing every event is fine.
194 ///
195 /// discord.js counterpart: `DiscordGatewayAdapterImplementerMethods#onVoiceStateUpdate`
196 /// and `onVoiceServerUpdate`.
197 pub fn process(&self, event: &DispatchEvent) {
198 match event {
199 DispatchEvent::VoiceStateUpdate(state) => {
200 if state.user_id != self.inner.user_id {
201 return;
202 }
203 if let Some(call) = state.guild_id.and_then(|guild_id| self.get(guild_id)) {
204 call.command(CallCommand::State {
205 session_id: state.session_id.to_string(),
206 channel_id: state.channel_id,
207 });
208 }
209 }
210 DispatchEvent::VoiceServerUpdate(server) => {
211 if let Some(call) = self.get(server.guild_id) {
212 call.command(CallCommand::Server {
213 token: server.token.to_string(),
214 endpoint: server.endpoint.as_ref().map(ToString::to_string),
215 });
216 }
217 }
218 _ => {}
219 }
220 }
221
222 /// Joins the voice channel `channel_id` of `guild_id`, deafened and not muted
223 /// ([`JoinOptions::default`]); returns the [`Call`] once it is connected (D-322, D-349).
224 ///
225 /// With end-to-end encryption (DAVE, which Discord requires), audio goes out once the bot
226 /// is in the call's MLS group: about a second after someone else is in the channel. A
227 /// bot alone in a channel has no group, so what it plays is not sent (nobody would hear
228 /// it); nothing is ever sent without end-to-end encryption.
229 ///
230 /// When the bot already has a call in the guild, it moves to the channel, and the same
231 /// call is returned (D-340).
232 ///
233 /// discord.js counterpart: `joinVoiceChannel` (which returns at once); songbird:
234 /// `Songbird::join`.
235 ///
236 /// # Errors
237 ///
238 /// [`JoinError::Gateway`] when Opcode 4 cannot be sent, [`JoinError::Timeout`] when the
239 /// call is not ready within 10 seconds (also when the bot lacks the Connect permission:
240 /// Discord does not answer), [`JoinError::Connection`] when the voice connection fails,
241 /// [`JoinError::Cancelled`] when the call is left or joined elsewhere meanwhile.
242 pub async fn join(&self, guild_id: GuildId, channel_id: ChannelId) -> Result<Call, JoinError> {
243 self.join_with(guild_id, channel_id, JoinOptions::default())
244 .await
245 }
246
247 /// [`join`](Self::join) with `options`.
248 ///
249 /// discord.js counterpart: `joinVoiceChannel` with options (`@discordjs/voice`).
250 ///
251 /// # Errors
252 ///
253 /// As [`join`](Self::join).
254 pub async fn join_with(
255 &self,
256 guild_id: GuildId,
257 channel_id: ChannelId,
258 options: JoinOptions,
259 ) -> Result<Call, JoinError> {
260 // A call that is just ending may still be in the map: its join is not answered,
261 // and the next attempt makes a new call.
262 let mut attempts = 0;
263 loop {
264 attempts += 1;
265 let call = self.call(guild_id);
266 let (done, result) = oneshot::channel();
267 let bitrate = options.bitrate;
268 if !call.command(CallCommand::Join {
269 channel_id,
270 bitrate,
271 done,
272 }) {
273 self.forget(&call);
274 continue;
275 }
276 let command = UpdateVoiceState::new(
277 guild_id,
278 Some(channel_id),
279 options.self_mute,
280 options.self_deaf,
281 );
282 if let Err(error) = self.inner.gateway.send(self.shard_id(guild_id), &command) {
283 drop(result);
284 call.command(CallCommand::Abandoned);
285 return Err(JoinError::Gateway(error));
286 }
287 match result.await {
288 Ok(Ok(())) => return Ok(call),
289 Ok(Err(error)) => return Err(error),
290 Err(_) if attempts < 2 => self.forget(&call),
291 Err(_) => return Err(JoinError::Cancelled),
292 }
293 }
294 }
295
296 /// The bot's call in `guild_id`, if it has one.
297 ///
298 /// discord.js counterpart: `getVoiceConnection`; songbird: `Songbird::get`.
299 #[must_use]
300 pub fn get(&self, guild_id: GuildId) -> Option<Call> {
301 lock(&self.inner.calls).get(&guild_id).cloned()
302 }
303
304 /// The bot's current calls, in no particular order.
305 ///
306 /// discord.js counterpart: `getVoiceConnections`; songbird: `Songbird::iter`.
307 ///
308 /// # Examples
309 ///
310 /// ```no_run
311 /// # async fn run(manager: djs_voice::VoiceManager) {
312 /// for call in manager.calls() {
313 /// println!("in {:?} of {}", call.channel_id(), call.guild_id());
314 /// }
315 /// # }
316 /// ```
317 #[must_use]
318 pub fn calls(&self) -> Vec<Call> {
319 lock(&self.inner.calls).values().cloned().collect()
320 }
321
322 /// The guild's call, made if there is none.
323 fn call(&self, guild_id: GuildId) -> Call {
324 lock(&self.inner.calls)
325 .entry(guild_id)
326 .or_insert_with(|| {
327 Call::spawn(Spawn {
328 id: self.inner.next_call.fetch_add(1, Ordering::Relaxed),
329 guild_id,
330 user_id: self.inner.user_id,
331 shard_id: self.shard_id(guild_id),
332 gateway: Arc::clone(&self.inner.gateway),
333 config: self.inner.config.clone(),
334 calls: Arc::downgrade(&self.inner.calls),
335 })
336 })
337 .clone()
338 }
339
340 /// Removes a call that ended from the map, if it is still there.
341 fn forget(&self, call: &Call) {
342 let mut calls = lock(&self.inner.calls);
343 if calls
344 .get(&call.guild_id())
345 .is_some_and(|current| current.inner.id == call.inner.id)
346 {
347 calls.remove(&call.guild_id());
348 }
349 }
350
351 /// The shard of a guild: `(guild_id >> 22) % shard_count`, as Discord documents.
352 fn shard_id(&self, guild_id: GuildId) -> u32 {
353 let shard = (guild_id.get() >> 22) % u64::from(self.inner.shard_count);
354 // Below `shard_count`, a `u32`.
355 u32::try_from(shard).unwrap_or_default()
356 }
357}
358
359#[cfg(test)]
360mod player_tests;
361#[cfg(test)]
362mod receive_tests;
363#[cfg(test)]
364mod stress_tests;
365#[cfg(test)]
366mod tests;