use std::time::SystemTime;
use std::time::UNIX_EPOCH;
use bytes::Bytes;
pub const ABS_CAPTURE_TIME_URI: &str =
"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time";
const NTP_UNIX_OFFSET_SECS: u64 = 2_208_988_800;
fn ulaw_to_linear(byte: u8) -> i16 {
let u = !byte;
let sign = u & 0x80;
let exponent = (u >> 4) & 0x07;
let mantissa = (u & 0x0F) as i32;
let magnitude = (((mantissa << 3) + 0x84) << exponent) - 0x84;
(if sign != 0 { -magnitude } else { magnitude }) as i16
}
fn alaw_to_linear(byte: u8) -> i16 {
let a = byte ^ 0x55;
let segment = (a >> 4) & 0x07;
let mut t = ((a & 0x0F) as i32) << 4;
match segment {
0 => t += 8,
1 => t += 0x108,
s => {
t += 0x108;
t <<= s - 1;
}
}
(if a & 0x80 != 0 { t } else { -t }) as i16
}
fn level_of(samples: impl Iterator<Item = i16>) -> Option<u8> {
let mut count = 0usize;
let mut sum = 0f64;
for s in samples {
let v = s as f64 / 32768.0;
sum += v * v;
count += 1;
}
if count == 0 {
return None;
}
let rms = (sum / count as f64).sqrt();
if rms <= 0.0 {
return Some(127);
}
Some((-20.0 * rms.log10()).round().clamp(0.0, 127.0) as u8)
}
pub fn audio_level(mime_type: &str, frame: &[u8]) -> Option<u8> {
match mime_type.to_ascii_lowercase().as_str() {
"audio/pcmu" => level_of(frame.iter().map(|b| ulaw_to_linear(*b))),
"audio/pcma" => level_of(frame.iter().map(|b| alaw_to_linear(*b))),
"audio/opus" => {
let (opus, _) = crate::fake_media::clip("audio/opus", false)?;
let index = opus.iter().position(|f| *f == frame)?;
let (pcmu, _) = crate::fake_media::clip("audio/pcmu", false)?;
let twin = pcmu.get(index)?;
level_of(twin.iter().map(|b| ulaw_to_linear(*b)))
}
_ => None,
}
}
pub fn audio_level_payload(level: u8) -> Bytes {
Bytes::copy_from_slice(&[level & 0x7F])
}
pub fn abs_capture_time_payload(now: SystemTime) -> Option<Bytes> {
let since = now.duration_since(UNIX_EPOCH).unwrap_or_default();
let seconds = since.as_secs().wrapping_add(NTP_UNIX_OFFSET_SECS);
let fraction = ((since.subsec_nanos() as u64) << 32) / 1_000_000_000;
let ntp = (seconds << 32) | (fraction & 0xFFFF_FFFF);
if rtci::shared::time::near_leap_second(ntp) {
return None;
}
let mut out = [0u8; 16];
out[..8].copy_from_slice(&ntp.to_be_bytes());
Some(Bytes::copy_from_slice(&out))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn g711_decodes_to_the_expected_extremes() {
assert_eq!(ulaw_to_linear(0xFF), 0);
assert_eq!(ulaw_to_linear(0x00), -32124);
assert_eq!(ulaw_to_linear(0x80), 32124);
assert_eq!(alaw_to_linear(0xD5), 8);
assert_eq!(alaw_to_linear(0x55), -8);
assert_eq!(alaw_to_linear(0xAA), 32256);
}
#[test]
fn the_fake_microphone_tone_is_about_21_dbov() {
let (pcmu, _) = crate::fake_media::clip("audio/pcmu", false).unwrap();
let level = audio_level("audio/PCMU", pcmu[10]).unwrap();
assert!((20..=22).contains(&level), "{level}");
let (opus, _) = crate::fake_media::clip("audio/opus", false).unwrap();
assert_eq!(audio_level("audio/opus", opus[10]), Some(level));
assert_eq!(audio_level("audio/opus", &[0x78, 1, 2, 3]), None);
assert_eq!(level_of([0i16; 160].into_iter()), Some(127));
}
#[test]
fn abs_capture_time_is_ntp_with_a_zero_offset() {
let t = UNIX_EPOCH + std::time::Duration::from_millis(1500);
let payload = abs_capture_time_payload(t).unwrap();
assert_eq!(payload.len(), 16);
let ntp = u64::from_be_bytes(payload[..8].try_into().unwrap());
assert_eq!(ntp >> 32, NTP_UNIX_OFFSET_SECS + 1);
assert_eq!(ntp & 0xFFFF_FFFF, 1 << 31);
assert_eq!(&payload[8..], &[0u8; 8]);
}
#[test]
fn no_abs_capture_time_around_the_end_of_a_month() {
let midnight = UNIX_EPOCH + std::time::Duration::from_secs(1_769_904_000);
let at = |offset_ms: i64| {
let t = if offset_ms < 0 {
midnight - std::time::Duration::from_millis(offset_ms.unsigned_abs())
} else {
midnight + std::time::Duration::from_millis(offset_ms as u64)
};
abs_capture_time_payload(t)
};
assert!(at(-1500).is_some());
assert!(at(-500).is_none());
assert!(at(500).is_none());
assert!(at(1500).is_some());
}
}