Skip to content

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

2.3 KB
Raw Blame
// Adapted from Serein (https://github.com/ViceVerse-cz/Serein) at commit a0e72cc,
// file `crates/discord-voice/src/video_codec.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.
//
// RustCord changes: H.264 only (Serein's receive-only H.265/AV1 paths need its Linux
// hardware decoders), so the codec enum became free functions.
//! H.264 Annex-B inspection shared by the Go Live sender and viewer.

/// Whether the access unit carries an IDR slice.
pub(crate) fn is_keyframe(frame: &[u8]) -> bool {
    nals(frame).any(|nal| nal[0] & 31 == 5)
}

/// Whether the access unit carries both an SPS and a PPS, so a fresh decoder can start.
#[cfg(test)]
pub(crate) fn has_parameter_sets(frame: &[u8]) -> bool {
    let mut found = 0u8;
    for nal in nals(frame) {
        match nal[0] & 31 {
            7 => found |= 1,
            8 => found |= 2,
            _ => {}
        }
    }
    found == 3
}

/// Non-empty NAL units of an Annex-B access unit (3- or 4-byte start codes).
pub(crate) fn nals(frame: &[u8]) -> impl Iterator<Item = &[u8]> {
    let mut at = 0;
    std::iter::from_fn(move || {
        while let Some((start, size)) = start_code(frame, at) {
            let nal = start + size;
            at = start_code(frame, nal).map_or(frame.len(), |(end, _)| end);
            if at > nal {
                return Some(&frame[nal..at]);
            }
        }
        None
    })
}

fn start_code(frame: &[u8], mut at: usize) -> Option<(usize, usize)> {
    while at + 3 <= frame.len() {
        if frame[at..].starts_with(&[0, 0, 0, 1]) {
            return Some((at, 4));
        }
        if frame[at..].starts_with(&[0, 0, 1]) {
            return Some((at, 3));
        }
        at += 1;
    }
    None
}

#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn nal_inspection_finds_idr_and_parameter_sets() {
        let frame = [0, 0, 0, 1, 0x67, 1, 0, 0, 1, 0x68, 2, 0, 0, 0, 1, 0x65, 7];
        assert_eq!(
            nals(&frame).collect::<Vec<_>>(),
            [&[0x67, 1][..], &[0x68, 2], &[0x65, 7]]
        );
        assert!(is_keyframe(&frame) && has_parameter_sets(&frame));
        let delta = [0, 0, 0, 1, 0x41, 9];
        assert!(!is_keyframe(&delta) && !has_parameter_sets(&delta));
        assert_eq!(nals(&[0, 0, 0, 1]).count(), 0);
    }
}