262 lines
11 KiB
Rust
262 lines
11 KiB
Rust
//! The audio packetizer, host side (`docs/PROTOCOL.md` 6.2, 6.3), checked against the client half: Opus packets
|
|
//! go through the crate's own `AudioDepacketizer` with the session keys and must come out identical, in order,
|
|
//! with the millisecond timestamps of 6.2, across sequence and timestamp wrap-around. A fixed vector checks one
|
|
//! datagram byte by byte; the cipher is checked against the openssl vectors. No parity packets are sent (U16).
|
|
|
|
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::indexing_slicing, missing_docs)]
|
|
|
|
mod common;
|
|
|
|
use core::time::Duration;
|
|
|
|
use common::SeqRng;
|
|
use domistream::audio::packet::{MAX_AUDIO_PACKET_BYTES, parse_audio_packet};
|
|
use domistream::audio::packetizer::{MAX_OPUS_ENCRYPTED_BYTES, MAX_OPUS_PLAIN_BYTES};
|
|
use domistream::audio::{
|
|
AudioCipher, AudioConfig, AudioDepacketizer, AudioEvent, AudioFec, AudioPacket, AudioPacketizer,
|
|
AudioPacketizerConfig, AudioParity,
|
|
};
|
|
use domistream::{Error, Instant, SessionKeys};
|
|
use proptest::prelude::*;
|
|
|
|
const KEY: [u8; 16] = *b"audio-pack-key!!";
|
|
const RIKEYID: u32 = 0xFFFF_FFF0; // rikeyid + sequence wraps inside the tests
|
|
|
|
fn keys() -> SessionKeys {
|
|
SessionKeys { rikey: KEY, rikeyid: RIKEYID }
|
|
}
|
|
|
|
fn cfg(encrypt: bool, first_sequence: u16, first_timestamp_ms: u32, duration: u8) -> AudioPacketizerConfig {
|
|
AudioPacketizerConfig {
|
|
cipher: encrypt.then(|| AudioCipher::new(&keys())),
|
|
packet_duration_ms: duration,
|
|
parity: AudioParity::None,
|
|
first_sequence,
|
|
first_timestamp_ms,
|
|
}
|
|
}
|
|
|
|
fn sender(encrypt: bool, first_sequence: u16, first_timestamp_ms: u32, duration: u8) -> AudioPacketizer {
|
|
AudioPacketizer::new(cfg(encrypt, first_sequence, first_timestamp_ms, duration)).expect("AudioPacketizer::new")
|
|
}
|
|
|
|
fn receiver(encrypt: bool, duration: u8) -> AudioDepacketizer {
|
|
AudioDepacketizer::new(AudioConfig {
|
|
cipher: encrypt.then(|| AudioCipher::new(&keys())),
|
|
packet_duration_ms: duration,
|
|
fec: AudioFec::Disabled,
|
|
loss_timeout: Duration::from_millis(40),
|
|
})
|
|
.expect("AudioDepacketizer::new")
|
|
}
|
|
|
|
fn receive(rx: &mut AudioDepacketizer, datagrams: &[Vec<u8>]) -> Vec<AudioEvent> {
|
|
let mut now = 1_000_000u64;
|
|
let mut events = Vec::new();
|
|
for d in datagrams {
|
|
rx.push(Instant::from_micros(now), d).expect("push never fails within the size cap");
|
|
now += 5_000;
|
|
while let Some(e) = rx.poll_event() {
|
|
events.push(e);
|
|
}
|
|
}
|
|
for _ in 0..64 {
|
|
now += 1_000_000;
|
|
rx.handle_timeout(Instant::from_micros(now)).unwrap();
|
|
while let Some(e) = rx.poll_event() {
|
|
events.push(e);
|
|
}
|
|
if rx.poll_timeout().is_none() {
|
|
break;
|
|
}
|
|
}
|
|
events
|
|
}
|
|
|
|
/// One Opus-sized payload: 1 to 1275 bytes (one Opus frame's maximum, RFC 6716), occasionally up to `max`.
|
|
fn opus(rng: &mut SeqRng, max: usize) -> Vec<u8> {
|
|
let len = if rng.below(20) == 0 { 1 + rng.below(max) } else { 1 + rng.below(1275) };
|
|
rng.bytes(len)
|
|
}
|
|
|
|
/// Packetizes `payloads` and returns (datagrams, the events a lossless receiver must report).
|
|
fn send(tx: &mut AudioPacketizer, payloads: &[Vec<u8>], duration: u8) -> (Vec<Vec<u8>>, Vec<AudioEvent>) {
|
|
let mut datagrams = Vec::new();
|
|
let mut want = Vec::new();
|
|
for o in payloads {
|
|
let (seq, ts) = (tx.next_sequence(), tx.next_timestamp_ms());
|
|
let out = tx.packetize(o).expect("packetize");
|
|
assert_eq!(out.len(), 1, "AudioParity::None: one datagram per Opus packet, no parity");
|
|
assert_eq!(tx.next_sequence(), seq.wrapping_add(1));
|
|
assert_eq!(tx.next_timestamp_ms(), ts.wrapping_add(u32::from(duration)));
|
|
datagrams.extend(out);
|
|
want.push(AudioEvent::Packet { sequence: seq, timestamp_ms: ts, opus: o.clone(), recovered: false });
|
|
}
|
|
(datagrams, want)
|
|
}
|
|
|
|
// ================================================================================================ fixed vectors
|
|
|
|
#[test]
|
|
fn fixed_vector_plaintext() {
|
|
let mut tx = sender(false, 0x0104, 0x0A0B_0C0D, 5);
|
|
let out = tx.packetize(&[0xFC, 0xFF, 0xFE]).unwrap();
|
|
#[rustfmt::skip]
|
|
let want = vec![
|
|
0x80, // RTP byte 0: version 2, no extension (6.2)
|
|
0x61, // payload type 97
|
|
0x01, 0x04, // sequence 0x0104, BE
|
|
0x0A, 0x0B, 0x0C, 0x0D, // timestamp (milliseconds), BE
|
|
0x00, 0x00, 0x00, 0x00, // SSRC 0
|
|
0xFC, 0xFF, 0xFE, // the Opus packet
|
|
];
|
|
assert_eq!(out, vec![want]);
|
|
assert_eq!((tx.next_sequence(), tx.next_timestamp_ms()), (0x0105, 0x0A0B_0C12));
|
|
}
|
|
|
|
#[test]
|
|
fn fixed_vector_encrypted() {
|
|
// Header as above; the payload is AES-128-CBC + PKCS#7 with IV = BE(rikeyid + sequence) || 12 zero bytes (6.3),
|
|
// here computed by the RustCrypto test oracle (itself checked against openssl in media.rs).
|
|
let mut tx = sender(true, 0x0020, 7, 10);
|
|
let opus = [0x11u8; 20];
|
|
let out = tx.packetize(&opus).unwrap();
|
|
let mut want = vec![0x80, 0x61, 0x00, 0x20, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x00];
|
|
want.extend(common::audio_encrypt(&KEY, RIKEYID, 0x0020, &opus));
|
|
assert_eq!(out, vec![want]);
|
|
assert_eq!(out[0].len(), 12 + 32, "20 bytes pad to 32");
|
|
}
|
|
|
|
#[test]
|
|
fn audio_cipher_encrypt_matches_openssl_vectors() {
|
|
let v = common::audio_vectors();
|
|
for name in ["a_0", "a_1", "a_ffff", "a_wrap", "a_exact_block", "a_one_byte"] {
|
|
let rikeyid = v.u32_hex(&format!("{name}_rikeyid"));
|
|
let seq = u16::from_str_radix(v.str(&format!("{name}_sequence")), 16).unwrap();
|
|
let c = AudioCipher::new(&SessionKeys { rikey: v.arr16("key"), rikeyid });
|
|
assert_eq!(
|
|
c.encrypt(seq, &v.bytes(&format!("{name}_plain"))).unwrap(),
|
|
v.bytes(&format!("{name}_cipher")),
|
|
"{name}"
|
|
);
|
|
}
|
|
}
|
|
|
|
// ================================================================================================ round trips
|
|
|
|
#[test]
|
|
fn round_trip_encrypted_across_sequence_and_timestamp_wrap() {
|
|
let mut rng = SeqRng::new(1);
|
|
// Sequence 0xFF00 wraps after 256 packets; the timestamp wraps too; rikeyid + sequence wraps in the IV.
|
|
let mut tx = sender(true, 0xFF00, u32::MAX - 1000, 20);
|
|
let payloads: Vec<Vec<u8>> = (0..600).map(|_| opus(&mut rng, MAX_OPUS_ENCRYPTED_BYTES)).collect();
|
|
let (datagrams, want) = send(&mut tx, &payloads, 20);
|
|
assert_eq!(receive(&mut receiver(true, 20), &datagrams), want);
|
|
}
|
|
|
|
#[test]
|
|
fn round_trip_plaintext() {
|
|
let mut rng = SeqRng::new(2);
|
|
let mut tx = sender(false, 0, 0, 5);
|
|
let payloads: Vec<Vec<u8>> = (0..300).map(|_| opus(&mut rng, MAX_OPUS_PLAIN_BYTES)).collect();
|
|
let (datagrams, want) = send(&mut tx, &payloads, 5);
|
|
for d in &datagrams {
|
|
assert!(matches!(parse_audio_packet(d), Ok(AudioPacket::Data { .. })));
|
|
}
|
|
assert_eq!(receive(&mut receiver(false, 5), &datagrams), want);
|
|
}
|
|
|
|
#[test]
|
|
fn sequence_wraps_from_ffff_to_0() {
|
|
let mut tx = sender(true, 0xFFFC, 100, 10);
|
|
let mut seen = Vec::new();
|
|
for _ in 0..6 {
|
|
let d = tx.packetize(&[1, 2, 3]).unwrap().remove(0);
|
|
let Ok(AudioPacket::Data { rtp, .. }) = parse_audio_packet(&d) else { panic!("data packet") };
|
|
seen.push((rtp.sequence, rtp.timestamp));
|
|
}
|
|
assert_eq!(seen, vec![(0xFFFC, 100), (0xFFFD, 110), (0xFFFE, 120), (0xFFFF, 130), (0x0000, 140), (0x0001, 150)]);
|
|
}
|
|
|
|
#[test]
|
|
fn lost_packets_are_reported_and_the_rest_arrive() {
|
|
let mut rng = SeqRng::new(3);
|
|
let mut tx = sender(true, 0x1000, 0, 5);
|
|
let payloads: Vec<Vec<u8>> = (0..200).map(|_| opus(&mut rng, 400)).collect();
|
|
let (datagrams, want) = send(&mut tx, &payloads, 5);
|
|
let mut kept = Vec::new();
|
|
let mut expect = Vec::new();
|
|
for (i, (d, w)) in datagrams.into_iter().zip(want).enumerate() {
|
|
if i > 0 && i < 199 && rng.below(10) == 0 {
|
|
let AudioEvent::Packet { sequence, .. } = w else { unreachable!() };
|
|
expect.push(AudioEvent::Lost { sequence });
|
|
} else {
|
|
kept.push(d);
|
|
expect.push(w);
|
|
}
|
|
}
|
|
assert_eq!(receive(&mut receiver(true, 5), &kept), expect);
|
|
}
|
|
|
|
// ================================================================================================ refusals
|
|
|
|
#[test]
|
|
fn size_caps() {
|
|
assert_eq!(MAX_OPUS_PLAIN_BYTES, MAX_AUDIO_PACKET_BYTES - 12);
|
|
assert_eq!(MAX_OPUS_ENCRYPTED_BYTES, 2031, "2031 bytes pad to 2032; 12 + 2032 = 2044 <= 2048");
|
|
for (encrypt, max) in [(false, MAX_OPUS_PLAIN_BYTES), (true, MAX_OPUS_ENCRYPTED_BYTES)] {
|
|
let mut tx = sender(encrypt, 4, 50, 5);
|
|
assert_eq!(tx.max_opus_len(), max);
|
|
let state = (tx.next_sequence(), tx.next_timestamp_ms());
|
|
assert_err!(tx.packetize(&[]), Error::Truncated { .. }, "an Opus packet has at least its TOC byte");
|
|
assert_too_large!(tx.packetize(&vec![7; max + 1]), max, max + 1);
|
|
assert_too_large!(tx.packetize(&vec![7; 100_000]), max, 100_000);
|
|
assert_eq!((tx.next_sequence(), tx.next_timestamp_ms()), state, "a refused packet changes nothing");
|
|
// The largest packet fits the receiver's datagram cap and comes back.
|
|
let (datagrams, want) = send(&mut tx, &[vec![9; max], vec![8; 1]], 5);
|
|
assert!(datagrams[0].len() <= MAX_AUDIO_PACKET_BYTES);
|
|
assert_eq!(receive(&mut receiver(encrypt, 5), &datagrams), want);
|
|
}
|
|
let c = AudioCipher::new(&keys());
|
|
assert_too_large!(
|
|
c.encrypt(0, &vec![0; MAX_AUDIO_PACKET_BYTES + 1]),
|
|
MAX_AUDIO_PACKET_BYTES,
|
|
MAX_AUDIO_PACKET_BYTES + 1
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn config_refusals() {
|
|
assert_err!(AudioPacketizer::new(cfg(true, 0, 0, 0)), Error::Malformed { .. }, "zero packet duration");
|
|
// Blocks start at multiples of 4 (6.4), and the receiver counts from the first block's start: a stream that
|
|
// began at 5 would make it report 4 as lost.
|
|
for first in [1u16, 2, 3, 5, 0xFFFF] {
|
|
assert_err!(AudioPacketizer::new(cfg(true, first, 0, 5)), Error::Malformed { .. }, "first sequence {first}");
|
|
}
|
|
assert!(AudioPacketizer::new(cfg(true, 0xFFFC, 0, 5)).is_ok());
|
|
assert_eq!(AudioParity::default(), AudioParity::None);
|
|
}
|
|
|
|
// ================================================================================================ generated
|
|
|
|
proptest! {
|
|
#![proptest_config(ProptestConfig { cases: 64, ..ProptestConfig::default() })]
|
|
|
|
#[test]
|
|
fn generated_round_trips(
|
|
seed in any::<u64>(),
|
|
first_sequence in any::<u16>(),
|
|
first_ts in any::<u32>(),
|
|
duration in 1u8..=40,
|
|
count in 1usize..80,
|
|
encrypt in any::<bool>(),
|
|
) {
|
|
let mut rng = SeqRng::new(seed);
|
|
let mut tx = sender(encrypt, first_sequence & !3, first_ts, duration);
|
|
let max = tx.max_opus_len();
|
|
let payloads: Vec<Vec<u8>> = (0..count).map(|_| opus(&mut rng, max)).collect();
|
|
let (datagrams, want) = send(&mut tx, &payloads, duration);
|
|
prop_assert_eq!(receive(&mut receiver(encrypt, duration), &datagrams), want);
|
|
}
|
|
}
|