[domistream] Implementation: HTTP, pairing, RTSP/SDP, ENet, control, input, RTP, FEC, video and audio receivers
Per PROTOCOL.md and the Wolf docs; interop with a real host is unverified. Strict, capped parsers throughout, shared helpers in util.rs. Where PROTOCOL.md says UNKNOWN the Wolf-documented behaviour is used. The audio receiver waits for the jitter budget before rebuilding a missing packet, so a late packet beats a rebuilt one.
This commit is contained in:
@@ -3,10 +3,19 @@
|
||||
//!
|
||||
//! **Opus decoding is not here.** A packet that cannot be rebuilt becomes [`AudioEvent::Lost`]; the platform
|
||||
//! conceals it.
|
||||
//!
|
||||
//! Parity packets are keyed by their FEC header's base sequence number, never by their own RTP sequence number,
|
||||
//! which overlaps the next block's data. The parity covers the (encrypted) payloads of the four data packets.
|
||||
|
||||
use core::fmt;
|
||||
use std::collections::{HashMap, VecDeque};
|
||||
|
||||
use crate::{Instant, Result, SessionKeys};
|
||||
use cbc::cipher::block_padding::Pkcs7;
|
||||
use cbc::cipher::{BlockModeDecrypt, KeyIvInit};
|
||||
|
||||
use crate::fec::ReedSolomon;
|
||||
use crate::util::malformed;
|
||||
use crate::{Error, Instant, Result, SessionKeys};
|
||||
|
||||
pub mod packet;
|
||||
|
||||
@@ -18,39 +27,54 @@ pub const DATA_SHARDS: usize = 4;
|
||||
pub const PARITY_SHARDS: usize = 2;
|
||||
/// Maximum blocks kept while waiting for missing packets.
|
||||
pub const MAX_BLOCKS_IN_FLIGHT: usize = 8;
|
||||
/// Packets further than this ahead of the next expected one are dropped (a stray, not a gap to wait for).
|
||||
pub const MAX_PACKETS_AHEAD: u16 = 1024;
|
||||
|
||||
/// AES-128-CBC for audio payloads: IV = `u32 BE (rikeyid + sequence) ‖ 12 zero bytes`, PKCS#7 padding.
|
||||
/// `Debug` never prints the key.
|
||||
#[derive(Clone)]
|
||||
pub struct AudioCipher {
|
||||
key: [u8; 16],
|
||||
key: zeroize::Zeroizing<[u8; 16]>,
|
||||
rikeyid: u32,
|
||||
}
|
||||
|
||||
impl AudioCipher {
|
||||
/// A cipher for the session's keys.
|
||||
#[must_use]
|
||||
pub const fn new(keys: &SessionKeys) -> Self {
|
||||
Self { key: keys.rikey, rikeyid: keys.rikeyid }
|
||||
pub fn new(keys: &SessionKeys) -> Self {
|
||||
Self { key: zeroize::Zeroizing::new(keys.rikey), rikeyid: keys.rikeyid }
|
||||
}
|
||||
|
||||
/// The IV for RTP sequence number `sequence`.
|
||||
/// The IV for RTP sequence number `sequence` (the sum wraps).
|
||||
///
|
||||
/// # Errors
|
||||
/// Phase A: always [`crate::Error::Unimplemented`].
|
||||
/// None today.
|
||||
pub fn iv(&self, sequence: u16) -> Result<[u8; 16]> {
|
||||
let _ = (sequence, self.rikeyid);
|
||||
Err(crate::Error::Unimplemented)
|
||||
let mut iv = [0u8; 16];
|
||||
let [a, b, c, d] = self.rikeyid.wrapping_add(u32::from(sequence)).to_be_bytes();
|
||||
iv[0] = a;
|
||||
iv[1] = b;
|
||||
iv[2] = c;
|
||||
iv[3] = d;
|
||||
Ok(iv)
|
||||
}
|
||||
|
||||
/// Decrypts one payload.
|
||||
///
|
||||
/// # Errors
|
||||
/// [`crate::Error::Malformed`] for a length that is not a positive multiple of 16, [`crate::Error::Crypto`] for
|
||||
/// bad padding. Phase A: always [`crate::Error::Unimplemented`].
|
||||
/// [`Error::Malformed`] for a length that is not a positive multiple of 16, [`Error::Crypto`] for bad padding.
|
||||
pub fn decrypt(&self, sequence: u16, ciphertext: &[u8]) -> Result<Vec<u8>> {
|
||||
let _ = (sequence, ciphertext, &self.key);
|
||||
Err(crate::Error::Unimplemented)
|
||||
if ciphertext.is_empty() || !ciphertext.len().is_multiple_of(16) {
|
||||
return Err(malformed("audio ciphertext length"));
|
||||
}
|
||||
let iv = self.iv(sequence)?;
|
||||
let mut buf = ciphertext.to_vec();
|
||||
let len = cbc::Decryptor::<aes::Aes128>::new((&*self.key).into(), &iv.into())
|
||||
.decrypt_padded::<Pkcs7>(&mut buf)
|
||||
.map_err(|_| Error::Crypto)?
|
||||
.len();
|
||||
buf.truncate(len);
|
||||
Ok(buf)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -116,52 +140,342 @@ pub struct AudioStats {
|
||||
pub lost: u64,
|
||||
}
|
||||
|
||||
/// One received or rebuilt data packet.
|
||||
#[derive(Debug, Clone)]
|
||||
struct Data {
|
||||
/// The payload as sent (ciphertext when encrypted): the FEC shard.
|
||||
shard: Vec<u8>,
|
||||
opus: Vec<u8>,
|
||||
timestamp_ms: u32,
|
||||
arrived: Instant,
|
||||
recovered: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
struct Parity {
|
||||
shard: Vec<u8>,
|
||||
base_timestamp: u32,
|
||||
arrived: Instant,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
struct Block {
|
||||
data: [Option<Data>; DATA_SHARDS],
|
||||
parity: [Option<Parity>; PARITY_SHARDS],
|
||||
}
|
||||
|
||||
impl Block {
|
||||
fn earliest_after(&self, index: usize) -> Option<Instant> {
|
||||
let data = self.data.iter().skip(index + 1).flatten().map(|d| d.arrived);
|
||||
let parity = self.parity.iter().flatten().map(|p| p.arrived);
|
||||
data.chain(parity).min()
|
||||
}
|
||||
}
|
||||
|
||||
/// The audio receiver.
|
||||
#[derive(Debug)]
|
||||
pub struct AudioDepacketizer {
|
||||
config: AudioConfig,
|
||||
code: Option<ReedSolomon>,
|
||||
next: Option<u16>,
|
||||
blocks: HashMap<u16, Block>,
|
||||
events: VecDeque<AudioEvent>,
|
||||
stats: AudioStats,
|
||||
}
|
||||
|
||||
const fn block_base(seq: u16) -> u16 {
|
||||
seq & !3
|
||||
}
|
||||
|
||||
impl AudioDepacketizer {
|
||||
/// A receiver for one stream.
|
||||
///
|
||||
/// # Errors
|
||||
/// [`crate::Error::Malformed`] for a zero packet duration or a parity matrix that is not MDS. Phase A: always
|
||||
/// [`crate::Error::Unimplemented`].
|
||||
/// [`Error::Malformed`] for a zero packet duration or a parity matrix that is not MDS.
|
||||
pub fn new(config: AudioConfig) -> Result<Self> {
|
||||
let _ = config;
|
||||
Err(crate::Error::Unimplemented)
|
||||
if config.packet_duration_ms == 0 {
|
||||
return Err(malformed("audio packet duration"));
|
||||
}
|
||||
let code = match config.fec {
|
||||
AudioFec::Disabled => None,
|
||||
AudioFec::ParityMatrix(m) => Some(ReedSolomon::with_parity_matrix(DATA_SHARDS, PARITY_SHARDS, &m)?),
|
||||
};
|
||||
Ok(Self { config, code, next: None, blocks: HashMap::new(), events: VecDeque::new(), stats: AudioStats::default() })
|
||||
}
|
||||
|
||||
fn drop_packet(&mut self) -> Result<()> {
|
||||
self.stats.packets_dropped += 1;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Feeds one datagram from the audio port. Bad, duplicate and too-old packets are counted and dropped; only an
|
||||
/// oversized datagram is an error.
|
||||
///
|
||||
/// # Errors
|
||||
/// [`crate::Error::TooLarge`] over [`packet::MAX_AUDIO_PACKET_BYTES`]. Phase A: always
|
||||
/// [`crate::Error::Unimplemented`].
|
||||
/// [`Error::TooLarge`] over [`packet::MAX_AUDIO_PACKET_BYTES`].
|
||||
pub fn push(&mut self, now: Instant, datagram: &[u8]) -> Result<()> {
|
||||
let _ = (now, datagram);
|
||||
Err(crate::Error::Unimplemented)
|
||||
crate::util::cap("audio datagram", packet::MAX_AUDIO_PACKET_BYTES, datagram.len())?;
|
||||
let Ok(p) = parse_audio_packet(datagram) else { return self.drop_packet() };
|
||||
match p {
|
||||
AudioPacket::Data { rtp, payload } => {
|
||||
let seq = rtp.sequence;
|
||||
if !self.admit(seq, seq) {
|
||||
return self.drop_packet();
|
||||
}
|
||||
let opus = match &self.config.cipher {
|
||||
Some(c) => match c.decrypt(seq, payload) {
|
||||
Ok(o) => o,
|
||||
Err(_) => return self.drop_packet(),
|
||||
},
|
||||
None => payload.to_vec(),
|
||||
};
|
||||
let slot = self.blocks.entry(block_base(seq)).or_default().data.get_mut(usize::from(seq & 3));
|
||||
match slot {
|
||||
Some(s) if s.is_none() => {
|
||||
*s = Some(Data {
|
||||
shard: payload.to_vec(),
|
||||
opus,
|
||||
timestamp_ms: rtp.timestamp,
|
||||
arrived: now,
|
||||
recovered: false,
|
||||
});
|
||||
}
|
||||
_ => return self.drop_packet(),
|
||||
}
|
||||
}
|
||||
AudioPacket::Parity { fec, parity, .. } => {
|
||||
let base = fec.base_sequence;
|
||||
if base & 3 != 0 || fec.payload_type != packet::AUDIO_PAYLOAD_TYPE {
|
||||
return self.drop_packet();
|
||||
}
|
||||
if self.code.is_none() {
|
||||
self.stats.packets += 1;
|
||||
return Ok(());
|
||||
}
|
||||
if !self.admit(base, base.wrapping_add(3)) {
|
||||
return self.drop_packet();
|
||||
}
|
||||
let slot = self.blocks.entry(base).or_default().parity.get_mut(usize::from(fec.shard_index));
|
||||
match slot {
|
||||
Some(s) if s.is_none() => {
|
||||
*s = Some(Parity { shard: parity.to_vec(), base_timestamp: fec.base_timestamp, arrived: now });
|
||||
}
|
||||
_ => return self.drop_packet(),
|
||||
}
|
||||
}
|
||||
}
|
||||
self.stats.packets += 1;
|
||||
self.advance(now);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Whether a packet covering `first..=last` may be stored: not entirely in the past, not too far ahead. A packet
|
||||
/// ahead of the block window first moves the window up (the blocks it passes are emitted or reported lost).
|
||||
fn admit(&mut self, first: u16, last: u16) -> bool {
|
||||
let next = *self.next.get_or_insert(block_base(first));
|
||||
if last.wrapping_sub(next) >= 0x8000 {
|
||||
return false;
|
||||
}
|
||||
let ahead = first.wrapping_sub(next);
|
||||
if ahead < 0x8000 && ahead >= MAX_PACKETS_AHEAD {
|
||||
return false;
|
||||
}
|
||||
let window = (MAX_BLOCKS_IN_FLIGHT * DATA_SHARDS) as u16;
|
||||
if block_base(first).wrapping_sub(block_base(next)) < 0x8000
|
||||
&& block_base(first).wrapping_sub(block_base(next)) >= window
|
||||
{
|
||||
self.flush_until(block_base(first).wrapping_sub(window - DATA_SHARDS as u16));
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// Emits or reports lost every sequence number before `target`, at once.
|
||||
fn flush_until(&mut self, target: u16) {
|
||||
while let Some(n) = self.next {
|
||||
if target.wrapping_sub(n) == 0 || target.wrapping_sub(n) >= 0x8000 {
|
||||
return;
|
||||
}
|
||||
if !self.emit_if_available(n) {
|
||||
self.events.push_back(AudioEvent::Lost { sequence: n });
|
||||
self.stats.lost += 1;
|
||||
self.step(n);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Emits `n` if it was received or can be rebuilt now.
|
||||
fn emit_if_available(&mut self, n: u16) -> bool {
|
||||
let base = block_base(n);
|
||||
let index = usize::from(n & 3);
|
||||
let present = |s: &Self| s.blocks.get(&base).and_then(|b| b.data.get(index)).is_some_and(Option::is_some);
|
||||
if present(self) || (self.recover(base) && present(self)) {
|
||||
self.emit_present(n, base, index);
|
||||
return true;
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// Emits in sequence order: received packets at once; a missing packet waits for the jitter budget
|
||||
/// (`loss_timeout`), since a late packet beats a rebuilt one, and is then rebuilt or reported lost.
|
||||
fn advance(&mut self, now: Instant) {
|
||||
let timeout = self.config.loss_timeout;
|
||||
while let Some(n) = self.next {
|
||||
let base = block_base(n);
|
||||
let index = usize::from(n & 3);
|
||||
if self.blocks.get(&base).and_then(|b| b.data.get(index)).is_some_and(Option::is_some) {
|
||||
self.emit_present(n, base, index);
|
||||
continue;
|
||||
}
|
||||
let Some(start) = self.earliest_after(n, base, index) else { return };
|
||||
if start.saturating_add(timeout) > now {
|
||||
return;
|
||||
}
|
||||
if self.emit_if_available(n) {
|
||||
continue;
|
||||
}
|
||||
self.events.push_back(AudioEvent::Lost { sequence: n });
|
||||
self.stats.lost += 1;
|
||||
self.step(n);
|
||||
}
|
||||
}
|
||||
|
||||
fn emit_present(&mut self, n: u16, base: u16, index: usize) {
|
||||
// The shard stays in the block: a later packet of the same block may still need it to be rebuilt.
|
||||
if let Some(d) = self.blocks.get_mut(&base).and_then(|b| b.data.get_mut(index)).and_then(Option::as_mut) {
|
||||
if d.recovered {
|
||||
self.stats.recovered += 1;
|
||||
}
|
||||
let opus = core::mem::take(&mut d.opus);
|
||||
self.events.push_back(AudioEvent::Packet {
|
||||
sequence: n,
|
||||
timestamp_ms: d.timestamp_ms,
|
||||
opus,
|
||||
recovered: d.recovered,
|
||||
});
|
||||
}
|
||||
self.step(n);
|
||||
}
|
||||
|
||||
/// Moves past `n`, dropping its block once its last data packet is done.
|
||||
fn step(&mut self, n: u16) {
|
||||
if n & 3 == 3 {
|
||||
self.blocks.remove(&block_base(n));
|
||||
}
|
||||
self.next = Some(n.wrapping_add(1));
|
||||
}
|
||||
|
||||
/// The earliest arrival of anything stored after sequence `n`: when the wait for `n` began.
|
||||
fn earliest_after(&self, n: u16, base: u16, index: usize) -> Option<Instant> {
|
||||
let own = self.blocks.get(&base).and_then(|b| b.earliest_after(index));
|
||||
let later = self
|
||||
.blocks
|
||||
.iter()
|
||||
.filter(|(b, _)| b.wrapping_sub(base) != 0 && b.wrapping_sub(n) < 0x8000)
|
||||
.filter_map(|(_, blk)| blk.data.iter().flatten().map(|d| d.arrived).chain(blk.parity.iter().flatten().map(|p| p.arrived)).min())
|
||||
.min();
|
||||
match (own, later) {
|
||||
(Some(a), Some(b)) => Some(a.min(b)),
|
||||
(a, b) => a.or(b),
|
||||
}
|
||||
}
|
||||
|
||||
/// Rebuilds the missing data packets of block `base` when FEC is on and 4 equal-length shards are there.
|
||||
fn recover(&mut self, base: u16) -> bool {
|
||||
let Some(code) = &self.code else { return false };
|
||||
let Some(block) = self.blocks.get(&base) else { return false };
|
||||
let len = block
|
||||
.data
|
||||
.iter()
|
||||
.flatten()
|
||||
.map(|d| d.shard.len())
|
||||
.next()
|
||||
.or_else(|| block.parity.iter().flatten().map(|p| p.shard.len()).next());
|
||||
let Some(len) = len else { return false };
|
||||
let mut shards: Vec<Option<Vec<u8>>> = block
|
||||
.data
|
||||
.iter()
|
||||
.map(|d| d.as_ref().filter(|d| d.shard.len() == len).map(|d| d.shard.clone()))
|
||||
.chain(block.parity.iter().map(|p| p.as_ref().filter(|p| p.shard.len() == len).map(|p| p.shard.clone())))
|
||||
.collect();
|
||||
if shards.iter().flatten().count() < DATA_SHARDS || block.data.iter().all(Option::is_some) {
|
||||
return false;
|
||||
}
|
||||
if code.reconstruct(&mut shards).is_err() {
|
||||
return false;
|
||||
}
|
||||
let base_ts = block
|
||||
.parity
|
||||
.iter()
|
||||
.flatten()
|
||||
.map(|p| p.base_timestamp)
|
||||
.next()
|
||||
.or_else(|| {
|
||||
block.data.iter().enumerate().find_map(|(i, d)| {
|
||||
d.as_ref().map(|d| d.timestamp_ms.wrapping_sub(i as u32 * u32::from(self.config.packet_duration_ms)))
|
||||
})
|
||||
})
|
||||
.unwrap_or(0);
|
||||
let duration = u32::from(self.config.packet_duration_ms);
|
||||
let mut rebuilt = Vec::new();
|
||||
for (i, shard) in shards.into_iter().take(DATA_SHARDS).enumerate() {
|
||||
if block.data.get(i).is_some_and(Option::is_some) {
|
||||
continue;
|
||||
}
|
||||
let Some(shard) = shard else { continue };
|
||||
let seq = base.wrapping_add(i as u16);
|
||||
let opus = match &self.config.cipher {
|
||||
Some(c) => match c.decrypt(seq, &shard) {
|
||||
Ok(o) => o,
|
||||
Err(_) => continue,
|
||||
},
|
||||
None => shard.clone(),
|
||||
};
|
||||
rebuilt.push((
|
||||
i,
|
||||
Data {
|
||||
shard,
|
||||
opus,
|
||||
timestamp_ms: base_ts.wrapping_add(i as u32 * duration),
|
||||
arrived: Instant::ZERO,
|
||||
recovered: true,
|
||||
},
|
||||
));
|
||||
}
|
||||
let any = !rebuilt.is_empty();
|
||||
if let Some(block) = self.blocks.get_mut(&base) {
|
||||
for (i, d) in rebuilt {
|
||||
if let Some(slot) = block.data.get_mut(i) {
|
||||
*slot = Some(d);
|
||||
}
|
||||
}
|
||||
}
|
||||
any
|
||||
}
|
||||
|
||||
/// The next event.
|
||||
pub fn poll_event(&mut self) -> Option<AudioEvent> {
|
||||
None
|
||||
self.events.pop_front()
|
||||
}
|
||||
|
||||
/// When a missing packet times out.
|
||||
#[must_use]
|
||||
pub fn poll_timeout(&self) -> Option<Instant> {
|
||||
None
|
||||
let n = self.next?;
|
||||
let base = block_base(n);
|
||||
let index = usize::from(n & 3);
|
||||
if self.blocks.get(&base).and_then(|b| b.data.get(index)).is_some_and(Option::is_some) {
|
||||
return None;
|
||||
}
|
||||
self.earliest_after(n, base, index).map(|t| t.saturating_add(self.config.loss_timeout))
|
||||
}
|
||||
|
||||
/// Reports timed-out packets as lost.
|
||||
///
|
||||
/// # Errors
|
||||
/// Phase A: always [`crate::Error::Unimplemented`].
|
||||
/// None today.
|
||||
pub fn handle_timeout(&mut self, now: Instant) -> Result<()> {
|
||||
let _ = now;
|
||||
Err(crate::Error::Unimplemented)
|
||||
self.advance(now);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Counters.
|
||||
|
||||
@@ -52,9 +52,34 @@ pub enum AudioPacket<'a> {
|
||||
///
|
||||
/// # Errors
|
||||
/// [`crate::Error::TooLarge`] over [`MAX_AUDIO_PACKET_BYTES`], [`crate::Error::Truncated`] for a cut header or an
|
||||
/// empty payload, [`crate::Error::UnexpectedValue`] for another payload type or a parity shard index above 1.
|
||||
/// Phase A: always [`crate::Error::Unimplemented`].
|
||||
/// empty payload, [`crate::Error::UnexpectedValue`] for another RTP version or payload type, or a parity shard
|
||||
/// index above 1.
|
||||
pub fn parse_audio_packet(packet: &[u8]) -> crate::Result<AudioPacket<'_>> {
|
||||
let _ = packet;
|
||||
Err(crate::Error::Unimplemented)
|
||||
use crate::util::{byte, need, u16_be, u32_be};
|
||||
const W: &str = "audio packet";
|
||||
crate::util::cap(W, MAX_AUDIO_PACKET_BYTES, packet.len())?;
|
||||
let rtp = crate::rtp::parse_rtp_header(packet)?;
|
||||
let at = crate::rtp::RTP_HEADER_LEN;
|
||||
match rtp.payload_type {
|
||||
AUDIO_PAYLOAD_TYPE => {
|
||||
need(W, at + 1, packet.len())?;
|
||||
Ok(AudioPacket::Data { rtp, payload: packet.get(at..).unwrap_or(&[]) })
|
||||
}
|
||||
AUDIO_FEC_PAYLOAD_TYPE => {
|
||||
need(W, at + AUDIO_FEC_HEADER_LEN + 1, packet.len())?;
|
||||
let shard_index = byte(W, packet, at)?;
|
||||
if shard_index > 1 {
|
||||
return Err(crate::Error::UnexpectedValue { what: "audio parity shard", value: shard_index.into() });
|
||||
}
|
||||
let fec = AudioFecHeader {
|
||||
shard_index,
|
||||
payload_type: byte(W, packet, at + 1)?,
|
||||
base_sequence: u16_be(W, packet, at + 2)?,
|
||||
base_timestamp: u32_be(W, packet, at + 4)?,
|
||||
ssrc: u32_be(W, packet, at + 8)?,
|
||||
};
|
||||
Ok(AudioPacket::Parity { rtp, fec, parity: packet.get(at + AUDIO_FEC_HEADER_LEN..).unwrap_or(&[]) })
|
||||
}
|
||||
other => Err(crate::Error::UnexpectedValue { what: "audio payload type", value: other.into() }),
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user