Skip to content

Lightweight native Discord client for Windows, Linux and macOS, written in Rust. No Electron, no browser engine.

8.0 KB
Raw Blame
// Adapted from Serein (https://github.com/ViceVerse-cz/Serein) at commit a0e72cc,
// file `crates/discord-voice/src/jitter.rs`.
// Copyright (c) 2026 Serein contributors. Licensed under MIT OR Apache-2.0; RustCord's
// modifications are under the same terms. See crates/voice/NOTICE.md.
//! Fixed 40ms startup with a bounded reorder window for 2.5-120 ms Opus packets.
//!
//! RustCord: the window holds 32 packets (640 ms of 20 ms speech) instead of eight. When
//! the media thread wakes late, everything that arrived meanwhile is pushed at once; an
//! eight-packet window treated the ninth as a jump and threw the speech before it away.
//! A window that stays deeper than `DEEP` of audio is shortened by one packet every half
//! second, so that delay does not stay.
const SLOTS: usize = 32;
/// Playout starts early once this many packets wait (short packets fill it before 40 ms).
const START: usize = 8;
/// More waiting audio than this (48 kHz samples: 160 ms) is delay worth shedding.
const DEEP: usize = 7_680;

/// How much audio an Opus packet holds, in 48 kHz samples, from its TOC byte (RFC 6716
/// section 3.1). An unreadable packet counts as the usual 20 ms.
fn duration(opus: &[u8]) -> usize {
    let Some(&toc) = opus.first() else { return 960 };
    let frame = match toc >> 3 {
        config @ 0..=11 => [480, 960, 1_920, 2_880][usize::from(config % 4)],
        config @ 12..=15 => [480, 960][usize::from(config % 2)],
        config => [120, 240, 480, 960][usize::from(config % 4)],
    };
    let frames = match toc & 3 {
        0 => 1,
        1 | 2 => 2,
        _ => usize::from(opus.get(1).copied().unwrap_or(1) & 0x3f).max(1),
    };
    (frame * frames).min(5_760)
}
#[derive(Default)]
pub(crate) struct Jitter {
    packets: Vec<(u16, Vec<u8>)>,
    next: Option<u16>,
    wait: u8,
    missing: u8,
    /// Consecutive pops that left the window deeper than `DEEP`.
    deep: u8,
}
impl Jitter {
    pub fn clear(&mut self) {
        *self = Self::default();
    }
    pub fn push(&mut self, sequence: u16, opus: Vec<u8>) {
        if opus.len() > 1275 {
            return;
        }
        if self.next.is_none() {
            self.next = Some(sequence);
            self.wait = 2;
        }
        let distance = sequence.wrapping_sub(self.next.unwrap());
        if distance >= 32768 {
            return;
        }
        if distance >= SLOTS as u16 {
            if !self.packets.is_empty() {
                crate::health::count(&crate::health::JITTER_RESETS);
            }
            self.packets.clear();
            self.next = Some(sequence);
            self.wait = 2;
            self.missing = 0;
        }
        if self.packets.len() < SLOTS && !self.packets.iter().any(|(id, _)| *id == sequence) {
            self.packets.push((sequence, opus));
        }
    }
    /// An empty packet requests Opus packet-loss concealment, at most three consecutive packets.
    pub fn pop(&mut self) -> Option<Vec<u8>> {
        if self.wait > 0 {
            // Short packets can fill the fixed window before 40ms. Start before
            // the next arrival would repeatedly reset a full window.
            if self.packets.len() < START {
                self.wait -= 1;
                return None;
            }
            self.wait = 0;
        }
        let next = self.next?;
        self.next = Some(next.wrapping_add(1));
        if let Some(index) = self.packets.iter().position(|(id, _)| *id == next) {
            self.missing = 0;
            let packet = self.packets.swap_remove(index).1;
            if self.packets.iter().map(|(_, opus)| duration(opus)).sum::<usize>() > DEEP {
                self.deep += 1;
                // Half a second too deep: skip the packet after this one (20 ms of delay).
                if self.deep >= 25 {
                    self.deep = 0;
                    let skipped = next.wrapping_add(1);
                    if let Some(index) = self.packets.iter().position(|(id, _)| *id == skipped) {
                        self.packets.swap_remove(index);
                        self.next = Some(skipped.wrapping_add(1));
                        crate::health::count(&crate::health::JITTER_TRIMMED);
                    }
                }
            } else {
                self.deep = 0;
            }
            return Some(packet);
        }
        self.missing += 1;
        if self.missing > 3 {
            // Stop concealing the gap, but retain speech that already arrived after it.
            if let Some((index, (sequence, _))) = self
                .packets
                .iter()
                .enumerate()
                .min_by_key(|(_, (sequence, _))| sequence.wrapping_sub(next))
            {
                self.next = Some(sequence.wrapping_add(1));
                self.missing = 0;
                return Some(self.packets.swap_remove(index).1);
            }
            self.clear();
            return None;
        }
        crate::health::count(&crate::health::CONCEALED);
        Some(Vec::new())
    }
}
#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn burst_loss_preserves_buffered_recovery_and_resets_on_far_jump() {
        for first in [0u16, u16::MAX - 2] {
            let mut jitter = Jitter::default();
            jitter.push(first, vec![0]);
            for offset in [7, 5, 6] {
                jitter.push(first.wrapping_add(offset), vec![offset as u8]);
            }
            assert!(jitter.pop().is_none());
            assert!(jitter.pop().is_none());
            assert_eq!(jitter.pop(), Some(vec![0]));
            for _ in 0..3 {
                assert_eq!(jitter.pop(), Some(vec![]));
            }
            for offset in [5, 6, 7] {
                assert_eq!(jitter.pop(), Some(vec![offset]));
            }
            for _ in 0..2 {
                assert_eq!(jitter.pop(), Some(vec![]));
            }
            jitter.push(first.wrapping_add(100), vec![100]);
            assert_eq!(jitter.missing, 0);
            assert!(jitter.pop().is_none());
            assert!(jitter.pop().is_none());
            assert_eq!(jitter.pop(), Some(vec![100]));
        }
    }
    #[test]
    fn bounded_reordering_loss_duplicates_and_wrap() {
        let mut jitter = Jitter::default();
        jitter.push(u16::MAX, vec![1]);
        jitter.push(1, vec![3]);
        jitter.push(0, vec![2]);
        jitter.push(0, vec![9]);
        assert!(jitter.pop().is_none());
        assert!(jitter.pop().is_none());
        assert_eq!(jitter.pop(), Some(vec![1]));
        assert_eq!(jitter.pop(), Some(vec![2]));
        assert_eq!(jitter.pop(), Some(vec![3]));
        for _ in 0..3 {
            assert_eq!(jitter.pop(), Some(vec![]));
        }
        assert!(jitter.pop().is_none());
        assert!(jitter.pop().is_none());
        for sequence in 0..1000 {
            jitter.push(sequence, vec![1; 1275]);
            assert!(jitter.packets.len() <= SLOTS);
        }
        // A late wake-up delivers 300 ms of speech at once: all of it is kept and played
        // in order, and the extra depth is then shed one packet at a time.
        let mut jitter = Jitter::default();
        for sequence in 0..15u16 {
            jitter.push(sequence, vec![sequence as u8]);
        }
        for sequence in 0..15u8 {
            assert_eq!(jitter.pop(), Some(vec![sequence]));
        }
        let mut jitter = Jitter::default();
        let mut played = Vec::new();
        for sequence in 0..200u16 {
            // 0x78: a 20 ms CELT fullband packet.
            jitter.push(sequence, vec![0x78, sequence as u8]);
            // Twelve packets (240 ms) of standing depth: the pop runs that far behind.
            if sequence >= 12 {
                played.extend(jitter.pop());
            }
        }
        assert!(jitter.packets.len() <= 9, "{}", jitter.packets.len());
        assert!(played.len() > 150);
        assert_eq!(duration(&[0x78]), 960);
        assert_eq!(duration(&[0x80]), 120);
        assert_eq!(duration(&[0x0b, 2]), 1_920);
        assert_eq!(duration(&[0x79]), 1_920);
        assert_eq!(duration(&[]), 960);
        jitter.push(1000, vec![0; 1276]);
        assert!(jitter.packets.len() <= SLOTS);
    }
}