pub trait RtcpRandom: Send + Sync {
fn next_u32(&mut self) -> u32;
fn unit(&mut self) -> f64 {
f64::from(self.next_u32()) / 4_294_967_296.0
}
}
#[derive(Clone)]
pub(crate) struct SharedRandom(pub(crate) std::sync::Arc<std::sync::Mutex<Box<dyn RtcpRandom>>>);
impl RtcpRandom for SharedRandom {
fn next_u32(&mut self) -> u32 {
match self.0.lock() {
Ok(mut random) => random.next_u32(),
Err(poisoned) => poisoned.into_inner().next_u32(),
}
}
}
#[derive(Debug, Default, Clone, Copy)]
pub(crate) struct ThreadRandom;
impl RtcpRandom for ThreadRandom {
fn next_u32(&mut self) -> u32 {
rand::random::<u32>()
}
}
const BASE64: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
pub(crate) fn generate_cname(random: &mut dyn RtcpRandom) -> String {
let mut octets = [0u8; 12];
for chunk in octets.chunks_mut(4) {
chunk.copy_from_slice(&random.next_u32().to_be_bytes());
}
let mut cname = String::with_capacity(16);
for triple in octets.chunks(3) {
let bits = u32::from(triple[0]) << 16 | u32::from(triple[1]) << 8 | u32::from(triple[2]);
for shift in [18, 12, 6, 0] {
cname.push(char::from(BASE64[((bits >> shift) & 0x3F) as usize]));
}
}
cname
}
pub fn generate_rtcp_cname() -> String {
generate_cname(&mut ThreadRandom)
}
pub(crate) fn choose_ssrc(random: &mut dyn RtcpRandom, in_use: impl Fn(u32) -> bool) -> u32 {
loop {
let candidate = random.next_u32();
if candidate != 0 && !in_use(candidate) {
return candidate;
}
}
}
#[cfg(test)]
mod tests {
use super::*;
struct Counter(u32);
impl RtcpRandom for Counter {
fn next_u32(&mut self) -> u32 {
self.0 = self.0.wrapping_add(1);
self.0
}
}
#[test]
fn a_cname_is_96_random_bits_in_base64() {
let cname = generate_cname(&mut ThreadRandom);
assert_eq!(16, cname.len());
assert!(
cname
.bytes()
.all(|b| b.is_ascii_alphanumeric() || b == b'+' || b == b'/')
);
assert!(!cname.contains('@'));
struct Foobar(u32);
impl RtcpRandom for Foobar {
fn next_u32(&mut self) -> u32 {
let words = [
u32::from_be_bytes(*b"foob"),
u32::from_be_bytes(*b"arfo"),
u32::from_be_bytes(*b"obar"),
];
self.0 += 1;
words[(self.0 as usize - 1) % 3]
}
}
assert_eq!("Zm9vYmFyZm9vYmFy", generate_cname(&mut Foobar(0)));
}
#[test]
fn two_cnames_differ() {
assert_ne!(
generate_cname(&mut ThreadRandom),
generate_cname(&mut ThreadRandom)
);
}
#[test]
fn a_chosen_ssrc_is_not_zero_and_not_in_use() {
assert_eq!(3, choose_ssrc(&mut Counter(0), |ssrc| ssrc < 3));
assert_eq!(1, choose_ssrc(&mut Counter(u32::MAX), |_| false));
}
#[test]
fn unit_is_in_the_half_open_interval() {
struct Fixed(u32);
impl RtcpRandom for Fixed {
fn next_u32(&mut self) -> u32 {
self.0
}
}
assert_eq!(0.0, Fixed(0).unit());
assert!(Fixed(u32::MAX).unit() < 1.0);
assert_eq!(0.5, Fixed(1 << 31).unit());
}
}