Skip to content

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

4.7 KB
Raw Blame
// RustCord's own (MIT OR Apache-2.0). See crates/voice/NOTICE.md.
//! Watched Go Live audio, mixed into the call's 20 ms speaker frames.
//!
//! Serein hands each watched stream's PCM to the call loop, which bridges it with
//! `stream_playout` and mixes it with the participants' voices. RustCord's call starts before
//! any stream and streams come and go, so each watch registers an input here instead.
use crate::{Frame, PlaybackFrame, stream_playout::Playout};
use std::{
    sync::{
        Arc, Mutex, Weak,
        atomic::{AtomicU16, AtomicU64, Ordering},
        mpsc::{Receiver, SyncSender, sync_channel},
    },
    time::{Duration, Instant},
};

/// Estimated time from the call loop handing a frame to the speaker queue until it plays
/// (the audio worker's 5 ms poll, its ring buffer and the device's shared-mode buffer).
/// Video presentation follows the stream's audio by this much.
const OUTPUT_LATENCY: Duration = Duration::from_millis(40);

struct Input {
    id: u64,
    receive: Receiver<PlaybackFrame>,
    /// Playback percentage, 0..=200.
    volume: Arc<AtomicU16>,
    playout: Playout,
}

#[derive(Default)]
pub(crate) struct StreamMix {
    inputs: Mutex<Vec<Input>>,
    next_id: AtomicU64,
}

/// Removes its input from the mix when dropped (the watch ended).
pub(crate) struct Registration {
    mix: Weak<StreamMix>,
    id: u64,
}
impl Drop for Registration {
    fn drop(&mut self) {
        if let Some(mix) = self.mix.upgrade() {
            mix.lock().retain(|input| input.id != self.id);
        }
    }
}

impl StreamMix {
    fn lock(&self) -> std::sync::MutexGuard<'_, Vec<Input>> {
        self.inputs
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
    }

    /// Add one watched stream: its PCM goes into the returned sender (eight frames deep).
    pub fn register(
        self: &Arc<Self>,
        volume: Arc<AtomicU16>,
    ) -> (SyncSender<PlaybackFrame>, Registration) {
        let (send, receive) = sync_channel(8);
        let id = self.next_id.fetch_add(1, Ordering::Relaxed);
        self.lock().push(Input {
            id,
            receive,
            volume,
            playout: Playout::default(),
        });
        (
            send,
            Registration {
                mix: Arc::downgrade(self),
                id,
            },
        )
    }

    /// One call tick: add every watched stream to `call` (None when no participant spoke).
    /// While `enabled` is false (deafened, or the call is not secure) queued PCM is dropped.
    pub fn mix(&self, call: Option<Frame>, enabled: bool, stalled: bool) -> Option<Frame> {
        // Registration never blocks the media clock: a contended tick skips stream audio.
        let Ok(mut inputs) = self.inputs.try_lock() else {
            return call;
        };
        if inputs.is_empty() {
            return call;
        }
        let mut output = call;
        for input in inputs.iter_mut() {
            let volume = input.volume.load(Ordering::Relaxed);
            let Some(frame) = input.playout.next(&input.receive, volume, enabled, stalled) else {
                continue;
            };
            if let Some(presentation) = &frame.presentation {
                // Lock-free: lets the watched video follow this audio's estimated playout.
                presentation.played(Instant::now() + OUTPUT_LATENCY);
            }
            let mixed = output.get_or_insert([0.0; 960]);
            for (out, sample) in mixed.iter_mut().zip(frame.samples) {
                *out = (*out + sample).clamp(-1.0, 1.0);
            }
        }
        output
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn watched_audio_mixes_with_the_call_at_its_volume_and_leaves_with_its_watch() {
        let mix = Arc::new(StreamMix::default());
        assert_eq!(mix.mix(None, true, false), None);
        let volume = Arc::new(AtomicU16::new(50));
        let (send, registration) = mix.register(volume.clone());
        // The bridge starts after three frames of headroom.
        for _ in 0..3 {
            send.send([0.4; 960].into()).unwrap();
        }
        let mixed = mix.mix(Some([0.1; 960]), true, false).unwrap();
        assert!((mixed[0] - 0.3).abs() < 1e-6, "{}", mixed[0]);
        let alone = mix.mix(None, true, false).unwrap();
        assert!((alone[0] - 0.2).abs() < 1e-6);
        // Deafened: queued stream audio is dropped, the call frame passes through.
        assert_eq!(mix.mix(Some([0.0; 960]), false, false), Some([0.0; 960]));
        volume.store(0, Ordering::Relaxed);
        for _ in 0..3 {
            send.send([0.4; 960].into()).unwrap();
        }
        assert_eq!(mix.mix(None, true, false), None);
        drop(registration);
        assert!(mix.lock().is_empty());
    }
}