From e1abd7d060f28bcf2328e68452cfcc19cc166143 Mon Sep 17 00:00:00 2001 From: mnovak Date: Fri, 4 Dec 2026 12:20:55 +0100 Subject: [PATCH] [domistream] Audio packetizer: tests first (round trips through AudioDepacketizer, wrap-around, caps, fixed vectors), API stubs --- crates/domistream/src/audio/mod.rs | 13 + crates/domistream/src/audio/packetizer.rs | 79 ++++++ crates/domistream/tests/audio_packetizer.rs | 255 ++++++++++++++++++++ 3 files changed, 347 insertions(+) create mode 100644 crates/domistream/src/audio/packetizer.rs create mode 100644 crates/domistream/tests/audio_packetizer.rs diff --git a/crates/domistream/src/audio/mod.rs b/crates/domistream/src/audio/mod.rs index 49bcbe5..7dc2b1b 100644 --- a/crates/domistream/src/audio/mod.rs +++ b/crates/domistream/src/audio/mod.rs @@ -18,8 +18,10 @@ use crate::util::malformed; use crate::{Error, Instant, Result, SessionKeys}; pub mod packet; +pub mod packetizer; pub use packet::{AudioFecHeader, AudioPacket, parse_audio_packet}; +pub use packetizer::{AudioPacketizer, AudioPacketizerConfig, AudioParity}; /// Data packets per FEC block. pub const DATA_SHARDS: usize = 4; @@ -78,6 +80,17 @@ impl AudioCipher { } } +impl AudioCipher { + /// Encrypts one payload (host side). + /// + /// # Errors + /// [`Error::Unimplemented`] (stub). + pub fn encrypt(&self, sequence: u16, plaintext: &[u8]) -> Result> { + let _ = (sequence, plaintext, &self.key); + Err(Error::Unimplemented) + } +} + impl fmt::Debug for AudioCipher { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str("AudioCipher()") diff --git a/crates/domistream/src/audio/packetizer.rs b/crates/domistream/src/audio/packetizer.rs new file mode 100644 index 0000000..5f373d3 --- /dev/null +++ b/crates/domistream/src/audio/packetizer.rs @@ -0,0 +1,79 @@ +//! The audio send path, host side (`docs/PROTOCOL.md` 6.2, 6.3): one Opus packet → one RTP datagram. +//! +//! Stub: the API is fixed and tested first; the bodies follow. + +use super::AudioCipher; +use crate::{Error, Result}; + +/// Largest Opus packet sent in the clear: the datagram cap minus the RTP header. +pub const MAX_OPUS_PLAIN_BYTES: usize = super::packet::MAX_AUDIO_PACKET_BYTES - crate::rtp::RTP_HEADER_LEN; +/// Largest Opus packet sent encrypted: PKCS#7 always adds 1 to 16 bytes, and the ciphertext must fit the cap. +pub const MAX_OPUS_ENCRYPTED_BYTES: usize = MAX_OPUS_PLAIN_BYTES / 16 * 16 - 1; + +/// Which audio parity packets are sent. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +#[non_exhaustive] +pub enum AudioParity { + /// None. + #[default] + None, +} + +/// Settings of the audio sender. +#[derive(Clone, Debug)] +pub struct AudioPacketizerConfig { + /// Encrypt payloads with this cipher. + pub cipher: Option, + /// Packet duration in milliseconds (`x-nv-aqos.packetDuration`). + pub packet_duration_ms: u8, + /// Parity packets. + pub parity: AudioParity, + /// RTP sequence number of the first packet. + pub first_sequence: u16, + /// RTP timestamp (milliseconds) of the first packet. + pub first_timestamp_ms: u32, +} + +/// The audio sender of one stream. +#[derive(Debug)] +pub struct AudioPacketizer { + config: AudioPacketizerConfig, +} + +impl AudioPacketizer { + /// A sender for one stream. + /// + /// # Errors + /// [`Error::Unimplemented`] (stub). + pub fn new(config: AudioPacketizerConfig) -> Result { + let _ = config; + Err(Error::Unimplemented) + } + + /// The largest Opus packet accepted. + #[must_use] + pub const fn max_opus_len(&self) -> usize { + 0 + } + + /// Packetizes one Opus packet. + /// + /// # Errors + /// [`Error::Unimplemented`] (stub). + pub fn packetize(&mut self, opus: &[u8]) -> Result>> { + let _ = (opus, &self.config); + Err(Error::Unimplemented) + } + + /// The RTP sequence number of the next packet. + #[must_use] + pub const fn next_sequence(&self) -> u16 { + 0 + } + + /// The RTP timestamp (milliseconds) of the next packet. + #[must_use] + pub const fn next_timestamp_ms(&self) -> u32 { + 0 + } +} diff --git a/crates/domistream/tests/audio_packetizer.rs b/crates/domistream/tests/audio_packetizer.rs new file mode 100644 index 0000000..6704cf6 --- /dev/null +++ b/crates/domistream/tests/audio_packetizer.rs @@ -0,0 +1,255 @@ +//! 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]) -> Vec { + 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 { + 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], duration: u8) -> (Vec>, Vec) { + 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, 0x0102, 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, 0x02, // sequence 0x0102, 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()), (0x0103, 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> = (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> = (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, 0xFFFE, 100, 10); + let mut seen = Vec::new(); + for _ in 0..4 { + 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![(0xFFFE, 100), (0xFFFF, 110), (0x0000, 120), (0x0001, 130)]); +} + +#[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> = (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, 5, 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"); + assert_eq!(AudioParity::default(), AudioParity::None); +} + +// ================================================================================================ generated + +proptest! { + #![proptest_config(ProptestConfig { cases: 64, ..ProptestConfig::default() })] + + #[test] + fn generated_round_trips( + seed in any::(), + first_sequence in any::(), + first_ts in any::(), + duration in 1u8..=40, + count in 1usize..80, + encrypt in any::(), + ) { + let mut rng = SeqRng::new(seed); + let mut tx = sender(encrypt, first_sequence, first_ts, duration); + let max = tx.max_opus_len(); + let payloads: Vec> = (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); + } +}