Skip to main content

djs_voice/
call.rs

1//! A call: the bot's voice connection in one guild, and what it plays (D-316, D-319–D-323,
2//! D-335, D-337, D-340, D-344, D-351–D-361).
3//!
4//! A [`Call`] is a handle on a task that owns everything: the voice state the main gateway
5//! reported, the voice connection (or the one being made), and the player. The handle's
6//! methods send it commands (D-320). The task joins when both halves of the voice state
7//! arrived (`VOICE_STATE_UPDATE` with the channel, then a `VOICE_SERVER_UPDATE`), connects
8//! again to a new voice server when the bot is moved, and ends the call when the connection
9//! ends for good. Its player plays the current track of the call's [queue](crate::queue)
10//! (C-126).
11
12use core::{
13    fmt,
14    pin::Pin,
15    sync::atomic::{AtomicU64, Ordering},
16    task::{Context, Poll},
17    time::Duration,
18};
19use std::{
20    collections::{HashMap, VecDeque},
21    error::Error,
22    sync::{Arc, Mutex, MutexGuard, PoisonError, Weak},
23};
24
25use djs_model::{
26    gateway::payload::UpdateVoiceState,
27    id::{ChannelId, GuildId, UserId},
28};
29use futures_util::Stream;
30use tokio::{
31    sync::{
32        mpsc::{self, error::TryRecvError},
33        oneshot, watch,
34    },
35    task::JoinHandle,
36    time::{Instant, sleep_until},
37};
38
39use crate::{
40    Input, InputError, JoinError, TrackError, TrackHandle, TrackQueue, VoiceGateway,
41    codec::{self, Decoder, Encoder, MAX_PACKET, MAX_PACKET_VALUES},
42    connection::{
43        self, Command, Config, ConnectError, ConnectionEvent, End, Handle, Info, Receiver, Sender,
44    },
45    input::{self as reading, Again, Chunk, Frame, History, Source},
46    payload::{Event, MICROPHONE},
47    queue::{Queue, Shared, Slot},
48    receive::{self, ReceiveOptions, Receiving, VoiceStream},
49    track::{Track, TrackEnd, TrackEvent, duration},
50    udp::Rtp,
51};
52
53/// The close code of a bot disconnected from its channel (kicked, the channel deleted) or
54/// moved to another: in the second case a new voice server follows.
55const DISCONNECTED: u16 = 4014;
56/// How long the call waits after a close with [`DISCONNECTED`] for the voice server of a
57/// new channel, before it ends (as `@discordjs/voice`'s guide does).
58const MOVE_GRACE: Duration = Duration::from_secs(5);
59/// The frames of silence sent when audio stops, so that receivers do not interpolate
60/// (Discord's "Voice Data Interpolation").
61const SILENCE_FRAMES: u8 = 5;
62/// The Opus packet of a 20 ms frame of silence.
63const SILENCE: [u8; 3] = [0xF8, 0xFF, 0xFE];
64/// How late a frame may be before the pace starts over from now, rather than catching up
65/// with a burst.
66const LATE: Duration = Duration::from_millis(100);
67/// How many packets a track's input is read ahead: about a second of 20 ms packets.
68const AHEAD: usize = 50;
69/// How many Opus packets are still re-encoded at gain 1.0 after a change of gain, before
70/// they go out as they are again: the listeners' decoders overlap each frame with the one
71/// before, which must then hold the same audio (C-127).
72const SETTLE: u8 = 2;
73
74/// A chunk read from a track's input.
75type Read = Option<Result<Chunk, InputError>>;
76
77/// An Ogg/Opus track's packets being re-encoded (a gain other than 1.0: a volume, a fade),
78/// in step with the packets as they are (C-127). The encoder's output comes its lookahead
79/// behind its input, so it is given the audio that far ahead: `fifo` holds the decoded audio
80/// from the start of the current frame plus the lookahead on.
81struct Reencode {
82    decoder: Decoder,
83    fifo: VecDeque<f32>,
84    /// Packets re-encoded at gain 1.0 since the gain last changed ([`SETTLE`]).
85    steady: u8,
86}
87
88/// The calls of a manager, by guild.
89pub(crate) type Calls = Mutex<HashMap<GuildId, Call>>;
90
91pub(crate) fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
92    mutex.lock().unwrap_or_else(PoisonError::into_inner)
93}
94
95/// The bot's voice connection in one guild, from
96/// [`VoiceManager::join`](crate::VoiceManager::join): it plays tracks, reports its events,
97/// and leaves.
98///
99/// A cheap-clone handle (D-320): clones are the same call, and every method takes `&self`.
100/// A lost connection is resumed or made again in the background (D-331), and a move to
101/// another channel (by [`join`](crate::VoiceManager::join) or by a moderator) connects it
102/// again; [`events`](Self::events) reports both. The call ends when the bot
103/// [leaves](Self::leave), is disconnected, or its connection cannot be repaired
104/// ([`CallEvent::Disconnected`]).
105///
106/// Discord documents voice connections at
107/// <https://discord.com/developers/docs/topics/voice-connections>.
108///
109/// discord.js counterpart: `VoiceConnection` with a subscribed `AudioPlayer` of
110/// `@discordjs/voice`; songbird: `Call`.
111///
112/// # Examples
113///
114/// ```no_run
115/// # async fn run(
116/// #     manager: djs_voice::VoiceManager,
117/// #     guild: djs_model::id::GuildId,
118/// #     channel: djs_model::id::ChannelId,
119/// # ) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
120/// use djs_voice::{CallEvent, Input};
121///
122/// let call = manager.join(guild, channel).await?;
123/// let mut events = call.events();
124/// call.play(Input::ogg_file("intro.opus").await?);
125/// while let Some(event) = events.next().await {
126///     if let CallEvent::Disconnected(reason) = event {
127///         println!("the call ended: {reason}");
128///     }
129/// }
130/// # Ok(()) }
131/// ```
132#[derive(Clone)]
133pub struct Call {
134    pub(crate) inner: Arc<Inner>,
135}
136
137pub(crate) struct Inner {
138    /// Tells this call from a later one in the same guild.
139    pub(crate) id: u64,
140    guild_id: GuildId,
141    shard_id: u32,
142    gateway: Arc<dyn VoiceGateway>,
143    /// The commands to the task, and the queue.
144    shared: Arc<Shared>,
145    subscribers: Arc<Mutex<Subscribers>>,
146    channel: watch::Receiver<Option<ChannelId>>,
147    tracks: AtomicU64,
148}
149
150#[derive(Default)]
151struct Subscribers {
152    senders: Vec<mpsc::UnboundedSender<CallEvent>>,
153    /// The call ended: new streams end at once.
154    closed: bool,
155}
156
157impl fmt::Debug for Call {
158    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
159        f.debug_struct("Call")
160            .field("guild_id", &self.inner.guild_id)
161            .field("channel_id", &self.channel_id())
162            .finish_non_exhaustive()
163    }
164}
165
166/// What a call's handles ask of its task.
167pub(crate) enum CallCommand {
168    /// Join or move to a channel: the manager sends Opcode 4 right after.
169    Join {
170        channel_id: ChannelId,
171        /// The bitrate of encoded audio (D-357).
172        bitrate: u32,
173        done: oneshot::Sender<Result<(), JoinError>>,
174    },
175    /// A join gave up (Opcode 4 could not be sent): forget its closed waiter.
176    Abandoned,
177    /// The bot's `VOICE_STATE_UPDATE` in this guild.
178    State {
179        session_id: String,
180        channel_id: Option<ChannelId>,
181    },
182    /// A `VOICE_SERVER_UPDATE` of this guild.
183    Server {
184        token: String,
185        endpoint: Option<String>,
186    },
187    /// The queue or a track changed: play the current track as it is now.
188    Wake,
189    /// Play the track `id` from `samples` (D-359).
190    Seek {
191        id: u64,
192        samples: u64,
193        done: oneshot::Sender<Result<Duration, TrackError>>,
194    },
195    Leave {
196        done: oneshot::Sender<()>,
197    },
198    /// Receive a user's audio (D-363).
199    Subscribe {
200        user_id: UserId,
201        options: ReceiveOptions,
202        tx: mpsc::Sender<receive::Item>,
203    },
204}
205
206/// Where the guild's shard is, and what the call is to the manager.
207pub(crate) struct Spawn {
208    pub(crate) id: u64,
209    pub(crate) guild_id: GuildId,
210    pub(crate) user_id: UserId,
211    pub(crate) shard_id: u32,
212    pub(crate) gateway: Arc<dyn VoiceGateway>,
213    pub(crate) config: Config,
214    pub(crate) calls: Weak<Calls>,
215}
216
217impl Call {
218    /// A new call in a guild, and its task.
219    pub(crate) fn spawn(spawn: Spawn) -> Self {
220        let (commands, commands_rx) = mpsc::unbounded_channel();
221        let (channel, channel_rx) = watch::channel(None);
222        let subscribers = Arc::new(Mutex::new(Subscribers::default()));
223        let shared = Arc::new(Shared {
224            commands,
225            queue: Mutex::new(Queue::default()),
226        });
227        let task = Task {
228            call_id: spawn.id,
229            guild_id: spawn.guild_id,
230            user_id: spawn.user_id,
231            config: spawn.config,
232            calls: spawn.calls,
233            subscribers: Arc::clone(&subscribers),
234            channel,
235            commands: commands_rx,
236            voice: VoiceState::default(),
237            fresh_server: false,
238            live: None,
239            connecting: None,
240            join: None,
241            grace: None,
242            removed: false,
243            connected_once: false,
244            leave: None,
245            player: Player::new(Arc::clone(&shared)),
246            receiving: Receiving::default(),
247        };
248        tokio::spawn(task.run());
249        Self {
250            inner: Arc::new(Inner {
251                id: spawn.id,
252                guild_id: spawn.guild_id,
253                shard_id: spawn.shard_id,
254                gateway: spawn.gateway,
255                shared,
256                subscribers,
257                channel: channel_rx,
258                tracks: AtomicU64::new(0),
259            }),
260        }
261    }
262
263    /// Sends the task a command; `false` once it has ended.
264    pub(crate) fn command(&self, command: CallCommand) -> bool {
265        self.inner.shared.commands.send(command).is_ok()
266    }
267
268    /// The guild of the call.
269    ///
270    /// discord.js counterpart: `VoiceConnection#joinConfig.guildId`.
271    #[must_use]
272    pub fn guild_id(&self) -> GuildId {
273        self.inner.guild_id
274    }
275
276    /// The voice channel the call is connected to; `None` while it is not (connecting again
277    /// after a move, or ended).
278    ///
279    /// discord.js counterpart: `VoiceConnection#joinConfig.channelId`.
280    #[must_use]
281    pub fn channel_id(&self) -> Option<ChannelId> {
282        *self.inner.channel.borrow()
283    }
284
285    /// Plays `input` now, replacing the current track (D-335, D-352): it ends
286    /// ([`TrackEnd::Replaced`]), and the tracks waiting in the [queue](Self::queue) play
287    /// after this one. Returns at once; the input is read and sent in the background, paced
288    /// in real time.
289    ///
290    /// While the call is connecting again (after a move or a lost connection) the track
291    /// keeps its pace and its audio is not sent; with end-to-end encryption (DAVE), audio is
292    /// sent once the bot is in the call's group (D-349).
293    ///
294    /// discord.js counterpart: `AudioPlayer#play` of a player subscribed to the connection;
295    /// songbird: `Call::play_only_input`.
296    ///
297    /// # Examples
298    ///
299    /// ```no_run
300    /// # async fn run(call: djs_voice::Call) -> Result<(), djs_voice::InputError> {
301    /// let track = call.play(djs_voice::Input::ogg_file("song.opus").await?);
302    /// # Ok(()) }
303    /// ```
304    #[allow(
305        clippy::must_use_candidate,
306        reason = "playing without keeping the handle is fine"
307    )]
308    pub fn play(&self, input: Input) -> TrackHandle {
309        self.add(input, true)
310    }
311
312    /// Adds `input` to the end of the call's [queue](Self::queue) (D-352): it plays when the
313    /// tracks before it have ended, at once when nothing plays. Returns its handle at once;
314    /// until its turn it is [`PlayState::Queued`](crate::PlayState::Queued), and FFmpeg is
315    /// not run for it yet.
316    ///
317    /// discord.js counterpart: none (a bot keeps its own queue); songbird:
318    /// `Call::enqueue_input`.
319    ///
320    /// # Examples
321    ///
322    /// ```no_run
323    /// # fn run(call: djs_voice::Call) {
324    /// use djs_voice::Input;
325    ///
326    /// for song in ["one.mp3", "two.mp3", "three.mp3"] {
327    ///     call.enqueue(Input::ffmpeg(song));
328    /// }
329    /// # }
330    /// ```
331    #[allow(
332        clippy::must_use_candidate,
333        reason = "queueing without keeping the handle is fine"
334    )]
335    pub fn enqueue(&self, input: Input) -> TrackHandle {
336        self.add(input, false)
337    }
338
339    fn add(&self, input: Input, now: bool) -> TrackHandle {
340        let id = self.inner.tracks.fetch_add(1, Ordering::Relaxed);
341        let track = Track::new(id, input.seekable(), Arc::downgrade(&self.inner.shared));
342        let handle = TrackHandle::new(Arc::clone(&track));
343        let slot = Slot {
344            track,
345            input: Some(input),
346        };
347        let mut queue = lock(&self.inner.shared.queue);
348        if queue.closed {
349            slot.track.end(TrackEnd::CallEnded);
350            return handle;
351        }
352        if now {
353            if let Some(old) = queue.current.replace(slot) {
354                old.track.end(TrackEnd::Replaced);
355            }
356        } else if queue.current.is_none() {
357            queue.current = Some(slot);
358        } else {
359            queue.waiting.push_back(slot);
360        }
361        drop(queue);
362        self.inner.shared.wake();
363        handle
364    }
365
366    /// The call's queue of tracks (D-352): skip the current one, clear the waiting ones,
367    /// see what plays.
368    ///
369    /// songbird counterpart: `Call::queue`.
370    ///
371    /// discord.js counterpart: none (`@discordjs/voice` has no queue).
372    #[must_use]
373    pub fn queue(&self) -> TrackQueue {
374        TrackQueue {
375            shared: Arc::clone(&self.inner.shared),
376        }
377    }
378
379    /// Receives the audio of the user `user_id` (D-363, D-367): a stream of their packets,
380    /// as Opus, in order, ended manually ([`subscribe_with`](Self::subscribe_with) chooses).
381    ///
382    /// Discord sends a bot nobody's audio while it is deafened, which is how
383    /// [`VoiceManager::join`](crate::VoiceManager::join) joins: join with
384    /// [`JoinOptions::self_deaf(false)`](crate::JoinOptions::self_deaf) to receive. The
385    /// stream may be made before the user speaks or even joins; packets come once the voice
386    /// gateway has said which source is theirs (the first time they speak). Each stream is
387    /// its own, with a copy of the packets (D-373); dropping it unsubscribes. It ends with
388    /// the call.
389    ///
390    /// discord.js counterpart: `VoiceReceiver#subscribe`; songbird: the `VoiceTick` event.
391    ///
392    /// # Examples
393    ///
394    /// ```no_run
395    /// # async fn example(manager: djs_voice::VoiceManager, guild_id: djs_model::id::GuildId,
396    /// #     channel_id: djs_model::id::ChannelId, user_id: djs_model::id::UserId)
397    /// #     -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
398    /// use djs_voice::{JoinOptions, VoiceData};
399    ///
400    /// let options = JoinOptions::new().self_deaf(false);
401    /// let call = manager.join_with(guild_id, channel_id, options).await?;
402    /// let mut voice = call.subscribe(user_id);
403    /// let mut bytes = 0;
404    /// while let Some(packet) = voice.next().await {
405    ///     if let VoiceData::Opus(opus) = packet.audio {
406    ///         bytes += opus.len();
407    ///     }
408    /// }
409    /// println!("{bytes} bytes of Opus received");
410    /// # Ok(())
411    /// # }
412    /// ```
413    #[must_use]
414    pub fn subscribe(&self, user_id: UserId) -> VoiceStream {
415        self.subscribe_with(user_id, ReceiveOptions::new())
416    }
417
418    /// Receives the audio of the user `user_id` with `options` (D-367, D-372): decoded to
419    /// PCM or not, ended by itself or not. Otherwise as [`subscribe`](Self::subscribe).
420    ///
421    /// discord.js counterpart: `VoiceReceiver#subscribe` with its options.
422    ///
423    /// # Examples
424    ///
425    /// ```no_run
426    /// # async fn example(call: djs_voice::Call, user_id: djs_model::id::UserId) {
427    /// use std::time::Duration;
428    ///
429    /// use djs_voice::{EndBehavior, ReceiveOptions, VoiceData};
430    ///
431    /// // One utterance, decoded: it ends after a second of silence.
432    /// let options = ReceiveOptions::new()
433    ///     .decode(true)
434    ///     .end(EndBehavior::AfterSilence(Duration::from_secs(1)));
435    /// let mut voice = call.subscribe_with(user_id, options);
436    /// let mut samples: Vec<i16> = Vec::new();
437    /// while let Some(packet) = voice.next().await {
438    ///     if let VoiceData::Pcm(pcm) = packet.audio {
439    ///         samples.extend(pcm);
440    ///     }
441    /// }
442    /// println!("{} s of audio", samples.len() / 2 / 48_000);
443    /// # }
444    /// ```
445    #[must_use]
446    pub fn subscribe_with(&self, user_id: UserId, options: ReceiveOptions) -> VoiceStream {
447        let (tx, rx) = mpsc::channel(receive::QUEUE);
448        // A call that has ended drops `tx`: the stream ends at once.
449        self.command(CallCommand::Subscribe {
450            user_id,
451            options,
452            tx,
453        });
454        VoiceStream::new(rx, options)
455    }
456
457    /// Returns a stream of the call's events: connections resumed and made again, users
458    /// joining, leaving and speaking, and the end of the call. Each stream gets every event
459    /// from its creation on, and ends with the call.
460    ///
461    /// discord.js counterpart: `VoiceConnection#on('stateChange')`; songbird:
462    /// `Call::add_global_event`.
463    #[must_use]
464    pub fn events(&self) -> CallEvents {
465        let (tx, rx) = mpsc::unbounded_channel();
466        let mut subscribers = lock(&self.inner.subscribers);
467        if !subscribers.closed {
468            subscribers.senders.push(tx);
469        }
470        CallEvents { rx }
471    }
472
473    /// Leaves the voice channel: sends Opcode 4 without a channel, closes the connection
474    /// and ends the call ([`DisconnectReason::Left`]); returns once it has ended.
475    ///
476    /// discord.js counterpart: `VoiceConnection#destroy`; songbird: `Call::leave`.
477    ///
478    /// # Errors
479    ///
480    /// When the [`VoiceGateway`] could not send Opcode 4: the call still ends, but Discord
481    /// may show the bot in the channel until its gateway session ends.
482    pub async fn leave(&self) -> Result<(), Box<dyn Error + Send + Sync>> {
483        let command = UpdateVoiceState::new(self.inner.guild_id, None, false, false);
484        let sent = self.inner.gateway.send(self.inner.shard_id, &command);
485        let (done, ended) = oneshot::channel();
486        if self.command(CallCommand::Leave { done }) {
487            // An error only means the call already ended.
488            let _ = ended.await;
489        }
490        sent
491    }
492}
493
494/// An event of a [`Call`], from [`Call::events`] (D-321, D-337).
495///
496/// discord.js counterpart: the state changes of `VoiceConnection` and the events of its
497/// receiver's `SpeakingMap`.
498#[derive(Clone, Debug)]
499#[non_exhaustive]
500pub enum CallEvent {
501    /// The connection was lost and resumed: nothing was missed.
502    Resumed,
503    /// The connection was made again: after a lost session, or to the voice server of a
504    /// channel a moderator moved the bot to. Audio goes on.
505    Reconnected,
506    /// The call ended, for this reason; the stream ends after it.
507    Disconnected(DisconnectReason),
508    /// A user joined the voice channel (or was in it when the bot joined).
509    UserJoined(UserId),
510    /// A user left the voice channel.
511    UserLeft(UserId),
512    /// A user started speaking with this SSRC: the RTP source of their audio.
513    #[non_exhaustive]
514    Speaking {
515        /// The user.
516        user_id: UserId,
517        /// Their audio's synchronization source.
518        ssrc: u32,
519    },
520    /// A user's audio started coming (D-369): their first packet after none for 100 ms.
521    /// Discord sends none to a deafened bot (see [`Call::subscribe`]).
522    ///
523    /// discord.js counterpart: the `start` event of `VoiceReceiver#speaking`.
524    SpeakingStarted(UserId),
525    /// 100 ms have passed since a user's last packet (D-369).
526    ///
527    /// discord.js counterpart: the `end` event of `VoiceReceiver#speaking`.
528    SpeakingStopped(UserId),
529}
530
531/// Why a call ended (D-344), in [`CallEvent::Disconnected`].
532///
533/// discord.js counterpart: `VoiceConnectionDisconnectReason` of `@discordjs/voice`.
534#[derive(Clone, Debug)]
535#[non_exhaustive]
536pub enum DisconnectReason {
537    /// The bot left with [`Call::leave`].
538    Left,
539    /// The voice gateway closed the connection with a code after which resuming cannot
540    /// help: 4014 when the bot was disconnected from the channel (kicked, the channel
541    /// deleted), 4022 when the call was terminated, …
542    #[non_exhaustive]
543    Closed {
544        /// The close code; Discord lists them at
545        /// <https://discord.com/developers/docs/topics/opcodes-and-status-codes#voice-voice-close-event-codes>.
546        code: u16,
547    },
548    /// Every attempt to resume or connect again failed (D-331); the last failure is the
549    /// [`source`](Error::source).
550    Lost(Arc<dyn Error + Send + Sync>),
551}
552
553impl fmt::Display for DisconnectReason {
554    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
555        match self {
556            Self::Left => f.write_str("the bot left the call"),
557            Self::Closed { code } => {
558                write!(f, "the voice gateway closed the call with code {code}")
559            }
560            Self::Lost(_) => f.write_str("the voice connection was lost"),
561        }
562    }
563}
564
565impl Error for DisconnectReason {
566    fn source(&self) -> Option<&(dyn Error + 'static)> {
567        match self {
568            Self::Lost(error) => Some(&**error),
569            Self::Left | Self::Closed { .. } => None,
570        }
571    }
572}
573
574/// The stream of a [`Call`]'s events. Created by [`Call::events`].
575///
576/// Implements [`Stream`]; [`next`](Self::next) is provided so no extension trait is needed.
577///
578/// discord.js counterpart: `VoiceConnection#on` (`@discordjs/voice`).
579#[derive(Debug)]
580pub struct CallEvents {
581    rx: mpsc::UnboundedReceiver<CallEvent>,
582}
583
584impl CallEvents {
585    /// Waits for the next event. Returns `None` once the call has ended (after
586    /// [`CallEvent::Disconnected`]).
587    ///
588    /// discord.js counterpart: `VoiceConnection#on` (`@discordjs/voice`).
589    pub async fn next(&mut self) -> Option<CallEvent> {
590        self.rx.recv().await
591    }
592}
593
594impl Stream for CallEvents {
595    type Item = CallEvent;
596
597    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<CallEvent>> {
598        self.rx.poll_recv(cx)
599    }
600}
601
602/// The voice state the main gateway reported for the bot in this guild.
603#[derive(Default)]
604struct VoiceState {
605    session_id: Option<String>,
606    channel_id: Option<ChannelId>,
607    /// The token and the endpoint of the voice server.
608    server: Option<(String, String)>,
609}
610
611/// A connected voice connection.
612struct Live {
613    channel_id: ChannelId,
614    handle: Handle,
615    sender: Sender,
616    receiver: Receiver,
617    events: mpsc::UnboundedReceiver<ConnectionEvent>,
618}
619
620type Connected = (Handle, Sender, mpsc::UnboundedReceiver<ConnectionEvent>);
621
622/// A voice connection being made.
623struct Connecting {
624    channel_id: ChannelId,
625    task: JoinHandle<Result<Connected, ConnectError>>,
626}
627
628/// A join waiting for the voice state of its channel.
629struct PendingJoin {
630    channel_id: ChannelId,
631    waiters: Vec<oneshot::Sender<Result<(), JoinError>>>,
632    deadline: Instant,
633    /// The `VOICE_STATE_UPDATE` of the channel arrived.
634    state: bool,
635    /// A `VOICE_SERVER_UPDATE` arrived.
636    server: bool,
637}
638
639/// What woke the task.
640enum Step {
641    Command(Option<CallCommand>),
642    Connection(Option<ConnectionEvent>),
643    Connected(ChannelId, Result<Connected, ConnectError>),
644    JoinTimeout,
645    GraceOver,
646    Chunk(Option<Result<Chunk, InputError>>),
647    Frame,
648    /// An RTP packet of others' audio.
649    Packet(Rtp),
650    /// Something of [`Receiving`] is due.
651    Receive,
652}
653
654/// How the call ends: the event reported (none for a call that never connected), and what
655/// a join still waiting gets.
656struct Ending {
657    reason: Option<DisconnectReason>,
658    join: JoinError,
659}
660
661impl Ending {
662    const fn new(reason: Option<DisconnectReason>, join: JoinError) -> Self {
663        Self { reason, join }
664    }
665}
666
667/// A call's task.
668struct Task {
669    call_id: u64,
670    guild_id: GuildId,
671    user_id: UserId,
672    config: Config,
673    calls: Weak<Calls>,
674    subscribers: Arc<Mutex<Subscribers>>,
675    channel: watch::Sender<Option<ChannelId>>,
676    commands: mpsc::UnboundedReceiver<CallCommand>,
677    voice: VoiceState,
678    /// A `VOICE_SERVER_UPDATE` arrived outside a join: connect to it.
679    fresh_server: bool,
680    live: Option<Live>,
681    connecting: Option<Connecting>,
682    join: Option<PendingJoin>,
683    /// After a close with [`DISCONNECTED`]: until when a move may still come.
684    grace: Option<Instant>,
685    /// The bot's voice state has no channel: it was disconnected.
686    removed: bool,
687    connected_once: bool,
688    /// The [`Call::leave`] waiting for the end.
689    leave: Option<oneshot::Sender<()>>,
690    player: Player,
691    receiving: Receiving,
692}
693
694impl Task {
695    async fn run(mut self) {
696        loop {
697            let join_deadline = self
698                .join
699                .as_ref()
700                .filter(|_| self.connecting.is_none())
701                .map(|join| join.deadline);
702            // A connection being made has its own timeout.
703            let grace = self.grace.filter(|_| self.connecting.is_none());
704            let due = self.player.due();
705            let wants_chunk = self.player.wants_chunk();
706            let receive = self.receiving.deadline();
707            let step = tokio::select! {
708                command = self.commands.recv() => Step::Command(command),
709                step = live_step(&mut self.live) => step,
710                (channel_id, result) = connected(&mut self.connecting) => {
711                    Step::Connected(channel_id, result)
712                }
713                () = wait(join_deadline) => Step::JoinTimeout,
714                () = wait(grace) => Step::GraceOver,
715                chunk = self.player.recv(), if wants_chunk => Step::Chunk(chunk),
716                () = wait(due) => Step::Frame,
717                () = wait(receive) => Step::Receive,
718            };
719            if let Err(ending) = self.step(step).await {
720                self.end(ending);
721                return;
722            }
723        }
724    }
725
726    async fn step(&mut self, step: Step) -> Result<(), Ending> {
727        match step {
728            Step::Command(None) => {
729                // Every handle and the manager are gone.
730                Err(Ending::new(None, JoinError::Cancelled))
731            }
732            Step::Command(Some(command)) => self.command(command),
733            Step::Connection(event) => self.connection_event(event),
734            Step::Connected(channel_id, result) => self.connected(channel_id, result),
735            Step::JoinTimeout => {
736                let join = self.join.take();
737                if let Err(ending) = self.idle(|| JoinError::Timeout) {
738                    // `end` answers it, once the call is out of the manager.
739                    self.join = join;
740                    return Err(ending);
741                }
742                if let Some(join) = join {
743                    answer(join.waiters, || Err(JoinError::Timeout));
744                }
745                Ok(())
746            }
747            Step::GraceOver => Err(Ending::new(
748                Some(DisconnectReason::Closed { code: DISCONNECTED }),
749                JoinError::Cancelled,
750            )),
751            Step::Chunk(chunk) => {
752                self.player.received(chunk);
753                Ok(())
754            }
755            Step::Frame => {
756                self.player.frame(self.live.as_mut()).await;
757                Ok(())
758            }
759            Step::Packet(rtp) => {
760                self.packet(rtp);
761                Ok(())
762            }
763            Step::Receive => {
764                for user_id in self.receiving.tick(Instant::now()) {
765                    self.emit(&CallEvent::SpeakingStopped(user_id));
766                }
767                Ok(())
768            }
769        }
770    }
771
772    /// An RTP packet of someone's audio came: they speak; it is opened for those who
773    /// receive them.
774    fn packet(&mut self, rtp: Rtp) {
775        let now = Instant::now();
776        let Some(arrival) = self.receiving.arrived(rtp, now) else {
777            return;
778        };
779        if arrival.started {
780            self.emit(&CallEvent::SpeakingStarted(arrival.user_id));
781        }
782        if arrival.wanted
783            && let Some(live) = &mut self.live
784            && let Some(opus) = live.receiver.open(arrival.user_id.get())
785        {
786            self.receiving.opened(arrival.user_id, rtp, opus, now);
787        }
788    }
789
790    fn command(&mut self, command: CallCommand) -> Result<(), Ending> {
791        match command {
792            CallCommand::Join {
793                channel_id,
794                bitrate,
795                done,
796            } => {
797                self.player.set_bitrate(bitrate);
798                self.start_join(channel_id, done);
799            }
800            CallCommand::Abandoned => {
801                if let Some(join) = &mut self.join {
802                    join.waiters.retain(|waiter| !waiter.is_closed());
803                    if join.waiters.is_empty() {
804                        self.join = None;
805                    }
806                }
807                return self.idle(|| JoinError::Cancelled);
808            }
809            CallCommand::State {
810                session_id,
811                channel_id,
812            } => {
813                self.voice.session_id = Some(session_id);
814                self.voice.channel_id = channel_id;
815                if let Some(channel_id) = channel_id {
816                    self.removed = false;
817                    if let Some(join) = &mut self.join
818                        && join.channel_id == channel_id
819                    {
820                        join.state = true;
821                    }
822                    self.connect();
823                } else if self.join.is_none() {
824                    // Disconnected from the channel (kicked, the channel deleted): the voice
825                    // gateway closes with 4014, or already did.
826                    self.removed = true;
827                    if self.grace.is_some() {
828                        return Err(Ending::new(
829                            Some(DisconnectReason::Closed { code: DISCONNECTED }),
830                            JoinError::Cancelled,
831                        ));
832                    }
833                }
834            }
835            CallCommand::Server { token, endpoint } => match endpoint {
836                // The voice server is being reallocated: the next update says where.
837                None => self.voice.server = None,
838                Some(endpoint) => {
839                    self.voice.server = Some((token, endpoint));
840                    match &mut self.join {
841                        Some(join) => join.server = true,
842                        None => self.fresh_server = true,
843                    }
844                    self.connect();
845                }
846            },
847            CallCommand::Wake => self.player.reconcile(),
848            CallCommand::Seek { id, samples, done } => self.player.seek(id, samples, done),
849            CallCommand::Leave { done } => {
850                self.leave = Some(done);
851                return Err(Ending::new(
852                    Some(DisconnectReason::Left),
853                    JoinError::Cancelled,
854                ));
855            }
856            CallCommand::Subscribe {
857                user_id,
858                options,
859                tx,
860            } => self.receiving.subscribe(user_id, options, tx),
861        }
862        Ok(())
863    }
864
865    fn start_join(&mut self, channel_id: ChannelId, done: oneshot::Sender<Result<(), JoinError>>) {
866        let already_there = self
867            .live
868            .as_ref()
869            .is_some_and(|live| live.channel_id == channel_id);
870        if already_there && self.connecting.is_none() && self.join.is_none() {
871            let _ = done.send(Ok(()));
872            return;
873        }
874        match &mut self.join {
875            Some(join) if join.channel_id == channel_id => join.waiters.push(done),
876            _ => {
877                if let Some(join) = self.join.take() {
878                    answer(join.waiters, || Err(JoinError::Cancelled));
879                }
880                if let Some(connecting) = self.connecting.take() {
881                    connecting.task.abort();
882                }
883                self.join = Some(PendingJoin {
884                    channel_id,
885                    waiters: vec![done],
886                    deadline: Instant::now() + self.config.timeout,
887                    state: false,
888                    server: false,
889                });
890            }
891        }
892    }
893
894    /// Connects to the voice server reported, when the voice state is complete: for a join,
895    /// once both updates of its channel arrived; otherwise on each new voice server.
896    fn connect(&mut self) {
897        let VoiceState {
898            session_id: Some(session_id),
899            channel_id: Some(channel_id),
900            server: Some((token, endpoint)),
901        } = &self.voice
902        else {
903            return;
904        };
905        let channel_id = *channel_id;
906        let timeout = match &self.join {
907            Some(join) if join.channel_id == channel_id && join.state && join.server => {
908                join.deadline.saturating_duration_since(Instant::now())
909            }
910            Some(_) => return,
911            None => {
912                if !core::mem::take(&mut self.fresh_server) {
913                    return;
914                }
915                self.config.timeout
916            }
917        };
918        let info = Info {
919            guild_id: self.guild_id,
920            channel_id,
921            user_id: self.user_id,
922            session_id: session_id.clone(),
923            endpoint: endpoint.clone(),
924            token: token.clone(),
925        };
926        let config = Config {
927            timeout,
928            ..self.config.clone()
929        };
930        if let Some(old) = self.connecting.take() {
931            old.task.abort();
932        }
933        self.connecting = Some(Connecting {
934            channel_id,
935            task: tokio::spawn(connection::connect(info, config)),
936        });
937    }
938
939    fn connected(
940        &mut self,
941        channel_id: ChannelId,
942        result: Result<Connected, ConnectError>,
943    ) -> Result<(), Ending> {
944        match result {
945            Ok((handle, sender, events)) => {
946                if let Some(old) = self.live.take() {
947                    // Its end is not this call's.
948                    old.handle.send(Command::Close);
949                }
950                // Other users, other sources.
951                for user_id in self.receiving.reset() {
952                    self.emit(&CallEvent::SpeakingStopped(user_id));
953                }
954                let receiver = sender.receiver();
955                self.live = Some(Live {
956                    channel_id,
957                    handle,
958                    sender,
959                    receiver,
960                    events,
961                });
962                self.channel.send_replace(Some(channel_id));
963                self.grace = None;
964                // A new connection has no speaking state yet.
965                self.player.speaking = false;
966                match self.join.take() {
967                    Some(join) => answer(join.waiters, || Ok(())),
968                    None if self.connected_once => self.emit(&CallEvent::Reconnected),
969                    None => {}
970                }
971                self.connected_once = true;
972                Ok(())
973            }
974            Err(error) => {
975                let error = Arc::new(error);
976                let join_error = {
977                    let error = Arc::clone(&error);
978                    move || match &*error {
979                        ConnectError::Timeout => JoinError::Timeout,
980                        _ => JoinError::Connection(Box::new(Arc::clone(&error))),
981                    }
982                };
983                // A move that failed ends the call, unless the old connection is still there.
984                self.grace = None;
985                if self.live.is_some() {
986                    if let Some(join) = self.join.take() {
987                        answer(join.waiters, || Err(join_error()));
988                    }
989                    tracing::warn!(guild = %self.guild_id, %error, "connecting the call again failed");
990                    return Ok(());
991                }
992                // `end` answers a join, once the call is out of the manager.
993                let reason = self
994                    .connected_once
995                    .then(|| DisconnectReason::Lost(error as Arc<dyn Error + Send + Sync>));
996                Err(Ending::new(reason, join_error()))
997            }
998        }
999    }
1000
1001    fn connection_event(&mut self, event: Option<ConnectionEvent>) -> Result<(), Ending> {
1002        let end = match event {
1003            Some(ConnectionEvent::Gateway(event)) => {
1004                match event {
1005                    Event::ClientsConnect(users) => {
1006                        for user in users {
1007                            self.emit(&CallEvent::UserJoined(user));
1008                        }
1009                    }
1010                    Event::ClientDisconnect(user) => {
1011                        self.receiving.left(user);
1012                        self.emit(&CallEvent::UserLeft(user));
1013                    }
1014                    Event::Speaking(speaking) => {
1015                        self.receiving
1016                            .map(speaking.user_id, speaking.ssrc, Instant::now());
1017                        self.emit(&CallEvent::Speaking {
1018                            user_id: speaking.user_id,
1019                            ssrc: speaking.ssrc,
1020                        });
1021                    }
1022                    _ => {}
1023                }
1024                return Ok(());
1025            }
1026            Some(ConnectionEvent::Resumed) => {
1027                self.emit(&CallEvent::Resumed);
1028                return Ok(());
1029            }
1030            Some(ConnectionEvent::Reconnected) => {
1031                self.emit(&CallEvent::Reconnected);
1032                return Ok(());
1033            }
1034            Some(ConnectionEvent::Ended(end)) => end,
1035            None => End::Lost(ConnectError::Closed(None)),
1036        };
1037        self.live = None;
1038        self.channel.send_replace(None);
1039        if self.join.is_some() || self.connecting.is_some() {
1040            // A move is under way: the new connection takes over.
1041            return Ok(());
1042        }
1043        match end {
1044            End::Stopped(DISCONNECTED) if !self.removed => {
1045                // Moved to another channel, maybe: its voice server would follow.
1046                self.grace = Some(Instant::now() + MOVE_GRACE);
1047                Ok(())
1048            }
1049            End::Stopped(code) => Err(Ending::new(
1050                Some(DisconnectReason::Closed { code }),
1051                JoinError::Cancelled,
1052            )),
1053            End::Lost(error) => Err(Ending::new(
1054                Some(DisconnectReason::Lost(Arc::new(error))),
1055                JoinError::Cancelled,
1056            )),
1057            End::Closed => Err(Ending::new(None, JoinError::Cancelled)),
1058        }
1059    }
1060
1061    /// Ends a call left with nothing to do: no connection, none being made, no join.
1062    fn idle(&self, join: impl FnOnce() -> JoinError) -> Result<(), Ending> {
1063        if self.live.is_none()
1064            && self.connecting.is_none()
1065            && self.join.is_none()
1066            && self.grace.is_none()
1067        {
1068            let reason = self.connected_once.then(|| {
1069                DisconnectReason::Lost(
1070                    Arc::new(ConnectError::Timeout) as Arc<dyn Error + Send + Sync>
1071                )
1072            });
1073            return Err(Ending::new(reason, join()));
1074        }
1075        Ok(())
1076    }
1077
1078    fn emit(&self, event: &CallEvent) {
1079        lock(&self.subscribers)
1080            .senders
1081            .retain(|subscriber| subscriber.send(event.clone()).is_ok());
1082    }
1083
1084    /// Ends the call: out of the manager first (a new join makes a new call), then the
1085    /// connection closed, the event reported, the waiters answered.
1086    fn end(mut self, ending: Ending) {
1087        if let Some(calls) = self.calls.upgrade() {
1088            let mut calls = lock(&calls);
1089            if calls
1090                .get(&self.guild_id)
1091                .is_some_and(|call| call.inner.id == self.call_id)
1092            {
1093                calls.remove(&self.guild_id);
1094            }
1095        }
1096        if let Some(connecting) = self.connecting.take() {
1097            connecting.task.abort();
1098        }
1099        if let Some(live) = self.live.take() {
1100            live.handle.send(Command::Close);
1101        }
1102        lock(&self.player.shared.queue).close();
1103        self.player.end();
1104        self.channel.send_replace(None);
1105        {
1106            let mut subscribers = lock(&self.subscribers);
1107            if let Some(reason) = ending.reason {
1108                let event = CallEvent::Disconnected(reason);
1109                for subscriber in &subscribers.senders {
1110                    let _ = subscriber.send(event.clone());
1111                }
1112            }
1113            subscribers.senders.clear();
1114            subscribers.closed = true;
1115        }
1116        if let Some(join) = self.join.take() {
1117            let mut join_error = Some(ending.join);
1118            answer(join.waiters, || {
1119                Err(join_error.take().unwrap_or(JoinError::Cancelled))
1120            });
1121        }
1122        if let Some(leave) = self.leave.take() {
1123            let _ = leave.send(());
1124        }
1125    }
1126}
1127
1128/// Answers the waiters of a join.
1129fn answer<T>(waiters: Vec<oneshot::Sender<T>>, mut result: impl FnMut() -> T) {
1130    for waiter in waiters {
1131        let _ = waiter.send(result());
1132    }
1133}
1134
1135/// What the connection gives next: one of its events, or a packet of others' audio.
1136async fn live_step(live: &mut Option<Live>) -> Step {
1137    let Some(live) = live else {
1138        return core::future::pending().await;
1139    };
1140    // Both are cancel-safe.
1141    tokio::select! {
1142        event = live.events.recv() => Step::Connection(event),
1143        rtp = live.receiver.recv() => Step::Packet(rtp),
1144    }
1145}
1146
1147async fn connected(
1148    connecting: &mut Option<Connecting>,
1149) -> (ChannelId, Result<Connected, ConnectError>) {
1150    let Some(pending) = connecting else {
1151        return core::future::pending().await;
1152    };
1153    let result = (&mut pending.task)
1154        .await
1155        .unwrap_or(Err(ConnectError::Unexpected("the connection task failed")));
1156    let channel_id = pending.channel_id;
1157    *connecting = None;
1158    (channel_id, result)
1159}
1160
1161/// Waits until `deadline`, or forever without one.
1162async fn wait(deadline: Option<Instant>) {
1163    match deadline {
1164        Some(deadline) => sleep_until(deadline).await,
1165        None => core::future::pending().await,
1166    }
1167}
1168
1169/// Reads `source` from `start` in a task of its own, about a second ahead.
1170fn spawn_reader(
1171    source: Source,
1172    start: u64,
1173) -> (mpsc::Receiver<Result<Chunk, InputError>>, JoinHandle<()>) {
1174    let (tx, chunks) = mpsc::channel(AHEAD);
1175    (chunks, tokio::spawn(reading::read(source, start, tx)))
1176}
1177
1178/// The track the player plays: its input read ahead, and what the player knows of it.
1179#[expect(
1180    clippy::struct_excessive_bools,
1181    reason = "independent facts about the track, each changed on its own"
1182)]
1183struct Playing {
1184    track: Arc<Track>,
1185    /// How to open its input again, for loops and seeking; `None` for a reader.
1186    again: Option<Again>,
1187    chunks: mpsc::Receiver<Result<Chunk, InputError>>,
1188    reader: JoinHandle<()>,
1189    /// While its Opus packets are re-encoded.
1190    reencode: Option<Reencode>,
1191    /// The input's last Opus packets (those before a seek's position, after one): a new
1192    /// decoder decodes them first.
1193    history: History,
1194    /// The input opened again while the listeners got the encoder's packets: its stream
1195    /// goes on, unprimed (C-127).
1196    continuing: bool,
1197    /// Whether the input's last Opus packet was CELT-only ([`codec::celt_only`]).
1198    celt: bool,
1199    /// Frames read ahead of `Player::next` for the re-encoding's lookahead, then what came
1200    /// after them (an error, the end), returned by `Player::recv` in order.
1201    after: VecDeque<Frame>,
1202    held: Option<Read>,
1203    /// How many frames from `Player::next` on are decoded already (into the `fifo`).
1204    decoded: usize,
1205    /// Paused, as the player last saw it.
1206    paused: bool,
1207    /// [`TrackEvent::Playing`] was sent since its audio last stopped.
1208    announced: bool,
1209    /// Seeks waiting for the first frame from the new place.
1210    seeks: Vec<oneshot::Sender<Result<Duration, TrackError>>>,
1211    /// The gain at the end of the last frame sent: the next one ramps from it (C-127).
1212    gain: f32,
1213    /// The next frame fades out to silence: the track pauses or seeks.
1214    closing: bool,
1215    /// A seek waiting for the frame from before it to fade out: the input is opened again
1216    /// at this position then.
1217    seek_to: Option<u64>,
1218    /// Its input is being opened again (a seek, a loop): frames of silence keep the stream
1219    /// going until its audio comes.
1220    restarting: bool,
1221}
1222
1223impl Playing {
1224    fn new(track: Arc<Track>, source: Source, again: Option<Again>) -> Self {
1225        let (chunks, reader) = spawn_reader(source, track.position());
1226        Self {
1227            gain: track.volume(),
1228            paused: track.paused(),
1229            track,
1230            again,
1231            chunks,
1232            reader,
1233            reencode: None,
1234            history: History::default(),
1235            continuing: false,
1236            celt: false,
1237            after: VecDeque::new(),
1238            held: None,
1239            decoded: 0,
1240            announced: false,
1241            seeks: Vec::new(),
1242            closing: false,
1243            seek_to: None,
1244            restarting: false,
1245        }
1246    }
1247
1248    /// Reads the input again from `start`, opened anew.
1249    fn restart(&mut self, start: u64) {
1250        let Some(again) = &self.again else {
1251            return;
1252        };
1253        self.reader.abort();
1254        (self.chunks, self.reader) = spawn_reader(again.source(), start);
1255        self.continuing = self.reencode.is_some();
1256        self.reencode = None;
1257        self.celt = false;
1258        self.history.clear();
1259        self.after.clear();
1260        self.held = None;
1261        self.decoded = 0;
1262        self.track.set_position(start);
1263        self.restarting = true;
1264    }
1265
1266    /// Reads the next frame ahead, if the reader has one ready, into `after`; whether it
1267    /// did. What is not a frame is kept for `Player::recv`.
1268    fn pull(&mut self) -> bool {
1269        if self.held.is_some() {
1270            return false;
1271        }
1272        match self.chunks.try_recv() {
1273            Ok(Ok(Chunk::Frame(frame))) => {
1274                self.after.push_back(frame);
1275                true
1276            }
1277            Ok(other) => {
1278                self.held = Some(Some(other));
1279                false
1280            }
1281            Err(TryRecvError::Empty) => false,
1282            Err(TryRecvError::Disconnected) => {
1283                self.held = Some(None);
1284                false
1285            }
1286        }
1287    }
1288
1289    fn answer(&mut self, result: &Result<Duration, TrackError>) {
1290        for seek in self.seeks.drain(..) {
1291            let _ = seek.send(*result);
1292        }
1293    }
1294}
1295
1296impl Drop for Playing {
1297    fn drop(&mut self) {
1298        // Its seeks, dropped, see the track ended.
1299        self.reader.abort();
1300    }
1301}
1302
1303/// The player of a call (D-351: one track at a time). It plays the current track of the
1304/// queue, sends each frame at its time, `at`, paced by the frames' durations, and frames of
1305/// silence when audio stops. Opus packets at volume 1.0 go out as they are; the others are
1306/// encoded when due (C-126).
1307struct Player {
1308    shared: Arc<Shared>,
1309    track: Option<Playing>,
1310    /// The next frame, waiting for its time.
1311    next: Option<Frame>,
1312    /// When the next frame (audio or silence) is due.
1313    at: Option<Instant>,
1314    /// Frames of silence still to send.
1315    silence: u8,
1316    /// Opcode 5 Speaking says the bot speaks on the current connection.
1317    speaking: bool,
1318    bitrate: u32,
1319    /// Made when the first frame is encoded.
1320    encoder: Option<Encoder>,
1321    /// Room for the PCM of the longest packet.
1322    pcm: Vec<f32>,
1323    /// Room for an encoded packet.
1324    packet: Vec<u8>,
1325}
1326
1327impl Player {
1328    fn new(shared: Arc<Shared>) -> Self {
1329        Self {
1330            shared,
1331            track: None,
1332            next: None,
1333            at: None,
1334            silence: 0,
1335            speaking: false,
1336            bitrate: codec::DEFAULT_BITRATE,
1337            encoder: None,
1338            pcm: vec![0.0; MAX_PACKET_VALUES],
1339            packet: vec![0; MAX_PACKET],
1340        }
1341    }
1342
1343    fn set_bitrate(&mut self, bitrate: u32) {
1344        self.bitrate = bitrate;
1345        if let Some(encoder) = &mut self.encoder {
1346            encoder.set_bitrate(bitrate);
1347        }
1348    }
1349
1350    /// Plays the queue's current track: starts it if it is new (the one playing ended
1351    /// already: replaced, skipped or stopped), and follows its pause.
1352    fn reconcile(&mut self) {
1353        let mut queue = lock(&self.shared.queue);
1354        let current = queue.current.as_ref().map(|slot| slot.track.id);
1355        if current.is_some() && current == self.track.as_ref().map(|playing| playing.track.id) {
1356            drop(queue);
1357            self.refresh();
1358            return;
1359        }
1360        let started = queue.current.as_mut().and_then(|slot| {
1361            let input = slot.input.take()?;
1362            slot.track.start();
1363            Some((Arc::clone(&slot.track), input))
1364        });
1365        drop(queue);
1366        let had = self.track.take().is_some();
1367        self.next = None;
1368        if let Some((track, input)) = started {
1369            let (source, again) = input.into_parts();
1370            self.track = Some(Playing::new(track, source, again));
1371        } else if had {
1372            self.quiet();
1373        }
1374    }
1375
1376    /// Follows the current track's pause.
1377    fn refresh(&mut self) {
1378        let Some(playing) = &mut self.track else {
1379            return;
1380        };
1381        let paused = playing.track.paused();
1382        if paused == playing.paused {
1383            return;
1384        }
1385        playing.paused = paused;
1386        if !paused {
1387            // Not paused after all, if its last frame has not gone yet (a seek still fades
1388            // it out).
1389            playing.closing = playing.seek_to.is_some();
1390            return;
1391        }
1392        if core::mem::take(&mut playing.announced) {
1393            playing.track.emit(&TrackEvent::Paused);
1394        }
1395        // The next frame (read now if need be) fades out, then silence follows.
1396        playing.closing = true;
1397    }
1398
1399    fn seek(&mut self, id: u64, samples: u64, done: oneshot::Sender<Result<Duration, TrackError>>) {
1400        match &mut self.track {
1401            Some(playing)
1402                if playing.track.id == id && !playing.track.ended() && playing.again.is_some() =>
1403            {
1404                playing.seeks.push(done);
1405                // Nothing audible to fade out: paused, or already opening the input again.
1406                let silent = (playing.paused && !playing.closing)
1407                    || (playing.restarting && self.next.is_none());
1408                if silent {
1409                    playing.restart(samples);
1410                    playing.seek_to = None;
1411                    playing.gain = 0.0;
1412                    self.next = None;
1413                } else {
1414                    // The frame from before fades out, then the input opens again.
1415                    playing.seek_to = Some(samples);
1416                    playing.closing = true;
1417                }
1418            }
1419            _ => {
1420                let _ = done.send(Err(TrackError::Ended));
1421            }
1422        }
1423    }
1424
1425    /// Frames of silence follow, if audio was going out.
1426    fn quiet(&mut self) {
1427        if self.speaking {
1428            self.silence = SILENCE_FRAMES;
1429        }
1430    }
1431
1432    /// The call ends: so does the track (its call already ended it).
1433    fn end(&mut self) {
1434        self.track = None;
1435        self.next = None;
1436    }
1437
1438    fn playing(&self) -> bool {
1439        self.track.as_ref().is_some_and(|playing| !playing.paused)
1440    }
1441
1442    fn wants_chunk(&self) -> bool {
1443        // A seek is answered by the first frame from the new place, even paused, and a
1444        // frame fading out is read even paused.
1445        let reading = self
1446            .track
1447            .as_ref()
1448            .is_some_and(|playing| !playing.seeks.is_empty() || playing.closing);
1449        (self.next.is_none() || self.ahead()) && self.silence == 0 && (self.playing() || reading)
1450    }
1451
1452    /// Whether the Opus frame that is next waits for 20 ms more of the input to be read:
1453    /// re-encoding it takes the start of what follows too (the encoder's lookahead, C-127).
1454    fn ahead(&self) -> bool {
1455        matches!(self.next, Some(Frame::Opus { .. }))
1456            && self.track.as_ref().is_some_and(|playing| {
1457                playing.held.is_none()
1458                    && playing.after.iter().map(Frame::samples).sum::<u32>() < 960
1459            })
1460    }
1461
1462    async fn recv(&mut self) -> Read {
1463        let Some(playing) = &mut self.track else {
1464            return core::future::pending().await;
1465        };
1466        // What was read ahead first, in order.
1467        if let Some(frame) = playing.after.pop_front() {
1468            return Some(Ok(Chunk::Frame(frame)));
1469        }
1470        if let Some(read) = playing.held.take() {
1471            return read;
1472        }
1473        playing.chunks.recv().await
1474    }
1475
1476    fn received(&mut self, chunk: Option<Result<Chunk, InputError>>) {
1477        let Some(playing) = &mut self.track else {
1478            return;
1479        };
1480        match chunk {
1481            // Read ahead of the next frame: kept in order for `recv`.
1482            Some(Ok(Chunk::Frame(frame))) if self.next.is_some() => playing.after.push_back(frame),
1483            chunk if self.next.is_some() => playing.held = Some(chunk),
1484            Some(Ok(Chunk::Preroll(packets))) => playing.history = packets,
1485            Some(Ok(Chunk::Start(at))) => {
1486                playing.track.set_position(at);
1487                playing.answer(&Ok(duration(at)));
1488            }
1489            Some(Ok(Chunk::Frame(frame))) => {
1490                // Not the frame fading out before a seek: one from the new place.
1491                if playing.seek_to.is_none() {
1492                    if !playing.seeks.is_empty() {
1493                        playing.answer(&Ok(duration(playing.track.position())));
1494                    }
1495                    playing.restarting = false;
1496                }
1497                self.next = Some(frame);
1498            }
1499            Some(Err(error)) => self.finished(Some(error)),
1500            None => self.finished(None),
1501        }
1502    }
1503
1504    /// The track's input ended: it plays again if it loops, or ends, and the next one plays.
1505    fn finished(&mut self, error: Option<InputError>) {
1506        let Some(playing) = &mut self.track else {
1507            return;
1508        };
1509        if let Some(samples) = playing.seek_to.take() {
1510            // The old place ended before a frame could fade out: the seek goes on.
1511            playing.closing = false;
1512            playing.restart(samples);
1513            playing.gain = 0.0;
1514            return;
1515        }
1516        if error.is_none()
1517            && playing.again.is_some()
1518            && !playing.track.ended()
1519            && playing.track.repeat()
1520        {
1521            playing.restart(0);
1522            playing.track.emit(&TrackEvent::Looped);
1523            return;
1524        }
1525        let reason = match error {
1526            None => TrackEnd::Finished,
1527            Some(error) => {
1528                tracing::warn!(%error, "a track's input failed");
1529                TrackEnd::Failed(Arc::new(error))
1530            }
1531        };
1532        {
1533            let mut queue = lock(&self.shared.queue);
1534            playing.track.end(reason);
1535            if queue
1536                .current
1537                .as_ref()
1538                .is_some_and(|slot| slot.track.id == playing.track.id)
1539            {
1540                queue.advance();
1541            }
1542        }
1543        // The next track, or silence.
1544        self.reconcile();
1545    }
1546
1547    /// Whether a frame of silence fills in while the track's input is opened again.
1548    fn filling(&self) -> bool {
1549        self.speaking
1550            && self.next.is_none()
1551            && self
1552                .track
1553                .as_ref()
1554                .is_some_and(|playing| playing.restarting && !playing.paused)
1555    }
1556
1557    /// When the next frame is due: now for the first after a pause.
1558    fn due(&self) -> Option<Instant> {
1559        let closing = self.track.as_ref().is_some_and(|playing| playing.closing);
1560        let ready = self.silence > 0
1561            || (self.next.is_some() && !self.ahead() && (self.playing() || closing))
1562            || self.filling();
1563        ready.then(|| self.at.unwrap_or_else(Instant::now))
1564    }
1565
1566    /// Sends the frame that is due, if the call has a connection.
1567    async fn frame(&mut self, live: Option<&mut Live>) {
1568        let now = Instant::now();
1569        let at = match self.at {
1570            Some(at) if at + LATE >= now => at,
1571            // A first frame, or one far too late: the pace starts over.
1572            _ => now,
1573        };
1574        // Silence filling in while the input opens again keeps the bot speaking.
1575        let mut filler = false;
1576        let frame = if self.silence > 0 {
1577            self.silence -= 1;
1578            None
1579        } else if let Some(frame) = self.next.take() {
1580            Some(frame)
1581        } else if self.filling() {
1582            filler = true;
1583            None
1584        } else {
1585            return;
1586        };
1587        let samples = frame.as_ref().map_or(960, Frame::samples);
1588        self.at = (frame.is_some() || filler || self.silence > 0)
1589            .then(|| at + duration(u64::from(samples)));
1590        // The gain the frame ramps from and to, and where the input opens again after it.
1591        let mut gains = (1.0, 1.0);
1592        let mut restart = None;
1593        if frame.is_some() {
1594            let Some(playing) = &mut self.track else {
1595                return;
1596            };
1597            if playing.track.ended() {
1598                // Read before the track was stopped or replaced.
1599                return;
1600            }
1601            let to = if playing.closing {
1602                0.0
1603            } else {
1604                playing.track.volume()
1605            };
1606            gains = (playing.gain, to);
1607            playing.gain = to;
1608            playing.track.advance(samples);
1609            let closing = core::mem::take(&mut playing.closing);
1610            // Once it has faded out, the input opens again at the new place.
1611            restart = playing.seek_to.take().filter(|_| closing);
1612            let pausing = closing && playing.paused;
1613            if !pausing && !core::mem::replace(&mut playing.announced, true) {
1614                playing.track.emit(&TrackEvent::Playing);
1615            }
1616            if pausing {
1617                // Its last frame fades out; silence follows.
1618                self.quiet();
1619            }
1620        }
1621        self.send(live, frame.as_ref(), gains, filler, samples)
1622            .await;
1623        if let Some(playing) = &mut self.track {
1624            if let Some(Frame::Opus { data, samples }) = frame {
1625                playing.history.push(data, samples);
1626            }
1627            if let Some(samples) = restart {
1628                playing.restart(samples);
1629            }
1630        }
1631    }
1632
1633    /// Sends `frame` (silence when `None`: a filler, or the frames after audio), if the call
1634    /// has a connection.
1635    async fn send(
1636        &mut self,
1637        live: Option<&mut Live>,
1638        frame: Option<&Frame>,
1639        gains: (f32, f32),
1640        filler: bool,
1641        samples: u32,
1642    ) {
1643        let Some(live) = live else {
1644            if self.silence == 0 && frame.is_none() {
1645                self.speaking = false;
1646            }
1647            if let Some(encoder) = &mut self.encoder {
1648                // Nobody decodes this one: the next starts independently.
1649                encoder.independent_next();
1650            }
1651            return;
1652        };
1653        // The packet, and whether the encoder made it.
1654        let (payload, encoded) = match frame {
1655            Some(frame) => {
1656                if !self.speaking {
1657                    live.handle.send(Command::Speaking(MICROPHONE));
1658                    self.speaking = true;
1659                }
1660                match (self.encode(frame, gains), frame) {
1661                    (Some(len), _) => (&self.packet[..len], true),
1662                    (None, Frame::Opus { data, .. }) => (&data[..], false),
1663                    // PCM that could not be encoded: nothing to send.
1664                    (None, Frame::Pcm(_)) => return,
1665                }
1666            }
1667            // While the input opens again: silence from the encoder, so that the listeners'
1668            // decoders stay in its stereo stream (Discord's silence frame is mono).
1669            None if filler => match self.silence_packet() {
1670                Some(len) => (&self.packet[..len], true),
1671                None => (&SILENCE[..], false),
1672            },
1673            None => (&SILENCE[..], false),
1674        };
1675        if let Err(error) = live.sender.send(payload, samples).await {
1676            tracing::debug!(%error, "a voice packet could not be sent");
1677        }
1678        if !encoded && let Some(encoder) = &mut self.encoder {
1679            // The listeners' decoders now hold what the encoder did not make (C-127).
1680            encoder.independent_next();
1681        }
1682        if frame.is_none() && !filler && self.silence == 0 {
1683            live.handle.send(Command::Speaking(0));
1684            self.speaking = false;
1685        }
1686    }
1687
1688    /// A 20 ms packet of silence from the encoder, in `packet`; its length.
1689    fn silence_packet(&mut self) -> Option<usize> {
1690        let encoder = match &mut self.encoder {
1691            Some(encoder) => encoder,
1692            None => self.encoder.insert(Encoder::new(self.bitrate)?),
1693        };
1694        let pcm = &mut self.pcm[..codec::FRAME_VALUES];
1695        pcm.fill(0.0);
1696        encoder.encode(pcm, 1.0, 1.0, &mut self.packet)
1697    }
1698
1699    /// Encodes `frame` into `packet`, its gain ramping from `gains.0` to `gains.1`; its
1700    /// length, or `None` for an Opus packet sent as it is (at 1.0 throughout once
1701    /// re-encoding has settled, or one libopus cannot re-encode).
1702    fn encode(&mut self, frame: &Frame, (from, to): (f32, f32)) -> Option<usize> {
1703        let encoder = match &mut self.encoder {
1704            Some(encoder) => encoder,
1705            None => self.encoder.insert(Encoder::new(self.bitrate)?),
1706        };
1707        let playing = self.track.as_mut()?;
1708        let (data, samples) = match frame {
1709            Frame::Pcm(bytes) => {
1710                let pcm = &mut self.pcm[..codec::FRAME_VALUES];
1711                codec::from_s16le(bytes, pcm);
1712                return encoder.encode(pcm, from, to, &mut self.packet);
1713            }
1714            Frame::Opus { data, samples } => (data, usize::try_from(*samples).ok()?),
1715        };
1716        let unity = (from - 1.0).abs() <= f32::EPSILON && (to - 1.0).abs() <= f32::EPSILON;
1717        let celt = codec::celt_only(data);
1718        let celt_before = core::mem::replace(&mut playing.celt, celt);
1719        let as_they_are = match &playing.reencode {
1720            // Not right after the input opened again under the encoder's packets.
1721            None => !playing.continuing,
1722            // Back to the packets as they are once the listeners' decoders hold the same
1723            // audio, and only between CELT-only ones: after the encoder's (CELT) packets,
1724            // a SILK or hybrid one is decoded from a reset SILK state, far too quiet.
1725            Some(reencode) => reencode.steady >= SETTLE && celt && celt_before,
1726        };
1727        if unity && as_they_are {
1728            playing.reencode = None;
1729            playing.decoded = 0;
1730            return None;
1731        }
1732        let lookahead = encoder.lookahead();
1733        if playing.reencode.is_none() {
1734            let mut decoder = Decoder::new()?;
1735            let mut fifo = VecDeque::with_capacity(MAX_PACKET_VALUES * 2);
1736            // The encoder first takes the 20 ms before this frame shifted by its lookahead:
1737            // the end of the packet before (silence if there is none), then the start of
1738            // this one. Its next output is then this frame, in step with the packets.
1739            let before = 960 - lookahead;
1740            // The input's packets before this one bring the decoder where the listeners'
1741            // decoders are: from one packet alone, CELT and SILK come out far too quiet, and
1742            // the encoder would start from the wrong state.
1743            let mut previous = 0;
1744            for packet in playing.history.packets() {
1745                previous = decoder.decode(packet, &mut self.pcm).unwrap_or(0);
1746            }
1747            let continuing = core::mem::take(&mut playing.continuing);
1748            if !continuing {
1749                let kept = previous.min(before);
1750                fifo.extend(core::iter::repeat_n(0.0, (before - kept) * 2));
1751                fifo.extend(&self.pcm[(previous - kept) * 2..previous * 2]);
1752            }
1753            let current = decoder.decode(data, &mut self.pcm)?;
1754            fifo.extend(&self.pcm[..current * 2]);
1755            playing.decoded = 1;
1756            let mut reencode = Reencode {
1757                decoder,
1758                fifo,
1759                steady: 0,
1760            };
1761            if continuing {
1762                // The encoder's stream goes on: the listeners decoded its packets. The new
1763                // place starts its lookahead in, so that it stays in step.
1764                fill(playing, &mut reencode, &mut self.pcm, lookahead * 2);
1765                reencode.fifo.drain(..lookahead * 2);
1766            } else {
1767                fill(playing, &mut reencode, &mut self.pcm, codec::FRAME_VALUES);
1768                // At the gain this frame starts at, as the listeners heard it: the packets
1769                // as they are (1.0), or nothing (0.0).
1770                let mut prime: Vec<f32> = reencode
1771                    .fifo
1772                    .drain(..codec::FRAME_VALUES)
1773                    .map(|value| value * from)
1774                    .collect();
1775                let _ = encoder.encode(&mut prime, 1.0, 1.0, &mut self.packet);
1776                // The listeners did not decode that one: the next starts independently.
1777                encoder.independent_next();
1778            }
1779            playing.reencode = Some(reencode);
1780        } else if playing.decoded == 0 {
1781            let reencode = playing.reencode.as_mut()?;
1782            let decoded = reencode.decoder.decode(data, &mut self.pcm)?;
1783            reencode.fifo.extend(&self.pcm[..decoded * 2]);
1784            playing.decoded = 1;
1785        }
1786        let mut reencode = playing.reencode.take()?;
1787        reencode.steady = if unity {
1788            reencode.steady.saturating_add(1)
1789        } else {
1790            0
1791        };
1792        let values = samples * 2;
1793        fill(playing, &mut reencode, &mut self.pcm, values);
1794        for (out, value) in self.pcm[..values]
1795            .iter_mut()
1796            .zip(reencode.fifo.drain(..values.min(reencode.fifo.len())))
1797        {
1798            *out = value;
1799        }
1800        playing.decoded = playing.decoded.saturating_sub(1);
1801        playing.reencode = Some(reencode);
1802        encoder.encode(&mut self.pcm[..values], from, to, &mut self.packet)
1803    }
1804}
1805
1806/// Decodes frames read ahead until `reencode.fifo` holds `values` (silence completes it at
1807/// the input's end, or when the reader is behind).
1808fn fill(playing: &mut Playing, reencode: &mut Reencode, pcm: &mut [f32], values: usize) {
1809    while reencode.fifo.len() < values {
1810        // The frames decoded so far: the current one and `decoded - 1` read ahead.
1811        let index = playing.decoded.saturating_sub(1);
1812        if index >= playing.after.len() && !playing.pull() {
1813            break;
1814        }
1815        let Some(Frame::Opus { data, .. }) = playing.after.get(index) else {
1816            break;
1817        };
1818        let Some(decoded) = reencode.decoder.decode(data, pcm) else {
1819            break;
1820        };
1821        reencode.fifo.extend(&pcm[..decoded * 2]);
1822        playing.decoded += 1;
1823    }
1824    let missing = values.saturating_sub(reencode.fifo.len());
1825    reencode.fifo.extend(core::iter::repeat_n(0.0, missing));
1826}