Skip to content

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

7.5 KB
Raw Blame
// RustCord's own (MIT OR Apache-2.0, like the rest of this crate). See crates/voice/NOTICE.md.
//! Go Live statistics: lock-free totals written by the media threads, turned into ~1 s
//! rates only when the application asks (so a stopped stream decays to zero by itself).
use std::{
    collections::VecDeque,
    sync::{
        Mutex,
        atomic::{AtomicU8, AtomicU32, AtomicU64, Ordering},
    },
    time::{Duration, Instant},
};

/// What is decoding (watching) or encoding (streaming).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(u8)]
pub(crate) enum Engine {
    Unknown = 0,
    MediaFoundationHardware = 1,
    MediaFoundation = 2,
    OpenH264 = 3,
}
impl Engine {
    pub fn name(self) -> &'static str {
        match self {
            Self::Unknown => "",
            Self::MediaFoundationHardware => "Media Foundation (hardware)",
            Self::MediaFoundation => "Media Foundation",
            Self::OpenH264 => "OpenH264",
        }
    }
    fn from_u8(value: u8) -> Self {
        match value {
            1 => Self::MediaFoundationHardware,
            2 => Self::MediaFoundation,
            3 => Self::OpenH264,
            _ => Self::Unknown,
        }
    }
}

/// Rates are measured over the newest snapshot at least this old.
const WINDOW: Duration = Duration::from_secs(1);
/// Shorter spans than this are too noisy; the previous rate is reported instead.
const MIN_SPAN: Duration = Duration::from_millis(250);
/// Snapshots are taken at most this often, which bounds the history.
const SPACING: Duration = Duration::from_millis(100);
const MAX_SNAPSHOTS: usize = 32;

#[derive(Clone, Copy)]
struct Snapshot {
    at: Instant,
    frames: u64,
    bytes: u64,
}

#[derive(Default)]
struct Rates {
    history: VecDeque<Snapshot>,
    fps: f32,
    kbps: u32,
}

/// One stream's counters. Writers only touch atomics; `snapshot` takes a short lock.
#[derive(Default)]
pub(crate) struct Counters {
    width: AtomicU32,
    height: AtomicU32,
    engine: AtomicU8,
    frames: AtomicU64,
    bytes: AtomicU64,
    dropped: AtomicU64,
    keyframe_requests: AtomicU64,
    rates: Mutex<Rates>,
}

impl Counters {
    /// The stream's size as sent, before any display downscale.
    pub fn set_size(&self, width: usize, height: usize) {
        self.width
            .store(u32::try_from(width).unwrap_or(0), Ordering::Relaxed);
        self.height
            .store(u32::try_from(height).unwrap_or(0), Ordering::Relaxed);
    }
    pub fn set_engine(&self, engine: Engine) {
        self.engine.store(engine as u8, Ordering::Relaxed);
    }
    pub fn engine(&self) -> Engine {
        Engine::from_u8(self.engine.load(Ordering::Relaxed))
    }
    /// One picture decoded (watching) or encoded and sent (streaming).
    pub fn frame(&self) {
        self.frames.fetch_add(1, Ordering::Relaxed);
    }
    /// Video bytes received or sent on the wire.
    pub fn bytes(&self, count: usize) {
        self.bytes.fetch_add(count as u64, Ordering::Relaxed);
    }
    pub fn dropped(&self, count: u64) {
        if count != 0 {
            self.dropped.fetch_add(count, Ordering::Relaxed);
        }
    }
    pub fn keyframe_request(&self) {
        self.keyframe_requests.fetch_add(1, Ordering::Relaxed);
    }

    pub fn snapshot(&self) -> crate::StreamStats {
        self.snapshot_at(Instant::now())
    }

    fn snapshot_at(&self, now: Instant) -> crate::StreamStats {
        let current = Snapshot {
            at: now,
            frames: self.frames.load(Ordering::Relaxed),
            bytes: self.bytes.load(Ordering::Relaxed),
        };
        let (fps, kbps) = {
            let mut rates = self
                .rates
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            rates.update(current);
            (rates.fps, rates.kbps)
        };
        crate::StreamStats {
            codec: "H264",
            width: self.width.load(Ordering::Relaxed),
            height: self.height.load(Ordering::Relaxed),
            fps,
            bitrate_kbps: kbps,
            engine: self.engine().name(),
            dropped: self.dropped.load(Ordering::Relaxed),
            keyframe_requests: self.keyframe_requests.load(Ordering::Relaxed),
        }
    }
}

impl Rates {
    fn update(&mut self, current: Snapshot) {
        // The newest snapshot at least a window old is the base; older ones are useless.
        let base = self
            .history
            .iter()
            .rposition(|old| current.at.saturating_duration_since(old.at) >= WINDOW)
            .unwrap_or(0);
        self.history.drain(..base);
        if let Some(base) = self.history.front().copied() {
            let span = current.at.saturating_duration_since(base.at);
            if span >= MIN_SPAN {
                let seconds = span.as_secs_f64();
                self.fps = (current.frames.saturating_sub(base.frames) as f64 / seconds) as f32;
                self.kbps = (current.bytes.saturating_sub(base.bytes) as f64 * 8.0
                    / 1000.0
                    / seconds)
                    .min(f64::from(u32::MAX)) as u32;
            }
        }
        if self
            .history
            .back()
            .is_none_or(|last| current.at.saturating_duration_since(last.at) >= SPACING)
        {
            if self.history.len() >= MAX_SNAPSHOTS {
                self.history.pop_front();
            }
            self.history.push_back(current);
        }
    }
}

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

    #[test]
    fn rates_average_about_a_second_and_decay_when_the_stream_stops() {
        let counters = Counters::default();
        let start = Instant::now();
        let at = |ms| start + Duration::from_millis(ms);
        counters.set_size(2560, 1440);
        counters.set_engine(Engine::MediaFoundationHardware);
        let first = counters.snapshot_at(at(0));
        assert_eq!(
            (first.codec, first.width, first.height, first.fps, first.bitrate_kbps),
            ("H264", 2560, 1440, 0.0, 0)
        );
        assert_eq!(first.engine, "Media Foundation (hardware)");
        // 60 pictures of 25 kB per second (12 Mbit/s), polled every frame by the UI.
        for frame in 1..=120u64 {
            counters.frame();
            counters.bytes(25_000);
            let stats = counters.snapshot_at(at(frame * 1000 / 60));
            if frame >= 60 {
                assert!((stats.fps - 60.0).abs() < 1.5, "{frame}: {}", stats.fps);
                assert!(
                    (11_700..=12_300).contains(&stats.bitrate_kbps),
                    "{frame}: {}",
                    stats.bitrate_kbps
                );
            }
        }
        let held = counters
            .rates
            .lock()
            .unwrap()
            .history
            .len();
        assert!(held <= 12, "{held}");
        // Nothing new: within a couple of seconds the rates fall to zero.
        let idle = counters.snapshot_at(at(4000));
        assert_eq!((idle.fps, idle.bitrate_kbps), (0.0, 0));
        counters.dropped(3);
        counters.dropped(0);
        counters.keyframe_request();
        let totals = counters.snapshot_at(at(4100));
        assert_eq!((totals.dropped, totals.keyframe_requests), (3, 1));
        // A rarely polling application still gets the average since its previous call.
        let sparse = Counters::default();
        sparse.snapshot_at(at(0));
        for _ in 0..90 {
            sparse.frame();
        }
        assert!((sparse.snapshot_at(at(3000)).fps - 30.0).abs() < 0.01);
        assert_eq!(Engine::from_u8(9).name(), "");
    }
}