Skip to content

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

6.3 KB
Raw Blame
// Adapted from Serein (https://github.com/ViceVerse-cz/Serein) at commit a0e72cc,
// file `crates/discord-voice/src/activity.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.
//! Display-only activity; never gates or changes transmitted audio.
// (A -45 dBFS level threshold detects sound, not speech: steady noise above it shows as talking.)
pub(crate) fn hold(energy: f32, previous: u8) -> u8 {
    if energy.is_finite() && energy > 960.0 * 0.000_031_623 {
        10 // 200 ms at the transport's 20 ms cadence.
    } else {
        previous.saturating_sub(1)
    }
}

/// Finite RMS level for the local preview meter, clamped to its display range.
pub(crate) fn level_db(frame: &[f32; 960]) -> f32 {
    let energy: f32 = frame
        .iter()
        .filter(|s| s.is_finite())
        .map(|s| s.clamp(-1.0, 1.0).powi(2))
        .sum();
    (10.0 * (energy / 960.0).max(1e-10).log10()).clamp(-100.0, 0.0)
}

/// Manual sensitivity with 3 dB hysteresis, 200 ms release and a 5 ms click-free ramp.
///
/// The gate decides per 20 ms frame, so the soft start of a word ("h", "f", "s") usually
/// sits in the frame before the one loud enough to open it. That frame is kept, and when
/// the gate opens it goes out first ([`InputGate::take_lead`]), so words are not clipped;
/// each burst of speech is sent 20 ms later for it.
#[derive(Default)]
pub(crate) struct InputGate {
    remaining: u8,
    gain: f32,
    /// The last frame the gate dropped.
    previous: Option<[f32; 960]>,
    /// That frame, ramped in, when the gate has just opened.
    lead: Option<[f32; 960]>,
}
impl InputGate {
    pub fn apply(&mut self, frame: &mut [f32; 960], threshold: Option<i16>) -> bool {
        let Some(threshold) = threshold else {
            self.gain = 1.0;
            self.remaining = 0;
            self.forget();
            return true;
        };
        let closing = self.remaining > 0;
        let held = threshold == i16::MIN;
        let threshold = f32::from(threshold.clamp(-80, 0)) - if closing { 3.0 } else { 0.0 };
        if level_db(frame) > threshold {
            self.remaining = 10;
        } else {
            self.remaining = self.remaining.saturating_sub(1);
        }
        let open = self.remaining > 0;
        let audible = open || self.gain > 0.0;
        if !audible {
            self.previous = Some(*frame);
            frame.fill(0.0);
            return false;
        }
        // Opening from silence: the ramp goes on the lead-in. Push to Talk sends nothing
        // from before the key went down.
        let previous = self.previous.take();
        if self.gain == 0.0
            && !held
            && let Some(mut lead) = previous
        {
            self.ramp(&mut lead, true);
            self.lead = Some(lead);
        }
        self.ramp(frame, open);
        true
    }
    fn ramp(&mut self, frame: &mut [f32; 960], open: bool) {
        for sample in frame {
            self.gain = (self.gain + if open { 1.0 / 240.0 } else { -1.0 / 240.0 }).clamp(0.0, 1.0);
            *sample *= self.gain;
        }
    }
    /// The lead-in frame to send before the one [`InputGate::apply`] just opened on.
    pub fn take_lead(&mut self) -> Option<[f32; 960]> {
        self.lead.take()
    }
    /// Drop the kept frame, for when the audio after it is not continuous (muted, a reset).
    pub fn forget(&mut self) {
        self.previous = None;
        self.lead = None;
    }
}

pub(crate) fn hold_at(energy: f32, previous: u8, threshold: i16) -> u8 {
    if energy.is_finite()
        && energy > 960.0 * 10.0_f32.powf(f32::from(threshold.clamp(-80, 0)) / 10.0)
    {
        10
    } else {
        previous.saturating_sub(1)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    // Device-free part of Serein's `audio::debug_processing_check`.
    #[test]
    fn energy_gate_opens_ramps_and_releases_after_200ms() {
        let mut gate = InputGate::default();
        let mut quiet = [0.0001; 960];
        assert!(!gate.apply(&mut quiet, Some(-55)) && quiet == [0.0; 960]);
        let mut speech = [0.1; 960];
        assert!(gate.apply(&mut speech, Some(-55)));
        let lead = gate.take_lead().unwrap();
        assert!(lead[0] < lead[959], "opening ramps instead of clicking");
        for _ in 0..11 {
            gate.apply(&mut [0.0; 960], Some(-55));
        }
        assert!(!gate.apply(&mut [0.0; 960], Some(-55)));
        let mut quiet = [0.0001; 960];
        assert!(gate.apply(&mut quiet, None) && quiet == [0.0001; 960]);
        assert!(level_db(&[0.0; 960]) <= -100.0);
        assert!((level_db(&[1.0; 960])).abs() < 0.001);
        assert!(level_db(&[f32::NAN; 960]).is_finite());
    }
    #[test]
    fn opening_sends_the_word_start_first() {
        let mut gate = InputGate::default();
        let mut onset = [0.0005; 960]; // -66 dBFS: below the gate, but part of the word.
        assert!(!gate.apply(&mut onset, Some(-55)));
        assert!(gate.take_lead().is_none());
        let mut speech = [0.1; 960];
        assert!(gate.apply(&mut speech, Some(-55)));
        let lead = gate.take_lead().expect("the frame before the gate opened");
        assert!((lead[0] - 0.0005 / 240.0).abs() < 1e-9, "the ramp is on the lead-in");
        assert_eq!(lead[959], 0.0005);
        assert!(speech.iter().all(|s| *s == 0.1), "the opening frame at full level");
        assert!(gate.take_lead().is_none());
        // While open, nothing extra is sent.
        assert!(gate.apply(&mut [0.1; 960], Some(-55)) && gate.take_lead().is_none());
        // Push to Talk: nothing from before the key went down.
        let mut gate = InputGate::default();
        assert!(!gate.apply(&mut [0.1; 960], Some(i16::MAX)));
        assert!(gate.apply(&mut [0.1; 960], Some(i16::MIN)) && gate.take_lead().is_none());
        // A muted stretch in between drops the kept frame.
        let mut gate = InputGate::default();
        assert!(!gate.apply(&mut [0.0005; 960], Some(-55)));
        gate.forget();
        assert!(gate.apply(&mut [0.1; 960], Some(-55)) && gate.take_lead().is_none());
    }

    #[test]
    fn activity_holds_for_ten_ticks() {
        let loud = 960.0 * 0.01;
        assert_eq!(hold(loud, 0), 10);
        assert_eq!(hold(0.0, 10), 9);
        assert_eq!(hold(f32::NAN, 1), 0);
        assert_eq!(hold_at(loud, 0, -55), 10);
        assert_eq!(hold_at(960.0 * 1e-7, 3, -55), 2);
    }
}