//! 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. //! //! 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 super::packet::{AUDIO_PAYLOAD_TYPE, MAX_AUDIO_PACKET_BYTES}; use crate::Result; use crate::rtp::RTP_HEADER_LEN; use crate::util::{cap, malformed, need}; /// 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 (`docs/PROTOCOL.md` 6.4). #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum AudioParity { /// None: the parity matrix is UNKNOWN U16 (GPL-provenance, unsettled), so clients conceal lost packets. #[default] None, } /// Settings of the audio sender. #[derive(Clone, Debug)] pub struct AudioPacketizerConfig { /// Encrypt payloads with this cipher (audio encryption negotiated, or always: UNKNOWN U17). pub cipher: Option, /// 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: 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, } /// The audio sender of one stream. #[derive(Debug)] pub struct AudioPacketizer { config: AudioPacketizerConfig, next_sequence: u16, next_timestamp_ms: u32, } impl AudioPacketizer { /// A sender for one stream. /// /// # Errors /// [`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 { 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: [`MAX_OPUS_ENCRYPTED_BYTES`] with a cipher, else [`MAX_OPUS_PLAIN_BYTES`]. #[must_use] pub const fn max_opus_len(&self) -> usize { if self.config.cipher.is_some() { MAX_OPUS_ENCRYPTED_BYTES } else { MAX_OPUS_PLAIN_BYTES } } /// 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 /// [`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>> { 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 { self.next_sequence } /// The RTP timestamp (milliseconds) of the next packet. #[must_use] pub const fn next_timestamp_ms(&self) -> u32 { self.next_timestamp_ms } }