diff --git a/crates/domistream/src/audio/mod.rs b/crates/domistream/src/audio/mod.rs index 7dc2b1b..6066d82 100644 --- a/crates/domistream/src/audio/mod.rs +++ b/crates/domistream/src/audio/mod.rs @@ -11,7 +11,7 @@ use core::fmt; use std::collections::{HashMap, VecDeque}; use cbc::cipher::block_padding::Pkcs7; -use cbc::cipher::{BlockModeDecrypt, KeyIvInit}; +use cbc::cipher::{BlockModeDecrypt, BlockModeEncrypt, KeyIvInit}; use crate::fec::ReedSolomon; use crate::util::malformed; @@ -81,13 +81,26 @@ impl AudioCipher { } impl AudioCipher { - /// Encrypts one payload (host side). + /// Encrypts one payload (host side), the exact mirror of [`Self::decrypt`]: AES-128-CBC with the IV of + /// [`Self::iv`] and PKCS#7 padding, so the ciphertext is the plaintext length rounded up to the next multiple of + /// 16, always 1 to 16 bytes longer (`docs/PROTOCOL.md` 6.3). /// /// # Errors - /// [`Error::Unimplemented`] (stub). + /// [`Error::TooLarge`] over [`packet::MAX_AUDIO_PACKET_BYTES`] (checked before anything is allocated), + /// [`Error::Crypto`] if the cipher refuses (never for a buffer sized as here). pub fn encrypt(&self, sequence: u16, plaintext: &[u8]) -> Result> { - let _ = (sequence, plaintext, &self.key); - Err(Error::Unimplemented) + crate::util::cap("audio plaintext", packet::MAX_AUDIO_PACKET_BYTES, plaintext.len())?; + let iv = self.iv(sequence)?; + let mut buf = vec![0u8; (plaintext.len() / 16 + 1) * 16]; + for (dst, src) in buf.iter_mut().zip(plaintext) { + *dst = *src; + } + let len = cbc::Encryptor::::new((&*self.key).into(), &iv.into()) + .encrypt_padded::(&mut buf, plaintext.len()) + .map_err(|_| Error::Crypto)? + .len(); + buf.truncate(len); + Ok(buf) } } diff --git a/crates/domistream/src/audio/packetizer.rs b/crates/domistream/src/audio/packetizer.rs index 5f373d3..2599fe8 100644 --- a/crates/domistream/src/audio/packetizer.rs +++ b/crates/domistream/src/audio/packetizer.rs @@ -1,20 +1,36 @@ -//! The audio send path, host side (`docs/PROTOCOL.md` 6.2, 6.3): one Opus packet → one RTP datagram. +//! The audio send path, host side (`docs/PROTOCOL.md` 6.2, 6.3): one Opus packet → one RTP datagram, the mirror of +//! [`super::AudioDepacketizer`] and tested against it. //! -//! Stub: the API is fixed and tested first; the bodies follow. +//! Each datagram is the 12-byte RTP header (byte 0 `0x80`, payload type 97, sequence BE, timestamp BE in +//! milliseconds, SSRC 0) followed by the Opus packet, AES-128-CBC encrypted with [`AudioCipher::encrypt`] when a +//! cipher is set (6.3: IV from `rikeyid + sequence`, PKCS#7). Sequence numbers count up by one per packet and the +//! timestamp by the packet duration, both wrapping. +//! +//! **No parity packets** (6.4): the audio parity matrix is UNKNOWN U16, and the only value seen has GPL provenance, +//! so [`AudioParity`] has a single variant, [`AudioParity::None`], and clients conceal lost packets. The enum is +//! `#[non_exhaustive]` and [`AudioPacketizer::packetize`] returns a list of datagrams, so a measured matrix can be +//! added later as a new variant that appends the 2 parity datagrams after every block's 4th data packet without +//! changing callers. Blocks start at sequence numbers that are multiples of 4 (6.4), so `first_sequence` must be one +//! already (the client's receiver also counts from the first packet's block start). use super::AudioCipher; -use crate::{Error, Result}; +use super::packet::{AUDIO_PAYLOAD_TYPE, MAX_AUDIO_PACKET_BYTES}; +use crate::Result; +use crate::rtp::RTP_HEADER_LEN; +use crate::util::{cap, malformed, need}; -/// 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; +/// Byte 0 of every audio RTP header: version 2, no padding, extension or CSRC (`docs/PROTOCOL.md` 6.2). +pub const AUDIO_RTP_BYTE0: u8 = 0x80; +/// Largest Opus packet sent in the clear: the receiver's datagram cap minus the RTP header. +pub const MAX_OPUS_PLAIN_BYTES: usize = MAX_AUDIO_PACKET_BYTES - 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. +/// Which audio parity packets are sent (`docs/PROTOCOL.md` 6.4). #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum AudioParity { - /// None. + /// None: the parity matrix is UNKNOWN U16 (GPL-provenance, unsettled), so clients conceal lost packets. #[default] None, } @@ -22,13 +38,13 @@ pub enum AudioParity { /// Settings of the audio sender. #[derive(Clone, Debug)] pub struct AudioPacketizerConfig { - /// Encrypt payloads with this cipher. + /// Encrypt payloads with this cipher (audio encryption negotiated, or always: UNKNOWN U17). pub cipher: Option, - /// Packet duration in milliseconds (`x-nv-aqos.packetDuration`). + /// Packet duration in milliseconds (`x-nv-aqos.packetDuration`): the timestamp step. pub packet_duration_ms: u8, /// Parity packets. pub parity: AudioParity, - /// RTP sequence number of the first packet. + /// RTP sequence number of the first packet: a multiple of 4, the start of an FEC block (6.4). pub first_sequence: u16, /// RTP timestamp (milliseconds) of the first packet. pub first_timestamp_ms: u32, @@ -38,42 +54,71 @@ pub struct AudioPacketizerConfig { #[derive(Debug)] pub struct AudioPacketizer { config: AudioPacketizerConfig, + next_sequence: u16, + next_timestamp_ms: u32, } impl AudioPacketizer { /// A sender for one stream. /// /// # Errors - /// [`Error::Unimplemented`] (stub). + /// [`crate::Error::Malformed`] for a zero packet duration or a `first_sequence` that is not a multiple of 4: FEC + /// blocks start at multiples of 4 (6.4), and the client's receiver counts from the start of the first packet's + /// block, so a stream starting mid-block would show it 1 to 3 phantom losses. pub fn new(config: AudioPacketizerConfig) -> Result { - let _ = config; - Err(Error::Unimplemented) + if config.packet_duration_ms == 0 { + return Err(malformed("audio packet duration")); + } + if !config.first_sequence.is_multiple_of(4) { + return Err(malformed("audio first sequence is not a block start (a multiple of 4)")); + } + Ok(Self { next_sequence: config.first_sequence, next_timestamp_ms: config.first_timestamp_ms, config }) } - /// The largest Opus packet accepted. + /// The largest Opus packet accepted: [`MAX_OPUS_ENCRYPTED_BYTES`] with a cipher, else [`MAX_OPUS_PLAIN_BYTES`]. #[must_use] pub const fn max_opus_len(&self) -> usize { - 0 + if self.config.cipher.is_some() { MAX_OPUS_ENCRYPTED_BYTES } else { MAX_OPUS_PLAIN_BYTES } } - /// Packetizes one Opus packet. + /// Packetizes one Opus packet into the datagrams to send now, in order: today exactly one (no parity, see + /// [`AudioParity`]). On error nothing changes (sequence number, timestamp). /// /// # Errors - /// [`Error::Unimplemented`] (stub). + /// [`crate::Error::Truncated`] for an empty packet (Opus packets carry at least their TOC byte, RFC 6716), + /// [`crate::Error::TooLarge`] over [`Self::max_opus_len`] (checked before anything is allocated), + /// [`crate::Error::Crypto`] if the cipher refuses. pub fn packetize(&mut self, opus: &[u8]) -> Result>> { - let _ = (opus, &self.config); - Err(Error::Unimplemented) + const W: &str = "opus packet"; + need(W, 1, opus.len())?; + cap(W, self.max_opus_len(), opus.len())?; + let (sequence, timestamp) = (self.next_sequence, self.next_timestamp_ms); + let mut packet = Vec::with_capacity(RTP_HEADER_LEN + opus.len() + 16); + packet.extend_from_slice(&[AUDIO_RTP_BYTE0, AUDIO_PAYLOAD_TYPE]); + packet.extend_from_slice(&sequence.to_be_bytes()); + packet.extend_from_slice(×tamp.to_be_bytes()); + packet.extend_from_slice(&0u32.to_be_bytes()); // SSRC 0 + match &self.config.cipher { + Some(c) => packet.extend_from_slice(&c.encrypt(sequence, opus)?), + None => packet.extend_from_slice(opus), + } + let datagrams = match self.config.parity { + AudioParity::None => vec![packet], + }; + self.next_sequence = sequence.wrapping_add(1); + self.next_timestamp_ms = timestamp.wrapping_add(u32::from(self.config.packet_duration_ms)); + Ok(datagrams) } /// The RTP sequence number of the next packet. #[must_use] pub const fn next_sequence(&self) -> u16 { - 0 + self.next_sequence } /// The RTP timestamp (milliseconds) of the next packet. #[must_use] pub const fn next_timestamp_ms(&self) -> u32 { - 0 + self.next_timestamp_ms } } diff --git a/crates/domistream/tests/audio_packetizer.rs b/crates/domistream/tests/audio_packetizer.rs index 6704cf6..252ebcd 100644 --- a/crates/domistream/tests/audio_packetizer.rs +++ b/crates/domistream/tests/audio_packetizer.rs @@ -99,19 +99,19 @@ fn send(tx: &mut AudioPacketizer, payloads: &[Vec], duration: u8) -> (Vec(), ) { let mut rng = SeqRng::new(seed); - let mut tx = sender(encrypt, first_sequence, first_ts, duration); + let mut tx = sender(encrypt, first_sequence & !3, 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); diff --git a/docs/PROTOCOL.md b/docs/PROTOCOL.md index 5787695..26d1088 100644 --- a/docs/PROTOCOL.md +++ b/docs/PROTOCOL.md @@ -532,6 +532,10 @@ coefficients (each parity byte is a linear combination of the 4 data bytes at th parity row, so a handful of byte positions gives a unique solution). Until then, audio loss falls back to the platform's packet-loss concealment. +Host side (Lumen, `audio::packetizer`): no parity packets until U16 is settled (`AudioParity::None`; the API leaves +room for a parity variant). The first sequence number is a multiple of 4, a block start, because our receiver counts +from the first packet's block start and would otherwise report the 1 to 3 numbers before it as lost. + ### 6.5 Decoding **Not DomiStream.** DomiStream outputs each Opus packet (or a "lost" marker) in sequence order plus the multistream