1use 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
53const DISCONNECTED: u16 = 4014;
56const MOVE_GRACE: Duration = Duration::from_secs(5);
59const SILENCE_FRAMES: u8 = 5;
62const SILENCE: [u8; 3] = [0xF8, 0xFF, 0xFE];
64const LATE: Duration = Duration::from_millis(100);
67const AHEAD: usize = 50;
69const SETTLE: u8 = 2;
73
74type Read = Option<Result<Chunk, InputError>>;
76
77struct Reencode {
82 decoder: Decoder,
83 fifo: VecDeque<f32>,
84 steady: u8,
86}
87
88pub(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#[derive(Clone)]
133pub struct Call {
134 pub(crate) inner: Arc<Inner>,
135}
136
137pub(crate) struct Inner {
138 pub(crate) id: u64,
140 guild_id: GuildId,
141 shard_id: u32,
142 gateway: Arc<dyn VoiceGateway>,
143 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 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
166pub(crate) enum CallCommand {
168 Join {
170 channel_id: ChannelId,
171 bitrate: u32,
173 done: oneshot::Sender<Result<(), JoinError>>,
174 },
175 Abandoned,
177 State {
179 session_id: String,
180 channel_id: Option<ChannelId>,
181 },
182 Server {
184 token: String,
185 endpoint: Option<String>,
186 },
187 Wake,
189 Seek {
191 id: u64,
192 samples: u64,
193 done: oneshot::Sender<Result<Duration, TrackError>>,
194 },
195 Leave {
196 done: oneshot::Sender<()>,
197 },
198 Subscribe {
200 user_id: UserId,
201 options: ReceiveOptions,
202 tx: mpsc::Sender<receive::Item>,
203 },
204}
205
206pub(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 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 pub(crate) fn command(&self, command: CallCommand) -> bool {
265 self.inner.shared.commands.send(command).is_ok()
266 }
267
268 #[must_use]
272 pub fn guild_id(&self) -> GuildId {
273 self.inner.guild_id
274 }
275
276 #[must_use]
281 pub fn channel_id(&self) -> Option<ChannelId> {
282 *self.inner.channel.borrow()
283 }
284
285 #[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 #[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 #[must_use]
373 pub fn queue(&self) -> TrackQueue {
374 TrackQueue {
375 shared: Arc::clone(&self.inner.shared),
376 }
377 }
378
379 #[must_use]
414 pub fn subscribe(&self, user_id: UserId) -> VoiceStream {
415 self.subscribe_with(user_id, ReceiveOptions::new())
416 }
417
418 #[must_use]
446 pub fn subscribe_with(&self, user_id: UserId, options: ReceiveOptions) -> VoiceStream {
447 let (tx, rx) = mpsc::channel(receive::QUEUE);
448 self.command(CallCommand::Subscribe {
450 user_id,
451 options,
452 tx,
453 });
454 VoiceStream::new(rx, options)
455 }
456
457 #[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 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 let _ = ended.await;
489 }
490 sent
491 }
492}
493
494#[derive(Clone, Debug)]
499#[non_exhaustive]
500pub enum CallEvent {
501 Resumed,
503 Reconnected,
506 Disconnected(DisconnectReason),
508 UserJoined(UserId),
510 UserLeft(UserId),
512 #[non_exhaustive]
514 Speaking {
515 user_id: UserId,
517 ssrc: u32,
519 },
520 SpeakingStarted(UserId),
525 SpeakingStopped(UserId),
529}
530
531#[derive(Clone, Debug)]
535#[non_exhaustive]
536pub enum DisconnectReason {
537 Left,
539 #[non_exhaustive]
543 Closed {
544 code: u16,
547 },
548 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#[derive(Debug)]
580pub struct CallEvents {
581 rx: mpsc::UnboundedReceiver<CallEvent>,
582}
583
584impl CallEvents {
585 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#[derive(Default)]
604struct VoiceState {
605 session_id: Option<String>,
606 channel_id: Option<ChannelId>,
607 server: Option<(String, String)>,
609}
610
611struct 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
622struct Connecting {
624 channel_id: ChannelId,
625 task: JoinHandle<Result<Connected, ConnectError>>,
626}
627
628struct PendingJoin {
630 channel_id: ChannelId,
631 waiters: Vec<oneshot::Sender<Result<(), JoinError>>>,
632 deadline: Instant,
633 state: bool,
635 server: bool,
637}
638
639enum 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 Packet(Rtp),
650 Receive,
652}
653
654struct 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
667struct 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 fresh_server: bool,
680 live: Option<Live>,
681 connecting: Option<Connecting>,
682 join: Option<PendingJoin>,
683 grace: Option<Instant>,
685 removed: bool,
687 connected_once: bool,
688 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 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 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 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 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 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 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 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 old.handle.send(Command::Close);
949 }
950 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 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 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 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 return Ok(());
1042 }
1043 match end {
1044 End::Stopped(DISCONNECTED) if !self.removed => {
1045 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 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 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
1128fn 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
1135async fn live_step(live: &mut Option<Live>) -> Step {
1137 let Some(live) = live else {
1138 return core::future::pending().await;
1139 };
1140 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
1161async fn wait(deadline: Option<Instant>) {
1163 match deadline {
1164 Some(deadline) => sleep_until(deadline).await,
1165 None => core::future::pending().await,
1166 }
1167}
1168
1169fn 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#[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 again: Option<Again>,
1187 chunks: mpsc::Receiver<Result<Chunk, InputError>>,
1188 reader: JoinHandle<()>,
1189 reencode: Option<Reencode>,
1191 history: History,
1194 continuing: bool,
1197 celt: bool,
1199 after: VecDeque<Frame>,
1202 held: Option<Read>,
1203 decoded: usize,
1205 paused: bool,
1207 announced: bool,
1209 seeks: Vec<oneshot::Sender<Result<Duration, TrackError>>>,
1211 gain: f32,
1213 closing: bool,
1215 seek_to: Option<u64>,
1218 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 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 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 self.reader.abort();
1300 }
1301}
1302
1303struct Player {
1308 shared: Arc<Shared>,
1309 track: Option<Playing>,
1310 next: Option<Frame>,
1312 at: Option<Instant>,
1314 silence: u8,
1316 speaking: bool,
1318 bitrate: u32,
1319 encoder: Option<Encoder>,
1321 pcm: Vec<f32>,
1323 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 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 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 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 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 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 playing.seek_to = Some(samples);
1416 playing.closing = true;
1417 }
1418 }
1419 _ => {
1420 let _ = done.send(Err(TrackError::Ended));
1421 }
1422 }
1423 }
1424
1425 fn quiet(&mut self) {
1427 if self.speaking {
1428 self.silence = SILENCE_FRAMES;
1429 }
1430 }
1431
1432 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 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 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 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 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 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 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 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 self.reconcile();
1545 }
1546
1547 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 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 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 _ => now,
1573 };
1574 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 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 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 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 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 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 encoder.independent_next();
1650 }
1651 return;
1652 };
1653 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 (None, Frame::Pcm(_)) => return,
1665 }
1666 }
1667 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 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 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 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 None => !playing.continuing,
1722 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 let before = 960 - lookahead;
1740 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 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 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 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
1806fn fill(playing: &mut Playing, reencode: &mut Reencode, pcm: &mut [f32], values: usize) {
1809 while reencode.fifo.len() < values {
1810 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}