[domistream] Audio packetizer: RTP datagram per Opus packet, AES-128-CBC (AudioCipher::encrypt), no parity until U16; first sequence must start a block
This commit is contained in:
@@ -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<Vec<u8>> {
|
||||
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::<aes::Aes128>::new((&*self.key).into(), &iv.into())
|
||||
.encrypt_padded::<Pkcs7>(&mut buf, plaintext.len())
|
||||
.map_err(|_| Error::Crypto)?
|
||||
.len();
|
||||
buf.truncate(len);
|
||||
Ok(buf)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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<AudioCipher>,
|
||||
/// 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<Self> {
|
||||
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<Vec<Vec<u8>>> {
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user