Skip to main content

djs_voice/
receive.rs

1//! Receiving audio (step 3, D-363–D-373): the public [`VoiceStream`] of one user's packets
2//! and its options, and [`Receiving`], what a call's task knows of who sends what.
3//!
4//! The call's task reads every RTP packet of the session ([`Receiver`](crate::connection::Receiver)):
5//! its header says whose it is (the SSRCs the voice gateway reports in Opcode 5), which is
6//! enough for [`CallEvent::SpeakingStarted`](crate::CallEvent::SpeakingStarted) and
7//! [`SpeakingStopped`](crate::CallEvent::SpeakingStopped). Only the packets of users someone
8//! subscribed to are decrypted, put in order by a [`Reorder`] buffer per user (D-366), then
9//! copied to each of their subscriptions (D-373). A stream that asked for PCM (D-364)
10//! decodes its packets itself, when it is read (D-374): the call's task only routes Opus, so
11//! a call with many speakers keeps up with its socket and its own audio, and the decoding
12//! is spread over the readers' tasks.
13
14use core::{
15    fmt,
16    pin::Pin,
17    task::{Context, Poll, ready},
18    time::Duration,
19};
20use std::collections::{HashMap, VecDeque};
21
22use djs_model::id::UserId;
23use futures_util::Stream;
24use tokio::{
25    sync::mpsc::{self, error::TrySendError},
26    time::Instant,
27};
28
29use crate::{codec::Decoder, opus, udp::Rtp};
30
31/// Opus's frame of silence, which Discord clients send after speaking.
32const SILENCE: [u8; 3] = [0xF8, 0xFF, 0xFE];
33/// How long a missing packet is waited for (D-366).
34const REORDER: Duration = Duration::from_millis(60);
35/// How long after their last packet a user stops speaking (D-369, as discord.js).
36const SPEAKING: Duration = Duration::from_millis(100);
37/// A jump of the sequence numbers further than this (a second of 20 ms packets) is a new
38/// stream, not lost packets.
39const JUMP: u16 = 50;
40/// How many packets a [`VoiceStream`] holds for a reader that is behind: about 5 s of
41/// 20 ms packets; more are dropped.
42pub(crate) const QUEUE: usize = 256;
43/// The most samples per channel an Opus packet holds: 120 ms.
44const MAX_SAMPLES: usize = 5760;
45/// The duration assumed for a packet whose own cannot be read: 20 ms.
46const FRAME: u32 = 960;
47
48/// When a [`VoiceStream`] ends by itself (D-365); it always ends with its call.
49///
50/// discord.js counterpart: `EndBehaviorType` and the `end` option of
51/// `VoiceReceiver#subscribe`.
52///
53/// # Examples
54///
55/// ```
56/// use std::time::Duration;
57///
58/// use djs_voice::{EndBehavior, ReceiveOptions};
59///
60/// // One stream per utterance: it ends a second after the user stops speaking.
61/// let options = ReceiveOptions::new().end(EndBehavior::AfterSilence(Duration::from_secs(1)));
62/// ```
63#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
64#[non_exhaustive]
65pub enum EndBehavior {
66    /// Only when the stream is dropped or the call ends.
67    #[default]
68    Manual,
69    /// When this long has passed since the user's last packet of audio other than silence
70    /// (Discord clients send a few frames of silence when they stop speaking). The time
71    /// starts at their first packet: a stream of someone who never speaks does not end.
72    AfterSilence(Duration),
73    /// When this long has passed since the user's last packet, silence or not; from their
74    /// first packet too.
75    AfterInactivity(Duration),
76}
77
78/// How [`Call::subscribe_with`](crate::Call::subscribe_with) receives a user's audio (D-372):
79/// the packets as Opus or decoded to PCM (D-364), and when the stream ends (D-365). The
80/// default is Opus, ended manually, as discord.js's `VoiceReceiver#subscribe`.
81///
82/// # Examples
83///
84/// ```
85/// use std::time::Duration;
86///
87/// use djs_voice::{EndBehavior, ReceiveOptions};
88///
89/// // Decoded audio, until a user has said nothing for half a second.
90/// let options = ReceiveOptions::new()
91///     .decode(true)
92///     .end(EndBehavior::AfterSilence(Duration::from_millis(500)));
93/// assert_ne!(options, ReceiveOptions::default());
94/// ```
95#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
96#[non_exhaustive]
97pub struct ReceiveOptions {
98    decode: bool,
99    end: EndBehavior,
100}
101
102impl ReceiveOptions {
103    /// The default options: Opus packets, [`EndBehavior::Manual`].
104    ///
105    /// discord.js counterpart: `AudioReceiveStreamOptions` (`@discordjs/voice`).
106    #[must_use]
107    pub const fn new() -> Self {
108        Self {
109            decode: false,
110            end: EndBehavior::Manual,
111        }
112    }
113
114    /// Whether the packets are decoded (D-364, D-370): [`VoiceData::Pcm`] at 48 kHz, stereo,
115    /// interleaved `i16` samples, lost packets concealed by Opus (rebuilt from the next
116    /// packet's forward error correction when it has some). Otherwise [`VoiceData::Opus`],
117    /// as they came, and [`VoiceData::Lost`] for the lost ones.
118    ///
119    /// discord.js counterpart: none (`@discordjs/voice` hands Opus packets only).
120    #[must_use]
121    pub const fn decode(mut self, decode: bool) -> Self {
122        self.decode = decode;
123        self
124    }
125
126    /// When the stream ends by itself (D-365).
127    ///
128    /// discord.js counterpart: the `end` of `AudioReceiveStreamOptions` (`@discordjs/voice`).
129    #[must_use]
130    pub const fn end(mut self, end: EndBehavior) -> Self {
131        self.end = end;
132        self
133    }
134}
135
136/// A packet of a user's audio, from a [`VoiceStream`] (D-368), in the order the user sent
137/// them: each one follows the one before, by [`sequence`](Self::sequence).
138///
139/// discord.js counterpart: the Opus packets an `AudioReceiveStream` yields.
140#[derive(Clone, Debug, PartialEq, Eq)]
141#[non_exhaustive]
142pub struct VoicePacket {
143    /// The RTP sequence number, one more than the packet before (wrapping after 65 535).
144    pub sequence: u16,
145    /// The RTP timestamp: when the audio starts, in samples per channel at 48 kHz from a
146    /// start of the sender's choosing (wrapping after `u32::MAX`). Packets that follow one
147    /// another without a pause are 960 apart (20 ms); a pause in speaking shows as a larger
148    /// step. A lost packet's timestamp is an estimate.
149    pub timestamp: u32,
150    /// The audio.
151    pub audio: VoiceData,
152}
153
154/// The audio of a [`VoicePacket`] (D-368).
155///
156/// discord.js counterpart: none (`@discordjs/voice` receives Opus only).
157#[derive(Clone, Debug, PartialEq, Eq)]
158#[non_exhaustive]
159pub enum VoiceData {
160    /// An Opus packet as the user sent it (decrypted): stereo, 48 kHz, usually 20 ms.
161    /// `[0xF8, 0xFF, 0xFE]` is a frame of silence, which clients send when they stop.
162    Opus(Vec<u8>),
163    /// Decoded audio (D-370): 48 kHz, stereo, interleaved `i16` samples (left, right, left,
164    /// …), 1 920 of them for 20 ms. A lost packet comes as this too, concealed.
165    Pcm(Vec<i16>),
166    /// A packet that did not come in time (D-366), in a stream of Opus packets. Only
167    /// packets missing between two that came are reported, not the pauses in speaking.
168    Lost,
169}
170
171/// The packets of one user's audio, from [`Call::subscribe`](crate::Call::subscribe) (D-371).
172/// It ends with its call, or as its [`EndBehavior`] says; dropping it unsubscribes.
173///
174/// A reader that falls more than about 5 s behind loses the packets that do not fit.
175/// A stream of decoded audio ([`ReceiveOptions::decode`]) decodes each packet when it is
176/// read, on the task that reads it (D-374): about 40 µs of that task's time per 20 ms
177/// packet.
178///
179/// Implements [`Stream`]; [`next`](Self::next) is provided so no extension trait is needed.
180///
181/// discord.js counterpart: `AudioReceiveStream`.
182pub struct VoiceStream {
183    rx: mpsc::Receiver<Item>,
184    /// For PCM; boxed, as most streams are of Opus.
185    decoding: Option<Box<Decoding>>,
186}
187
188impl VoiceStream {
189    /// The stream of what `rx` receives, decoded if `options` say so. A stream that cannot
190    /// decode (libopus cannot make a decoder, which it always can) ends at once.
191    pub(crate) fn new(mut rx: mpsc::Receiver<Item>, options: ReceiveOptions) -> Self {
192        let decoding = if options.decode {
193            let decoding = Decoder::new().map(|decoder| {
194                Box::new(Decoding {
195                    decoder,
196                    pcm: vec![0; MAX_SAMPLES * 2],
197                    ahead: None,
198                    lost: None,
199                })
200            });
201            if decoding.is_none() {
202                rx.close();
203            }
204            decoding
205        } else {
206            None
207        };
208        Self { rx, decoding }
209    }
210
211    /// Waits for the next packet; `None` once the stream has ended. Cancel safe: a packet
212    /// is never lost by dropping the future before it is ready.
213    ///
214    /// discord.js counterpart: the `data` event of `AudioReceiveStream` (`@discordjs/voice`).
215    pub async fn next(&mut self) -> Option<VoicePacket> {
216        core::future::poll_fn(|cx| Pin::new(&mut *self).poll_next(cx)).await
217    }
218
219    /// The next packet if one is there, without waiting.
220    #[cfg(test)]
221    pub(crate) fn try_next(&mut self) -> Result<VoicePacket, mpsc::error::TryRecvError> {
222        let mut cx = Context::from_waker(std::task::Waker::noop());
223        match Pin::new(self).poll_next(&mut cx) {
224            Poll::Ready(Some(packet)) => Ok(packet),
225            Poll::Ready(None) => Err(mpsc::error::TryRecvError::Disconnected),
226            Poll::Pending => Err(mpsc::error::TryRecvError::Empty),
227        }
228    }
229}
230
231impl fmt::Debug for VoiceStream {
232    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
233        f.debug_struct("VoiceStream")
234            .field("decode", &self.decoding.is_some())
235            .finish_non_exhaustive()
236    }
237}
238
239impl Stream for VoiceStream {
240    type Item = VoicePacket;
241
242    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<VoicePacket>> {
243        let Self { rx, decoding } = self.get_mut();
244        let Some(decoding) = decoding else {
245            return rx.poll_recv(cx).map(|item| {
246                item.map(|item| match item {
247                    Item::Packet {
248                        sequence,
249                        timestamp,
250                        opus,
251                    } => VoicePacket {
252                        sequence,
253                        timestamp,
254                        audio: VoiceData::Opus(opus),
255                    },
256                    Item::Lost {
257                        sequence,
258                        timestamp,
259                        ..
260                    } => VoicePacket {
261                        sequence,
262                        timestamp,
263                        audio: VoiceData::Lost,
264                    },
265                })
266            });
267        };
268        decoding.poll(rx, cx)
269    }
270}
271
272/// A [`VoiceStream`]'s decoding (D-364, D-374).
273struct Decoding {
274    decoder: Decoder,
275    /// Room for a packet's samples.
276    pcm: Vec<i16>,
277    /// The item after a lost packet, read to rebuild that one: given next.
278    ahead: Option<Item>,
279    /// A lost packet waiting for the item after it (sequence, timestamp, samples).
280    lost: Option<(u16, u32, u32)>,
281}
282
283impl Decoding {
284    fn poll(
285        &mut self,
286        rx: &mut mpsc::Receiver<Item>,
287        cx: &mut Context<'_>,
288    ) -> Poll<Option<VoicePacket>> {
289        loop {
290            if let Some((sequence, timestamp, samples)) = self.lost {
291                // Every gap given up is followed by a packet that came, sent with it: the
292                // packet after a lost one may carry it (forward error correction).
293                let after = ready!(rx.poll_recv(cx));
294                self.lost = None;
295                let audio = match &after {
296                    Some(Item::Packet {
297                        sequence: next,
298                        opus,
299                        ..
300                    }) if *next == sequence.wrapping_add(1) => {
301                        decode(&mut self.decoder, &mut self.pcm, opus, true, samples)
302                    }
303                    _ => decode(&mut self.decoder, &mut self.pcm, &[], false, samples),
304                };
305                self.ahead = after;
306                return Poll::Ready(Some(VoicePacket {
307                    sequence,
308                    timestamp,
309                    audio,
310                }));
311            }
312            let item = match self.ahead.take() {
313                Some(item) => item,
314                None => match ready!(rx.poll_recv(cx)) {
315                    Some(item) => item,
316                    None => return Poll::Ready(None),
317                },
318            };
319            match item {
320                Item::Packet {
321                    sequence,
322                    timestamp,
323                    opus,
324                } => {
325                    let audio = decode(&mut self.decoder, &mut self.pcm, &opus, false, FRAME);
326                    return Poll::Ready(Some(VoicePacket {
327                        sequence,
328                        timestamp,
329                        audio,
330                    }));
331                }
332                Item::Lost {
333                    sequence,
334                    timestamp,
335                    samples,
336                } => self.lost = Some((sequence, timestamp, samples)),
337            }
338        }
339    }
340}
341
342/// A packet put in order, or one given up: what a call's task sends a [`VoiceStream`].
343#[derive(Clone, Debug, PartialEq, Eq)]
344pub(crate) enum Item {
345    Packet {
346        sequence: u16,
347        timestamp: u32,
348        opus: Vec<u8>,
349    },
350    Lost {
351        sequence: u16,
352        timestamp: u32,
353        /// How long it is assumed to be: as the packet before.
354        samples: u32,
355    },
356}
357
358/// A packet waiting for a missing one before it.
359#[derive(Debug)]
360struct Held {
361    timestamp: u32,
362    opus: Vec<u8>,
363}
364
365/// Puts one sender's packets in order (D-366). A packet that follows the one before is
366/// passed on at once; after a gap, the packets are held until the missing ones come, for
367/// at most [`REORDER`] after the first held one came. Then every gap is given up as lost.
368/// Packets older than the one passed on last are dropped (late, or duplicates).
369#[derive(Debug, Default)]
370struct Reorder {
371    /// The sequence number passed on next; `None` before the first packet.
372    next: Option<u16>,
373    /// The timestamp and duration of the last packet passed on.
374    timestamp: u32,
375    samples: u32,
376    /// `held[i]` is the packet `next + i`, `None` while missing; empty without a gap.
377    held: VecDeque<Option<Held>>,
378    /// When the first packet after a gap came.
379    since: Option<Instant>,
380}
381
382impl Reorder {
383    fn push(
384        &mut self,
385        sequence: u16,
386        timestamp: u32,
387        opus: &[u8],
388        now: Instant,
389        out: &mut Vec<Item>,
390    ) {
391        let Some(next) = self.next else {
392            self.pass(sequence, timestamp, opus.to_vec(), out);
393            return;
394        };
395        let ahead = sequence.wrapping_sub(next);
396        let behind = next.wrapping_sub(sequence);
397        if ahead > JUMP {
398            if behind != 0 && behind <= JUMP {
399                // Late (given up already) or a duplicate.
400                return;
401            }
402            // A new stream: what is held goes first.
403            self.flush(out);
404            self.pass(sequence, timestamp, opus.to_vec(), out);
405            return;
406        }
407        let index = usize::from(ahead);
408        if index == 0 && self.held.is_empty() {
409            self.pass(sequence, timestamp, opus.to_vec(), out);
410            return;
411        }
412        if self.held.len() <= index {
413            self.held.resize_with(index + 1, || None);
414        }
415        if self.held[index].is_some() {
416            return;
417        }
418        self.held[index] = Some(Held {
419            timestamp,
420            opus: opus.to_vec(),
421        });
422        self.since.get_or_insert(now);
423        self.drain(out);
424    }
425
426    /// Passes on the held packets that follow the last one passed on.
427    fn drain(&mut self, out: &mut Vec<Item>) {
428        while let Some(Some(_)) = self.held.front() {
429            let Some(Some(held)) = self.held.pop_front() else {
430                break;
431            };
432            let sequence = self.next.unwrap_or_default();
433            self.pass(sequence, held.timestamp, held.opus, out);
434        }
435        if self.held.is_empty() {
436            self.since = None;
437        }
438    }
439
440    /// Gives up the missing packets: passes on everything held, in order.
441    fn flush(&mut self, out: &mut Vec<Item>) {
442        while let Some(slot) = self.held.pop_front() {
443            let sequence = self.next.unwrap_or_default();
444            if let Some(held) = slot {
445                self.pass(sequence, held.timestamp, held.opus, out);
446            } else {
447                let timestamp = self.timestamp.wrapping_add(self.samples);
448                out.push(Item::Lost {
449                    sequence,
450                    timestamp,
451                    samples: self.samples,
452                });
453                self.timestamp = timestamp;
454                self.next = Some(sequence.wrapping_add(1));
455            }
456        }
457        self.since = None;
458    }
459
460    fn pass(&mut self, sequence: u16, timestamp: u32, opus: Vec<u8>, out: &mut Vec<Item>) {
461        self.next = Some(sequence.wrapping_add(1));
462        self.timestamp = timestamp;
463        self.samples = opus::packet_samples(&opus).unwrap_or(FRAME);
464        out.push(Item::Packet {
465            sequence,
466            timestamp,
467            opus,
468        });
469    }
470
471    /// When the missing packets are given up.
472    fn deadline(&self) -> Option<Instant> {
473        self.since.map(|since| since + REORDER)
474    }
475}
476
477/// One [`VoiceStream`], as the call's task holds it.
478struct Subscription {
479    tx: mpsc::Sender<Item>,
480    end: EndBehavior,
481    /// When it ends ([`EndBehavior`]), once a packet came.
482    end_at: Option<Instant>,
483}
484
485impl Subscription {
486    /// Sends `item`; whether the stream is still there.
487    fn send(&mut self, item: &Item, now: Instant) -> bool {
488        if let Item::Packet { opus, .. } = item {
489            match self.end {
490                EndBehavior::Manual => {}
491                EndBehavior::AfterSilence(wait) => {
492                    if opus[..] != SILENCE || self.end_at.is_none() {
493                        self.end_at = Some(now + wait);
494                    }
495                }
496                EndBehavior::AfterInactivity(wait) => self.end_at = Some(now + wait),
497            }
498        }
499        match self.tx.try_send(item.clone()) {
500            Ok(()) => true,
501            Err(TrySendError::Full(_)) => {
502                tracing::trace!("dropping a received packet: its stream's reader is behind");
503                true
504            }
505            Err(TrySendError::Closed(_)) => false,
506        }
507    }
508
509    fn ended(&self, now: Instant) -> bool {
510        self.end_at.is_some_and(|at| at <= now) || self.tx.is_closed()
511    }
512}
513
514/// Decodes `packet` (`fec`: the lost one before it from its forward error correction, or
515/// empty: concealed) of `samples` (when lost); a packet that does not decode is concealed.
516fn decode(
517    decoder: &mut Decoder,
518    pcm: &mut [i16],
519    packet: &[u8],
520    fec: bool,
521    samples: u32,
522) -> VoiceData {
523    let lost = usize::try_from(samples).map_or(MAX_SAMPLES, |samples| samples.min(MAX_SAMPLES));
524    let written = if packet.is_empty() || fec {
525        decoder.decode_i16(packet, fec, &mut pcm[..lost * 2])
526    } else {
527        decoder
528            .decode_i16(packet, false, pcm)
529            .or_else(|| decoder.decode_i16(&[], false, &mut pcm[..lost * 2]))
530    };
531    match written {
532        Some(samples) => VoiceData::Pcm(pcm[..samples * 2].to_vec()),
533        None => VoiceData::Lost,
534    }
535}
536
537/// A user someone receives, or who speaks.
538#[derive(Default)]
539struct User {
540    /// When their last packet came: `Some` while they speak (D-369).
541    last: Option<Instant>,
542    order: Reorder,
543    subscriptions: Vec<Subscription>,
544}
545
546impl User {
547    /// Sends `items` to every subscription; the closed ones are removed.
548    fn send(&mut self, items: &[Item], now: Instant) {
549        for item in items {
550            self.subscriptions
551                .retain_mut(|subscription| subscription.send(item, now));
552        }
553        if self.subscriptions.is_empty() {
554            self.order = Reorder::default();
555        }
556    }
557}
558
559/// A packet of a known user, from [`Receiving::arrived`].
560#[derive(Clone, Copy, Debug)]
561pub(crate) struct Arrival {
562    pub(crate) user_id: UserId,
563    /// Their first packet in a while: they started speaking.
564    pub(crate) started: bool,
565    /// Someone receives them: open the packet and give it to [`Receiving::opened`].
566    pub(crate) wanted: bool,
567}
568
569/// What a call's task knows of the audio it receives: whose each SSRC is, who speaks, and
570/// the subscriptions.
571#[derive(Default)]
572pub(crate) struct Receiving {
573    /// The users of the SSRCs the voice gateway reported (Opcode 5).
574    ssrcs: HashMap<u32, UserId>,
575    users: HashMap<UserId, User>,
576    /// The items passed on, reused.
577    items: Vec<Item>,
578}
579
580impl Receiving {
581    /// Adds a subscription to `user_id`'s audio.
582    pub(crate) fn subscribe(
583        &mut self,
584        user_id: UserId,
585        options: ReceiveOptions,
586        tx: mpsc::Sender<Item>,
587    ) {
588        self.users
589            .entry(user_id)
590            .or_default()
591            .subscriptions
592            .push(Subscription {
593                tx,
594                end: options.end,
595                end_at: None,
596            });
597    }
598
599    /// The voice gateway reported that `user_id` sends with `ssrc` (Opcode 5).
600    pub(crate) fn map(&mut self, user_id: UserId, ssrc: u32, now: Instant) {
601        if self.ssrcs.get(&ssrc) == Some(&user_id) {
602            return;
603        }
604        let had = self.ssrcs.values().any(|user| *user == user_id);
605        self.ssrcs.retain(|_, user| *user != user_id);
606        self.ssrcs.insert(ssrc, user_id);
607        if had && let Some(user) = self.users.get_mut(&user_id) {
608            // Their new source numbers its packets anew.
609            let mut items = core::mem::take(&mut self.items);
610            user.order.flush(&mut items);
611            user.send(&items, now);
612            user.order = Reorder::default();
613            items.clear();
614            self.items = items;
615        }
616    }
617
618    /// `user_id` left the channel: their packets are not expected any more.
619    pub(crate) fn left(&mut self, user_id: UserId) {
620        self.ssrcs.retain(|_, user| *user != user_id);
621    }
622
623    /// A new connection (another channel's voice server): other users, other SSRCs. Returns
624    /// the users who were speaking.
625    pub(crate) fn reset(&mut self) -> Vec<UserId> {
626        self.ssrcs.clear();
627        let mut stopped = Vec::new();
628        for (user_id, user) in &mut self.users {
629            if user.last.take().is_some() {
630                stopped.push(*user_id);
631            }
632            user.order = Reorder::default();
633        }
634        self.users.retain(|_, user| !user.subscriptions.is_empty());
635        stopped
636    }
637
638    /// The packet `rtp` came: whose it is, if the voice gateway said.
639    pub(crate) fn arrived(&mut self, rtp: Rtp, now: Instant) -> Option<Arrival> {
640        let user_id = *self.ssrcs.get(&rtp.ssrc)?;
641        let user = self.users.entry(user_id).or_default();
642        let started = user.last.replace(now).is_none();
643        Some(Arrival {
644            user_id,
645            started,
646            wanted: !user.subscriptions.is_empty(),
647        })
648    }
649
650    /// The Opus packet of `rtp`, from `user_id`, opened: put in order and sent on.
651    pub(crate) fn opened(&mut self, user_id: UserId, rtp: Rtp, opus: &[u8], now: Instant) {
652        let Some(user) = self.users.get_mut(&user_id) else {
653            return;
654        };
655        let mut items = core::mem::take(&mut self.items);
656        user.order
657            .push(rtp.sequence, rtp.timestamp, opus, now, &mut items);
658        user.send(&items, now);
659        items.clear();
660        self.items = items;
661    }
662
663    /// When [`tick`](Self::tick) has something to do.
664    pub(crate) fn deadline(&self) -> Option<Instant> {
665        self.users
666            .values()
667            .flat_map(|user| {
668                let ends = user
669                    .subscriptions
670                    .iter()
671                    .filter_map(|subscription| subscription.end_at)
672                    .min();
673                [
674                    user.last.map(|last| last + SPEAKING),
675                    user.order.deadline(),
676                    ends,
677                ]
678            })
679            .flatten()
680            .min()
681    }
682
683    /// Does what is due at `now`: users stop speaking (returned), missing packets are given
684    /// up, streams end.
685    pub(crate) fn tick(&mut self, now: Instant) -> Vec<UserId> {
686        let mut stopped = Vec::new();
687        let mut items = core::mem::take(&mut self.items);
688        for (user_id, user) in &mut self.users {
689            if user.last.is_some_and(|last| last + SPEAKING <= now) {
690                user.last = None;
691                stopped.push(*user_id);
692            }
693            if user.order.deadline().is_some_and(|at| at <= now) {
694                user.order.flush(&mut items);
695                user.send(&items, now);
696                items.clear();
697            }
698            // Dropping a subscription ends its stream, after the packets it holds.
699            user.subscriptions
700                .retain(|subscription| !subscription.ended(now));
701            if user.subscriptions.is_empty() {
702                user.order = Reorder::default();
703            }
704        }
705        self.items = items;
706        self.users
707            .retain(|_, user| user.last.is_some() || !user.subscriptions.is_empty());
708        stopped
709    }
710}
711
712#[cfg(test)]
713mod tests;