Compare commits
12 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 81ddf64bee | |||
| 7a6afed575 | |||
| 0d3a9a7917 | |||
| b62443ef28 | |||
| e1abd7d060 | |||
| 7983833ba6 | |||
| 514565dbd7 | |||
| 284bf7cc17 | |||
| e4fdca794b | |||
| 73deb851ae | |||
| 813a0ab8c4 | |||
| 3794ed0e7f |
@@ -11,15 +11,17 @@ use core::fmt;
|
|||||||
use std::collections::{HashMap, VecDeque};
|
use std::collections::{HashMap, VecDeque};
|
||||||
|
|
||||||
use cbc::cipher::block_padding::Pkcs7;
|
use cbc::cipher::block_padding::Pkcs7;
|
||||||
use cbc::cipher::{BlockModeDecrypt, KeyIvInit};
|
use cbc::cipher::{BlockModeDecrypt, BlockModeEncrypt, KeyIvInit};
|
||||||
|
|
||||||
use crate::fec::ReedSolomon;
|
use crate::fec::ReedSolomon;
|
||||||
use crate::util::malformed;
|
use crate::util::malformed;
|
||||||
use crate::{Error, Instant, Result, SessionKeys};
|
use crate::{Error, Instant, Result, SessionKeys};
|
||||||
|
|
||||||
pub mod packet;
|
pub mod packet;
|
||||||
|
pub mod packetizer;
|
||||||
|
|
||||||
pub use packet::{AudioFecHeader, AudioPacket, parse_audio_packet};
|
pub use packet::{AudioFecHeader, AudioPacket, parse_audio_packet};
|
||||||
|
pub use packetizer::{AudioPacketizer, AudioPacketizerConfig, AudioParity};
|
||||||
|
|
||||||
/// Data packets per FEC block.
|
/// Data packets per FEC block.
|
||||||
pub const DATA_SHARDS: usize = 4;
|
pub const DATA_SHARDS: usize = 4;
|
||||||
@@ -78,6 +80,30 @@ impl AudioCipher {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl AudioCipher {
|
||||||
|
/// 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::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>> {
|
||||||
|
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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
impl fmt::Debug for AudioCipher {
|
impl fmt::Debug for AudioCipher {
|
||||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
f.write_str("AudioCipher(<redacted>)")
|
f.write_str("AudioCipher(<redacted>)")
|
||||||
|
|||||||
@@ -0,0 +1,124 @@
|
|||||||
|
//! 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<AudioCipher>,
|
||||||
|
/// 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<Self> {
|
||||||
|
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<Vec<Vec<u8>>> {
|
||||||
|
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
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -26,8 +26,8 @@
|
|||||||
//! | [`input`] | input and gamepad packets (section 4) |
|
//! | [`input`] | input and gamepad packets (section 4) |
|
||||||
//! | [`rtp`] | the RTP header shared by video and audio |
|
//! | [`rtp`] | the RTP header shared by video and audio |
|
||||||
//! | [`fec`] | Reed-Solomon erasure coding over GF(2^8) |
|
//! | [`fec`] | Reed-Solomon erasure coding over GF(2^8) |
|
||||||
//! | [`video`] | video depacketizer with FEC recovery and decryption (section 5) |
|
//! | [`video`] | video depacketizer with FEC recovery and decryption (section 5); the host's packetizer |
|
||||||
//! | [`audio`] | audio depacketizer with FEC recovery and decryption (section 6) |
|
//! | [`audio`] | audio depacketizer with FEC recovery and decryption (section 6); the host's packetizer |
|
||||||
//!
|
//!
|
||||||
//! Opus and video decoding are not here: they belong to the platform layer (ArenaTV).
|
//! Opus and video decoding are not here: they belong to the platform layer (ArenaTV).
|
||||||
|
|
||||||
|
|||||||
@@ -20,8 +20,10 @@ use crate::util::{array, cap, malformed, need};
|
|||||||
use crate::{Error, Instant, Result};
|
use crate::{Error, Instant, Result};
|
||||||
|
|
||||||
pub mod packet;
|
pub mod packet;
|
||||||
|
pub mod packetizer;
|
||||||
|
|
||||||
pub use packet::{FecInfo, FrameHeader, FrameType, NvVideoHeader, VideoFlags, VideoPacket, parse_video_packet};
|
pub use packet::{FecInfo, FrameHeader, FrameType, NvVideoHeader, VideoFlags, VideoPacket, parse_video_packet};
|
||||||
|
pub use packetizer::{EncodedFrame, VideoPacketizer, VideoPacketizerConfig};
|
||||||
|
|
||||||
/// Length of the prefix of an encrypted packet: IV 12 + frame number 4 + tag 16.
|
/// Length of the prefix of an encrypted packet: IV 12 + frame number 4 + tag 16.
|
||||||
pub const ENCRYPTION_PREFIX_LEN: usize = 12 + 4 + 16;
|
pub const ENCRYPTION_PREFIX_LEN: usize = 12 + 4 + 16;
|
||||||
@@ -69,6 +71,38 @@ impl VideoCipher {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl VideoCipher {
|
||||||
|
/// Seals one plaintext packet (host side), the exact mirror of [`Self::decrypt`]: IV = `counter` as 8 bytes LE,
|
||||||
|
/// 3 zero bytes, `'V'`; output `IV ‖ frame number u32 LE ‖ tag ‖ ciphertext` (`docs/PROTOCOL.md` 7, UNKNOWN
|
||||||
|
/// U19 against Sunshine). The caller must never reuse a `counter` under one key: the packetizer counts from 0
|
||||||
|
/// per session, and the `'V'` byte keeps video nonces apart from control's (`'C'`).
|
||||||
|
///
|
||||||
|
/// # Errors
|
||||||
|
/// [`Error::TooLarge`] when the sealed packet would exceed [`packet::MAX_VIDEO_PACKET_BYTES`], [`Error::Crypto`]
|
||||||
|
/// if the cipher refuses (never for packets within the cap).
|
||||||
|
pub fn encrypt(&self, counter: u64, frame_number: u32, packet: &[u8]) -> Result<Vec<u8>> {
|
||||||
|
let sealed = packet.len().saturating_add(ENCRYPTION_PREFIX_LEN);
|
||||||
|
cap("sealed video packet", packet::MAX_VIDEO_PACKET_BYTES, sealed)?;
|
||||||
|
let mut iv = [0u8; 12];
|
||||||
|
for (dst, src) in iv.iter_mut().zip(counter.to_le_bytes()) {
|
||||||
|
*dst = src;
|
||||||
|
}
|
||||||
|
if let Some(last) = iv.last_mut() {
|
||||||
|
*last = b'V';
|
||||||
|
}
|
||||||
|
let mut body = packet.to_vec();
|
||||||
|
let tag = Aes128Gcm::new((&*self.key).into())
|
||||||
|
.encrypt_inout_detached(&iv.into(), b"", body.as_mut_slice().into())
|
||||||
|
.map_err(|_| Error::Crypto)?;
|
||||||
|
let mut out = Vec::with_capacity(sealed);
|
||||||
|
out.extend_from_slice(&iv);
|
||||||
|
out.extend_from_slice(&frame_number.to_le_bytes());
|
||||||
|
out.extend_from_slice(tag.as_slice());
|
||||||
|
out.extend_from_slice(&body);
|
||||||
|
Ok(out)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
impl fmt::Debug for VideoCipher {
|
impl fmt::Debug for VideoCipher {
|
||||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
f.write_str("VideoCipher(<redacted>)")
|
f.write_str("VideoCipher(<redacted>)")
|
||||||
|
|||||||
@@ -0,0 +1,391 @@
|
|||||||
|
//! The video send path, host side (`docs/PROTOCOL.md` 5.2, 5.3, 7): one encoded access unit → the RTP + NV-header
|
||||||
|
//! datagrams of one frame, in FEC blocks with Reed-Solomon parity, optionally AES-128-GCM sealed.
|
||||||
|
//!
|
||||||
|
//! The mirror of [`super::VideoDepacketizer`], and tested against it:
|
||||||
|
//!
|
||||||
|
//! 1. Frame data = the 8-byte frame header ([`write_frame_header`], the structured reading of 5.2; UNKNOWN U13 is
|
||||||
|
//! open, so the writer is one small function) followed by the Annex-B bitstream, cut into `packetSize - 16`-byte
|
||||||
|
//! data shards, the last one zero-padded (5.2).
|
||||||
|
//! 2. The data shards are split into at most 4 FEC blocks ([`plan_fec_blocks`]); each block gets
|
||||||
|
//! `m = ceil(k × percentage / 100)` parity shards, with the percentage raised for the client's minimum parity
|
||||||
|
//! count and lowered only when a block would exceed 255 shards (5.3).
|
||||||
|
//! 3. Each data shard becomes a whole packet (RTP header, 4 reserved bytes, NV header, payload). Parity is computed
|
||||||
|
//! over these whole packets with [`crate::fec::ReedSolomon`] (the Cauchy matrix of 5.3), and only then are the
|
||||||
|
//! parity packets' RTP and NV header fields written over their first 32 bytes, exactly as 5.3 says.
|
||||||
|
//! 4. Sequence numbers run on across frames (one per datagram, data and parity alike, wrapping at 16 bits); the
|
||||||
|
//! stream packet index is the sequence number shifted left by 8 (5.2).
|
||||||
|
//! 5. With video encryption, every finished packet is sealed with [`VideoCipher::encrypt`] (FEC before
|
||||||
|
//! encryption, 7), with a per-session nonce counter that starts at 0.
|
||||||
|
//!
|
||||||
|
//! The input is trusted (our own encoder), but nothing here panics: sizes are capped with typed errors before
|
||||||
|
//! anything is allocated, and a refused frame changes no state.
|
||||||
|
//!
|
||||||
|
//! Choices of our own, not from a source (to be compared with a real host's capture): the block split (fewest
|
||||||
|
//! blocks that carry the requested parity; every block but the last has the same `k`), the percentage arithmetic
|
||||||
|
//! for the minimum parity count, and what happens to a frame too big for its parity (the parity is lowered, counted
|
||||||
|
//! in [`VideoPacketizerStats::fec_reduced_blocks`]).
|
||||||
|
|
||||||
|
use super::VideoCipher;
|
||||||
|
use super::packet::{
|
||||||
|
FRAME_HEADER_LEN, FrameType, MAX_FEC_BLOCKS, MAX_VIDEO_PACKET_BYTES, NV_HEADER_LEN, PAYLOAD_OFFSET, VIDEO_RTP_LEN,
|
||||||
|
VideoFlags,
|
||||||
|
};
|
||||||
|
use super::{ENCRYPTION_PREFIX_LEN, MAX_FRAME_BYTES};
|
||||||
|
use crate::fec::{MAX_SHARDS, ReedSolomon};
|
||||||
|
use crate::util::{cap, malformed};
|
||||||
|
use crate::{Error, Result};
|
||||||
|
|
||||||
|
/// The NV header's multi-FEC flags byte (`docs/PROTOCOL.md` 5.2, UNKNOWN U15: sent as documented, meaning unknown).
|
||||||
|
pub const MULTI_FEC_FLAGS: u8 = 0x10;
|
||||||
|
/// Byte 0 of the structured frame header (`docs/PROTOCOL.md` 5.2).
|
||||||
|
pub const FRAME_HEADER_TYPE: u8 = 0x01;
|
||||||
|
/// Byte 0 of every video RTP header: version 2, extension bit set (`docs/PROTOCOL.md` 5.2).
|
||||||
|
pub const VIDEO_RTP_BYTE0: u8 = 0x90;
|
||||||
|
/// Most data shards one frame can carry: [`MAX_FEC_BLOCKS`] blocks of at most [`MAX_SHARDS`] shards.
|
||||||
|
pub const MAX_DATA_SHARDS_PER_FRAME: usize = MAX_FEC_BLOCKS * MAX_SHARDS;
|
||||||
|
|
||||||
|
/// Settings of the video sender, from the client's ANNOUNCE (`docs/PROTOCOL.md` 2.4).
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
pub struct VideoPacketizerConfig {
|
||||||
|
/// Negotiated `packetSize`: NV header + payload. Each datagram is `packetSize + 16` bytes (+ 32 when sealed).
|
||||||
|
pub packet_size: u16,
|
||||||
|
/// Requested FEC percentage.
|
||||||
|
pub fec_percentage: u8,
|
||||||
|
/// Minimum parity packets per block (`x-nv-vqos[0].fec.minRequiredFecPackets`).
|
||||||
|
pub min_required_fec_packets: u8,
|
||||||
|
/// Seal every datagram with this cipher when video encryption was negotiated.
|
||||||
|
pub cipher: Option<VideoCipher>,
|
||||||
|
/// RTP sequence number of the first datagram.
|
||||||
|
pub first_sequence: u16,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One encoded access unit from the encoder.
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||||
|
pub struct EncodedFrame<'a> {
|
||||||
|
/// Frame index (NV header bytes 20-23).
|
||||||
|
pub frame_index: u32,
|
||||||
|
/// Frame type written into the frame header.
|
||||||
|
pub frame_type: FrameType,
|
||||||
|
/// RTP timestamp shared by every datagram of the frame (UNKNOWN U29: clock rate, probably 90 kHz).
|
||||||
|
pub rtp_timestamp: u32,
|
||||||
|
/// Host processing latency, frame header bytes 1-2 (unit UNKNOWN, U13).
|
||||||
|
pub processing_latency: u16,
|
||||||
|
/// The Annex-B bitstream, start codes included.
|
||||||
|
pub bitstream: &'a [u8],
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The FEC geometry of one block.
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||||
|
pub struct FecBlock {
|
||||||
|
/// Data shards `k`.
|
||||||
|
pub data_shards: u16,
|
||||||
|
/// Parity shards `m = ceil(k × percentage / 100)`.
|
||||||
|
pub parity_shards: u16,
|
||||||
|
/// The percentage written into the block's FEC info (the receiver derives `m` from it).
|
||||||
|
pub fec_percentage: u8,
|
||||||
|
/// The requested parity (percentage and minimum count) did not fit in 255 shards and was lowered.
|
||||||
|
pub reduced: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Counters.
|
||||||
|
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
|
||||||
|
pub struct VideoPacketizerStats {
|
||||||
|
/// Frames packetized.
|
||||||
|
pub frames: u64,
|
||||||
|
/// Datagrams produced (data + parity).
|
||||||
|
pub packets: u64,
|
||||||
|
/// Parity datagrams among them.
|
||||||
|
pub parity_packets: u64,
|
||||||
|
/// Blocks whose parity was lowered to fit 255 shards.
|
||||||
|
pub fec_reduced_blocks: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The frame type byte of the structured frame header (`docs/PROTOCOL.md` 5.2).
|
||||||
|
const fn frame_type_byte(t: FrameType) -> u8 {
|
||||||
|
match t {
|
||||||
|
FrameType::Predicted => 1,
|
||||||
|
FrameType::Key => 2,
|
||||||
|
FrameType::Recovery => 5,
|
||||||
|
FrameType::Other(v) => v,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Writes the 8-byte frame header in its structured form (`docs/PROTOCOL.md` 5.2): type `0x01`, processing latency
|
||||||
|
/// u16 LE, frame type, payload bytes in the last data shard u32 LE. UNKNOWN U13 (Wolf shows a constant instead) is
|
||||||
|
/// open; this is the form our client reads, and the only place to change if the capture says otherwise.
|
||||||
|
#[must_use]
|
||||||
|
pub fn write_frame_header(
|
||||||
|
frame_type: FrameType,
|
||||||
|
processing_latency: u16,
|
||||||
|
last_payload_len: u32,
|
||||||
|
) -> [u8; FRAME_HEADER_LEN] {
|
||||||
|
let [l0, l1] = processing_latency.to_le_bytes();
|
||||||
|
let [a, b, c, d] = last_payload_len.to_le_bytes();
|
||||||
|
[FRAME_HEADER_TYPE, l0, l1, frame_type_byte(frame_type), a, b, c, d]
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Parity of a block of `k` at percentage `p`: `ceil(k × p / 100)` (the receiver's formula, 5.3).
|
||||||
|
const fn parity_at(k: usize, p: usize) -> usize {
|
||||||
|
(k * p).div_ceil(100)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The parity the client asks for a block of `k`: the percentage's, but at least the minimum count.
|
||||||
|
fn target(k: usize, pct: u8, min: u8) -> usize {
|
||||||
|
let m = parity_at(k, usize::from(pct));
|
||||||
|
if m < usize::from(min) { usize::from(min) } else { m }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The least percentage, at or above `pct`, whose parity reaches the target, if it is an 8-bit value and keeps the
|
||||||
|
/// block within [`MAX_SHARDS`].
|
||||||
|
fn wished_percentage(k: usize, pct: u8, min: u8) -> Option<usize> {
|
||||||
|
if k == 0 {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let t = target(k, pct, min);
|
||||||
|
let p = if parity_at(k, usize::from(pct)) >= t {
|
||||||
|
usize::from(pct)
|
||||||
|
} else {
|
||||||
|
// The least p with k·p > 100·(t − 1), i.e. ceil(k·p / 100) ≥ t.
|
||||||
|
100 * (t - 1) / k + 1
|
||||||
|
};
|
||||||
|
(p <= usize::from(u8::MAX) && k + parity_at(k, p) <= MAX_SHARDS).then_some(p)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The FEC geometry of one block of `k` data shards.
|
||||||
|
fn block(k: usize, pct: u8, min: u8) -> Result<FecBlock> {
|
||||||
|
let (p, reduced) = match wished_percentage(k, pct, min) {
|
||||||
|
Some(p) => (p, false),
|
||||||
|
// The most parity that fits: the largest p with k + ceil(k·p / 100) ≤ 255.
|
||||||
|
None => ((100 * MAX_SHARDS.saturating_sub(k) / k.max(1)).min(usize::from(u8::MAX)), true),
|
||||||
|
};
|
||||||
|
let to_u16 = |v: usize| u16::try_from(v).map_err(|_| malformed("video fec block"));
|
||||||
|
Ok(FecBlock {
|
||||||
|
data_shards: to_u16(k)?,
|
||||||
|
parity_shards: to_u16(parity_at(k, p))?,
|
||||||
|
fec_percentage: u8::try_from(p).map_err(|_| malformed("video fec percentage"))?,
|
||||||
|
reduced,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Splits a frame's `data_shards` into FEC blocks (`docs/PROTOCOL.md` 5.3): the fewest blocks (at most
|
||||||
|
/// [`MAX_FEC_BLOCKS`]) whose blocks can each carry the requested parity, where every block but the last carries
|
||||||
|
/// `ceil(data_shards / blocks)` data shards. Each block's percentage is the least one, at or above `fec_percentage`,
|
||||||
|
/// that gives `max(ceil(k × fec_percentage / 100), min_parity)` parity shards; when that cannot fit in
|
||||||
|
/// [`MAX_SHARDS`] shards (or an 8-bit percentage), the block gets the most parity that fits and is marked `reduced`.
|
||||||
|
///
|
||||||
|
/// # Errors
|
||||||
|
/// [`Error::Malformed`] for 0 data shards, [`Error::TooLarge`] over [`MAX_DATA_SHARDS_PER_FRAME`].
|
||||||
|
pub fn plan_fec_blocks(data_shards: usize, fec_percentage: u8, min_parity: u8) -> Result<Vec<FecBlock>> {
|
||||||
|
if data_shards == 0 {
|
||||||
|
return Err(malformed("video frame without data shards"));
|
||||||
|
}
|
||||||
|
cap("video frame data shards", MAX_DATA_SHARDS_PER_FRAME, data_shards)?;
|
||||||
|
let blocks = (1..=MAX_FEC_BLOCKS)
|
||||||
|
.find(|&b| wished_percentage(data_shards.div_ceil(b), fec_percentage, min_parity).is_some())
|
||||||
|
.unwrap_or(MAX_FEC_BLOCKS);
|
||||||
|
let k_full = data_shards.div_ceil(blocks);
|
||||||
|
let count = data_shards.div_ceil(k_full);
|
||||||
|
let mut plan = Vec::with_capacity(count);
|
||||||
|
let mut left = data_shards;
|
||||||
|
while left > 0 {
|
||||||
|
let k = left.min(k_full);
|
||||||
|
plan.push(block(k, fec_percentage, min_parity)?);
|
||||||
|
left -= k;
|
||||||
|
}
|
||||||
|
Ok(plan)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The 32 header bytes of one packet (`docs/PROTOCOL.md` 5.2).
|
||||||
|
struct Header {
|
||||||
|
sequence: u16,
|
||||||
|
timestamp: u32,
|
||||||
|
frame_index: u32,
|
||||||
|
flags: u8,
|
||||||
|
block: u8,
|
||||||
|
last_block: u8,
|
||||||
|
shard_index: u16,
|
||||||
|
data_shards: u16,
|
||||||
|
fec_percentage: u8,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Header {
|
||||||
|
fn bytes(&self) -> [u8; PAYLOAD_OFFSET] {
|
||||||
|
let fec_info = (u32::from(self.fec_percentage) << 4)
|
||||||
|
| ((u32::from(self.shard_index) & 0x3FF) << 12)
|
||||||
|
| ((u32::from(self.data_shards) & 0x3FF) << 22);
|
||||||
|
let parts: [&[u8]; 11] = [
|
||||||
|
&[VIDEO_RTP_BYTE0, 0], // RTP byte 0, payload type 0
|
||||||
|
&self.sequence.to_be_bytes(), // sequence, BE
|
||||||
|
&self.timestamp.to_be_bytes(), // timestamp, BE
|
||||||
|
&[0; 4], // SSRC 0
|
||||||
|
&[0; 4], // reserved
|
||||||
|
&(u32::from(self.sequence) << 8).to_le_bytes(), // stream packet index, LE
|
||||||
|
&self.frame_index.to_le_bytes(), // frame index, LE
|
||||||
|
&[self.flags, 0], // flags, reserved
|
||||||
|
&[MULTI_FEC_FLAGS], // multi-FEC flags (U15)
|
||||||
|
&[((self.block & 3) << 4) | ((self.last_block & 3) << 6)], // multi-FEC blocks
|
||||||
|
&fec_info.to_le_bytes(), // FEC info, LE
|
||||||
|
];
|
||||||
|
let mut out = [0u8; PAYLOAD_OFFSET];
|
||||||
|
for (dst, src) in out.iter_mut().zip(parts.iter().flat_map(|p| p.iter())) {
|
||||||
|
*dst = *src;
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The video sender of one stream.
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct VideoPacketizer {
|
||||||
|
config: VideoPacketizerConfig,
|
||||||
|
payload_len: usize,
|
||||||
|
next_sequence: u16,
|
||||||
|
/// Next GCM nonce counter (sealed streams only).
|
||||||
|
next_nonce: u64,
|
||||||
|
stats: VideoPacketizerStats,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl VideoPacketizer {
|
||||||
|
/// A sender for one stream.
|
||||||
|
///
|
||||||
|
/// # Errors
|
||||||
|
/// [`Error::Malformed`] for a `packet_size` not above the NV header size, or one whose datagrams (sealed, when a
|
||||||
|
/// cipher is set) would not fit [`MAX_VIDEO_PACKET_BYTES`], the receiver's cap.
|
||||||
|
pub fn new(config: VideoPacketizerConfig) -> Result<Self> {
|
||||||
|
let size = usize::from(config.packet_size);
|
||||||
|
let sealed = if config.cipher.is_some() { ENCRYPTION_PREFIX_LEN } else { 0 };
|
||||||
|
if size <= NV_HEADER_LEN || size + VIDEO_RTP_LEN + sealed > MAX_VIDEO_PACKET_BYTES {
|
||||||
|
return Err(malformed("video packet_size"));
|
||||||
|
}
|
||||||
|
Ok(Self {
|
||||||
|
payload_len: size - NV_HEADER_LEN,
|
||||||
|
next_sequence: config.first_sequence,
|
||||||
|
config,
|
||||||
|
next_nonce: 0,
|
||||||
|
stats: VideoPacketizerStats::default(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The largest bitstream one frame can carry: [`MAX_DATA_SHARDS_PER_FRAME`] shards of payload, and the
|
||||||
|
/// receiver's [`MAX_FRAME_BYTES`], minus the frame header.
|
||||||
|
#[must_use]
|
||||||
|
pub const fn max_bitstream_len(&self) -> usize {
|
||||||
|
let shards = MAX_DATA_SHARDS_PER_FRAME * self.payload_len;
|
||||||
|
let max = if shards < MAX_FRAME_BYTES { shards } else { MAX_FRAME_BYTES };
|
||||||
|
max - FRAME_HEADER_LEN
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Packetizes one frame into its datagrams, in send order: block 0's data shards then its parity, block 1, …
|
||||||
|
/// On error nothing changes (sequence numbers, nonce counter, stats).
|
||||||
|
///
|
||||||
|
/// # Errors
|
||||||
|
/// [`Error::TooLarge`] for a bitstream over [`Self::max_bitstream_len`] (checked before anything is allocated),
|
||||||
|
/// [`Error::State`] once the nonce counter of a sealed stream is exhausted (a new session key is needed).
|
||||||
|
pub fn packetize(&mut self, frame: &EncodedFrame<'_>) -> Result<Vec<Vec<u8>>> {
|
||||||
|
cap("video access unit", self.max_bitstream_len(), frame.bitstream.len())?;
|
||||||
|
let p = self.payload_len;
|
||||||
|
let data_len = FRAME_HEADER_LEN + frame.bitstream.len();
|
||||||
|
let n = data_len.div_ceil(p);
|
||||||
|
let plan = plan_fec_blocks(n, self.config.fec_percentage, self.config.min_required_fec_packets)?;
|
||||||
|
let total: usize = plan.iter().map(|b| usize::from(b.data_shards) + usize::from(b.parity_shards)).sum();
|
||||||
|
let sealed = self.config.cipher.is_some();
|
||||||
|
if sealed && self.next_nonce.checked_add(total as u64).is_none() {
|
||||||
|
return Err(Error::State { expected: "a fresh session key (video nonce counter exhausted)" });
|
||||||
|
}
|
||||||
|
|
||||||
|
// Frame data: header + bitstream, zero-padded to n whole shards (5.2).
|
||||||
|
let last_payload = data_len - (n - 1) * p;
|
||||||
|
let header =
|
||||||
|
write_frame_header(frame.frame_type, frame.processing_latency, u32::try_from(last_payload).unwrap_or(0));
|
||||||
|
let mut data = Vec::with_capacity(n * p);
|
||||||
|
data.extend_from_slice(&header);
|
||||||
|
data.extend_from_slice(frame.bitstream);
|
||||||
|
data.resize(n * p, 0);
|
||||||
|
|
||||||
|
let last_block = u8::try_from(plan.len() - 1).map_err(|_| malformed("video fec blocks"))?;
|
||||||
|
let mut sequence = self.next_sequence;
|
||||||
|
let mut next_header = |flags: u8, block: u8, shard_index: u16, b: &FecBlock| {
|
||||||
|
let h = Header {
|
||||||
|
sequence,
|
||||||
|
timestamp: frame.rtp_timestamp,
|
||||||
|
frame_index: frame.frame_index,
|
||||||
|
flags,
|
||||||
|
block,
|
||||||
|
last_block,
|
||||||
|
shard_index,
|
||||||
|
data_shards: b.data_shards,
|
||||||
|
fec_percentage: b.fec_percentage,
|
||||||
|
};
|
||||||
|
sequence = sequence.wrapping_add(1);
|
||||||
|
h.bytes()
|
||||||
|
};
|
||||||
|
|
||||||
|
let packet_len = PAYLOAD_OFFSET + p;
|
||||||
|
let mut out: Vec<Vec<u8>> = Vec::with_capacity(total);
|
||||||
|
let mut chunks = data.chunks(p);
|
||||||
|
let mut shard_no = 0usize;
|
||||||
|
let mut reduced = 0u64;
|
||||||
|
let mut parity_packets = 0u64;
|
||||||
|
for (bi, b) in plan.iter().enumerate() {
|
||||||
|
let block = u8::try_from(bi).map_err(|_| malformed("video fec blocks"))?;
|
||||||
|
let (k, m) = (usize::from(b.data_shards), usize::from(b.parity_shards));
|
||||||
|
reduced += u64::from(b.reduced);
|
||||||
|
let mut shards: Vec<Vec<u8>> = Vec::with_capacity(k + m);
|
||||||
|
for i in 0..k {
|
||||||
|
let mut flags = VideoFlags::PICTURE_DATA;
|
||||||
|
if shard_no == 0 {
|
||||||
|
flags |= VideoFlags::START_OF_FRAME;
|
||||||
|
}
|
||||||
|
if shard_no + 1 == n {
|
||||||
|
flags |= VideoFlags::END_OF_FRAME;
|
||||||
|
}
|
||||||
|
shard_no += 1;
|
||||||
|
let mut packet = Vec::with_capacity(packet_len);
|
||||||
|
packet.extend_from_slice(&next_header(flags, block, u16::try_from(i).unwrap_or(u16::MAX), b));
|
||||||
|
packet.extend_from_slice(chunks.next().ok_or(malformed("video frame shards"))?);
|
||||||
|
shards.push(packet);
|
||||||
|
}
|
||||||
|
if m > 0 {
|
||||||
|
// Parity over the whole data packets, headers included (5.3) ...
|
||||||
|
shards.resize_with(k + m, || vec![0u8; packet_len]);
|
||||||
|
ReedSolomon::new(k, m)?.encode(&mut shards)?;
|
||||||
|
// ... and only then the parity packets' own header fields, over their first 32 bytes.
|
||||||
|
for (j, parity) in shards.iter_mut().skip(k).enumerate() {
|
||||||
|
let h = next_header(0, block, u16::try_from(k + j).unwrap_or(u16::MAX), b);
|
||||||
|
if let Some(head) = parity.get_mut(..PAYLOAD_OFFSET) {
|
||||||
|
head.copy_from_slice(&h);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
parity_packets += m as u64;
|
||||||
|
}
|
||||||
|
out.append(&mut shards);
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Some(cipher) = &self.config.cipher {
|
||||||
|
let mut nonce = self.next_nonce;
|
||||||
|
for packet in &mut out {
|
||||||
|
*packet = cipher.encrypt(nonce, frame.frame_index, packet)?;
|
||||||
|
nonce += 1;
|
||||||
|
}
|
||||||
|
self.next_nonce = nonce;
|
||||||
|
}
|
||||||
|
self.next_sequence = sequence;
|
||||||
|
self.stats.frames += 1;
|
||||||
|
self.stats.packets += out.len() as u64;
|
||||||
|
self.stats.parity_packets += parity_packets;
|
||||||
|
self.stats.fec_reduced_blocks += reduced;
|
||||||
|
Ok(out)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The RTP sequence number of the next datagram.
|
||||||
|
#[must_use]
|
||||||
|
pub const fn next_sequence(&self) -> u16 {
|
||||||
|
self.next_sequence
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Counters.
|
||||||
|
#[must_use]
|
||||||
|
pub const fn stats(&self) -> VideoPacketizerStats {
|
||||||
|
self.stats
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,261 @@
|
|||||||
|
//! 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<u8>]) -> Vec<AudioEvent> {
|
||||||
|
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<u8> {
|
||||||
|
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<u8>], duration: u8) -> (Vec<Vec<u8>>, Vec<AudioEvent>) {
|
||||||
|
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, 0x0104, 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, 0x04, // sequence 0x0104, 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()), (0x0105, 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<Vec<u8>> = (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<Vec<u8>> = (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, 0xFFFC, 100, 10);
|
||||||
|
let mut seen = Vec::new();
|
||||||
|
for _ in 0..6 {
|
||||||
|
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![(0xFFFC, 100), (0xFFFD, 110), (0xFFFE, 120), (0xFFFF, 130), (0x0000, 140), (0x0001, 150)]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[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<Vec<u8>> = (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, 4, 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");
|
||||||
|
// Blocks start at multiples of 4 (6.4), and the receiver counts from the first block's start: a stream that
|
||||||
|
// began at 5 would make it report 4 as lost.
|
||||||
|
for first in [1u16, 2, 3, 5, 0xFFFF] {
|
||||||
|
assert_err!(AudioPacketizer::new(cfg(true, first, 0, 5)), Error::Malformed { .. }, "first sequence {first}");
|
||||||
|
}
|
||||||
|
assert!(AudioPacketizer::new(cfg(true, 0xFFFC, 0, 5)).is_ok());
|
||||||
|
assert_eq!(AudioParity::default(), AudioParity::None);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ================================================================================================ generated
|
||||||
|
|
||||||
|
proptest! {
|
||||||
|
#![proptest_config(ProptestConfig { cases: 64, ..ProptestConfig::default() })]
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn generated_round_trips(
|
||||||
|
seed in any::<u64>(),
|
||||||
|
first_sequence in any::<u16>(),
|
||||||
|
first_ts in any::<u32>(),
|
||||||
|
duration in 1u8..=40,
|
||||||
|
count in 1usize..80,
|
||||||
|
encrypt in any::<bool>(),
|
||||||
|
) {
|
||||||
|
let mut rng = SeqRng::new(seed);
|
||||||
|
let mut tx = sender(encrypt, first_sequence & !3, first_ts, duration);
|
||||||
|
let max = tx.max_opus_len();
|
||||||
|
let payloads: Vec<Vec<u8>> = (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);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,825 @@
|
|||||||
|
//! The video packetizer, host side (`docs/PROTOCOL.md` 5.2, 5.3, 7), checked against the client half: every frame
|
||||||
|
//! goes through the crate's own `VideoDepacketizer` and must come out identical and in order, also with up to `m`
|
||||||
|
//! packets of every block lost, reordered or duplicated; with more lost, the frame is reported lost, never corrupt.
|
||||||
|
//! Fixed vectors check one small frame byte by byte against the field table of 5.2, and the parity against an
|
||||||
|
//! independent GF(2^8) encoder with the Cauchy matrix of 5.3.
|
||||||
|
|
||||||
|
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::indexing_slicing, missing_docs)]
|
||||||
|
|
||||||
|
mod common;
|
||||||
|
|
||||||
|
use core::time::Duration;
|
||||||
|
use std::collections::BTreeMap;
|
||||||
|
|
||||||
|
use common::{SeqRng, gf};
|
||||||
|
use domistream::fec::parity_count;
|
||||||
|
use domistream::video::packet::{
|
||||||
|
FRAME_HEADER_LEN, MAX_FEC_BLOCKS, MAX_VIDEO_PACKET_BYTES, PAYLOAD_OFFSET, parse_frame_header, parse_video_packet,
|
||||||
|
};
|
||||||
|
use domistream::video::packetizer::{
|
||||||
|
EncodedFrame, MAX_DATA_SHARDS_PER_FRAME, VideoPacketizer, VideoPacketizerConfig, VideoPacketizerStats,
|
||||||
|
plan_fec_blocks, write_frame_header,
|
||||||
|
};
|
||||||
|
use domistream::video::{
|
||||||
|
ENCRYPTION_PREFIX_LEN, FrameType, MAX_FRAME_BYTES, VideoCipher, VideoConfig, VideoDepacketizer, VideoEvent,
|
||||||
|
VideoFrame,
|
||||||
|
};
|
||||||
|
use domistream::{Error, Instant};
|
||||||
|
use proptest::prelude::*;
|
||||||
|
|
||||||
|
const KEY: [u8; 16] = *b"video-pack-key!!";
|
||||||
|
|
||||||
|
fn config(packet_size: u16, pct: u8, min: u8, encrypt: bool, first_sequence: u16) -> VideoPacketizerConfig {
|
||||||
|
VideoPacketizerConfig {
|
||||||
|
packet_size,
|
||||||
|
fec_percentage: pct,
|
||||||
|
min_required_fec_packets: min,
|
||||||
|
cipher: encrypt.then(|| VideoCipher::new(KEY)),
|
||||||
|
first_sequence,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn sender(packet_size: u16, pct: u8, min: u8, encrypt: bool, first_sequence: u16) -> VideoPacketizer {
|
||||||
|
VideoPacketizer::new(config(packet_size, pct, min, encrypt, first_sequence)).expect("VideoPacketizer::new")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn receiver(packet_size: u16, encrypt: bool) -> VideoDepacketizer {
|
||||||
|
VideoDepacketizer::new(VideoConfig {
|
||||||
|
packet_size,
|
||||||
|
cipher: encrypt.then(|| VideoCipher::new(KEY)),
|
||||||
|
frame_timeout: Duration::from_millis(50),
|
||||||
|
})
|
||||||
|
.expect("VideoDepacketizer::new")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A bitstream of exactly `len` bytes: a start code, then random bytes, every third frame with a zero tail (the
|
||||||
|
/// frame header's last-payload length, not the content, says where the frame ends).
|
||||||
|
fn bitstream(rng: &mut SeqRng, len: usize) -> Vec<u8> {
|
||||||
|
let mut b = rng.bytes(len);
|
||||||
|
for (dst, src) in b.iter_mut().zip([0u8, 0, 0, 1, 0x65]) {
|
||||||
|
*dst = src;
|
||||||
|
}
|
||||||
|
if rng.below(3) == 0 {
|
||||||
|
let tail = rng.below(len / 2 + 1);
|
||||||
|
for x in &mut b[len - tail..] {
|
||||||
|
*x = 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
b
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One frame as sent.
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
struct Sent {
|
||||||
|
index: u32,
|
||||||
|
frame_type: FrameType,
|
||||||
|
latency: u16,
|
||||||
|
timestamp: u32,
|
||||||
|
bitstream: Vec<u8>,
|
||||||
|
datagrams: Vec<Vec<u8>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn send_bytes(tx: &mut VideoPacketizer, rng: &mut SeqRng, index: u32, bitstream: Vec<u8>) -> Sent {
|
||||||
|
let frame_type = [FrameType::Predicted, FrameType::Key, FrameType::Recovery][rng.below(3)];
|
||||||
|
let latency = rng.below(65_536) as u16;
|
||||||
|
let timestamp = rng.next_u64() as u32;
|
||||||
|
let frame = EncodedFrame {
|
||||||
|
frame_index: index,
|
||||||
|
frame_type,
|
||||||
|
rtp_timestamp: timestamp,
|
||||||
|
processing_latency: latency,
|
||||||
|
bitstream: &bitstream,
|
||||||
|
};
|
||||||
|
let datagrams = tx.packetize(&frame).expect("packetize");
|
||||||
|
Sent { index, frame_type, latency, timestamp, bitstream, datagrams }
|
||||||
|
}
|
||||||
|
|
||||||
|
fn send(tx: &mut VideoPacketizer, rng: &mut SeqRng, index: u32, len: usize) -> Sent {
|
||||||
|
let b = bitstream(rng, len);
|
||||||
|
send_bytes(tx, rng, index, b)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn plain(datagram: &[u8], encrypt: bool) -> Vec<u8> {
|
||||||
|
if encrypt { VideoCipher::new(KEY).decrypt(datagram).expect("decrypt our own datagram") } else { datagram.to_vec() }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A datagram's place in its frame, read from its plaintext.
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||||
|
struct Place {
|
||||||
|
block: u8,
|
||||||
|
shard: u16,
|
||||||
|
k: u16,
|
||||||
|
m: u16,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn place(datagram: &[u8], encrypt: bool) -> Place {
|
||||||
|
let bytes = plain(datagram, encrypt);
|
||||||
|
let p = parse_video_packet(&bytes).expect("our own datagram parses");
|
||||||
|
let k = p.nv.fec.data_shards;
|
||||||
|
let m = parity_count(usize::from(k), p.nv.fec.fec_percentage).expect("consistent FEC fields") as u16;
|
||||||
|
Place { block: p.nv.fec.block_index, shard: p.nv.fec.shard_index, k, m }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Datagram positions of each block, and the block's parity count.
|
||||||
|
fn blocks_of(sent: &Sent, encrypt: bool) -> BTreeMap<u8, (Vec<usize>, usize)> {
|
||||||
|
let mut out: BTreeMap<u8, (Vec<usize>, usize)> = BTreeMap::new();
|
||||||
|
for (i, d) in sent.datagrams.iter().enumerate() {
|
||||||
|
let p = place(d, encrypt);
|
||||||
|
let e = out.entry(p.block).or_insert_with(|| (Vec::new(), usize::from(p.m)));
|
||||||
|
e.0.push(i);
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The frame's datagrams with, in every block, a random subset of `extra(m)` lost (`extra = 0` keeps all).
|
||||||
|
fn with_loss(rng: &mut SeqRng, sent: &Sent, encrypt: bool, lose: impl Fn(&mut SeqRng, usize) -> usize) -> Vec<Vec<u8>> {
|
||||||
|
let mut keep = vec![true; sent.datagrams.len()];
|
||||||
|
for (positions, m) in blocks_of(sent, encrypt).values() {
|
||||||
|
let n = lose(rng, *m).min(positions.len());
|
||||||
|
for i in rng.subset(positions.len(), n) {
|
||||||
|
keep[positions[i]] = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
sent.datagrams.iter().zip(keep).filter(|(_, k)| *k).map(|(d, _)| d.clone()).collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Default)]
|
||||||
|
struct Out {
|
||||||
|
frames: Vec<VideoFrame>,
|
||||||
|
lost: Vec<(u32, u32)>,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn drain(rx: &mut VideoDepacketizer, out: &mut Out) {
|
||||||
|
while let Some(e) = rx.poll_event() {
|
||||||
|
match e {
|
||||||
|
VideoEvent::Frame(f) => out.frames.push(f),
|
||||||
|
VideoEvent::FrameLost { first, last } => out.lost.push((first, last)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn receive(rx: &mut VideoDepacketizer, datagrams: &[Vec<u8>]) -> Out {
|
||||||
|
let mut now = 1_000_000u64;
|
||||||
|
let mut out = Out::default();
|
||||||
|
for d in datagrams {
|
||||||
|
rx.push(Instant::from_micros(now), d).expect("push never fails within the size cap");
|
||||||
|
now += 10;
|
||||||
|
drain(rx, &mut out);
|
||||||
|
}
|
||||||
|
for _ in 0..64 {
|
||||||
|
now += 10_000_000;
|
||||||
|
rx.handle_timeout(Instant::from_micros(now)).unwrap();
|
||||||
|
drain(rx, &mut out);
|
||||||
|
if rx.poll_timeout().is_none() {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Every frame not in `lost` came out identical and in order; every frame in `lost` is in a FrameLost range.
|
||||||
|
fn check(sent: &[Sent], lost: &[u32], out: &Out) {
|
||||||
|
let want: Vec<&Sent> = sent.iter().filter(|s| !lost.contains(&s.index)).collect();
|
||||||
|
assert_eq!(
|
||||||
|
out.frames.iter().map(|f| f.frame_index).collect::<Vec<_>>(),
|
||||||
|
want.iter().map(|s| s.index).collect::<Vec<_>>(),
|
||||||
|
"frames delivered (lost ranges {:?})",
|
||||||
|
out.lost
|
||||||
|
);
|
||||||
|
for (f, s) in out.frames.iter().zip(&want) {
|
||||||
|
assert!(
|
||||||
|
f.bitstream == s.bitstream,
|
||||||
|
"frame {} differs: {} bytes, want {}",
|
||||||
|
s.index,
|
||||||
|
f.bitstream.len(),
|
||||||
|
s.bitstream.len()
|
||||||
|
);
|
||||||
|
assert_eq!(f.header.header_type, 0x01, "frame {} header type", s.index);
|
||||||
|
assert_eq!(f.header.frame_type, s.frame_type, "frame {} type", s.index);
|
||||||
|
assert_eq!(f.header.processing_latency, s.latency, "frame {} latency", s.index);
|
||||||
|
assert_eq!(f.rtp_timestamp, s.timestamp, "frame {} timestamp", s.index);
|
||||||
|
}
|
||||||
|
for &l in lost {
|
||||||
|
assert!(
|
||||||
|
out.lost.iter().any(|&(a, b)| l.wrapping_sub(a) <= b.wrapping_sub(a)),
|
||||||
|
"frame {l} was not reported lost: {:?}",
|
||||||
|
out.lost
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Checks every field of every datagram of a frame against PROTOCOL.md 5.2/5.3 and returns the next sequence.
|
||||||
|
fn check_layout(s: &Sent, packet_size: u16, pct: u8, min: u8, encrypt: bool, first_sequence: u16) -> u16 {
|
||||||
|
let payload = usize::from(packet_size) - 16;
|
||||||
|
let n = (FRAME_HEADER_LEN + s.bitstream.len()).div_ceil(payload);
|
||||||
|
let plan = plan_fec_blocks(n, pct, min).expect("plan");
|
||||||
|
let total: usize = plan.iter().map(|b| usize::from(b.data_shards) + usize::from(b.parity_shards)).sum();
|
||||||
|
assert_eq!(s.datagrams.len(), total, "frame {}: datagram count", s.index);
|
||||||
|
let last_block = (plan.len() - 1) as u8;
|
||||||
|
let mut seq = first_sequence;
|
||||||
|
let mut it = s.datagrams.iter();
|
||||||
|
let mut data_seen = 0usize;
|
||||||
|
for (b, blk) in plan.iter().enumerate() {
|
||||||
|
let (k, m) = (usize::from(blk.data_shards), usize::from(blk.parity_shards));
|
||||||
|
assert_eq!(m, parity_count(k, blk.fec_percentage).unwrap(), "plan m = ceil(k * pct / 100)");
|
||||||
|
for shard in 0..k + m {
|
||||||
|
let d = it.next().expect("datagram");
|
||||||
|
let extra = if encrypt { ENCRYPTION_PREFIX_LEN } else { 0 };
|
||||||
|
assert_eq!(d.len(), usize::from(packet_size) + 16 + extra, "datagram length");
|
||||||
|
let bytes = plain(d, encrypt);
|
||||||
|
let p = parse_video_packet(&bytes).expect("parses");
|
||||||
|
assert_eq!(bytes[0], 0x90, "RTP byte 0");
|
||||||
|
assert_eq!(p.rtp.payload_type, 0);
|
||||||
|
assert_eq!(p.rtp.sequence, seq, "sequence numbers are consecutive");
|
||||||
|
assert_eq!(p.rtp.timestamp, s.timestamp);
|
||||||
|
assert_eq!(p.rtp.ssrc, 0);
|
||||||
|
assert_eq!(&bytes[12..16], &[0, 0, 0, 0], "reserved");
|
||||||
|
assert_eq!(p.nv.stream_packet_index, u32::from(seq) << 8, "stream packet index");
|
||||||
|
assert_eq!(p.nv.frame_index, s.index);
|
||||||
|
assert_eq!(bytes[25], 0, "reserved byte 25");
|
||||||
|
assert_eq!(p.nv.multi_fec_flags, 0x10, "multi-FEC flags (U15)");
|
||||||
|
assert_eq!(bytes[27] & 0x0F, 0, "multi-FEC blocks low bits");
|
||||||
|
assert_eq!(bytes[28] & 0x0F, 0, "FEC info low bits");
|
||||||
|
assert_eq!(p.nv.fec.block_index, b as u8);
|
||||||
|
assert_eq!(p.nv.fec.last_block_index, last_block);
|
||||||
|
assert_eq!(usize::from(p.nv.fec.shard_index), shard, "data first, then parity");
|
||||||
|
assert_eq!(usize::from(p.nv.fec.data_shards), k);
|
||||||
|
assert_eq!(p.nv.fec.fec_percentage, blk.fec_percentage);
|
||||||
|
let flags = p.nv.flags.0;
|
||||||
|
if shard < k {
|
||||||
|
let mut want = 0x01;
|
||||||
|
if data_seen == 0 {
|
||||||
|
want |= 0x04;
|
||||||
|
}
|
||||||
|
if data_seen == n - 1 {
|
||||||
|
want |= 0x02;
|
||||||
|
}
|
||||||
|
assert_eq!(flags, want, "frame {} data shard {data_seen} flags", s.index);
|
||||||
|
data_seen += 1;
|
||||||
|
} else {
|
||||||
|
assert_eq!(flags, 0, "parity flags");
|
||||||
|
}
|
||||||
|
seq = seq.wrapping_add(1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
assert_eq!(data_seen, n);
|
||||||
|
seq
|
||||||
|
}
|
||||||
|
|
||||||
|
fn sizes(rng: &mut SeqRng, payload: usize, count: usize) -> Vec<usize> {
|
||||||
|
let max = MAX_DATA_SHARDS_PER_FRAME * payload - FRAME_HEADER_LEN;
|
||||||
|
// Around the shard boundaries: frame data (8 + len) of exactly one and two shards, and one byte either side.
|
||||||
|
let mut out = vec![0, 1];
|
||||||
|
for edge in [payload, 2 * payload] {
|
||||||
|
let at = edge.saturating_sub(FRAME_HEADER_LEN);
|
||||||
|
out.extend([at.saturating_sub(1), at, at + 1]);
|
||||||
|
}
|
||||||
|
while out.len() < count {
|
||||||
|
out.push(match rng.below(4) {
|
||||||
|
0 => rng.below(payload * 3),
|
||||||
|
1 => rng.below(payload * 40),
|
||||||
|
_ => rng.below(payload * 300),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
out.into_iter().map(|s| s.min(max)).collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
const PACKET_SIZES: [u16; 9] = [17, 18, 20, 64, 100, 1024, 1040, 1408, 4080];
|
||||||
|
const PERCENTAGES: [u8; 8] = [0, 1, 10, 20, 50, 100, 200, 255];
|
||||||
|
|
||||||
|
// ================================================================================================ fixed vectors
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn fixed_vector_one_small_frame() {
|
||||||
|
// packetSize 32: 16 bytes of payload per datagram. Frame data = 8-byte header + 7-byte bitstream = 15 bytes,
|
||||||
|
// so one data shard (zero-padded to 16) and, at 100 %, ceil(1 * 100 / 100) = 1 parity shard.
|
||||||
|
let mut tx = sender(32, 100, 0, false, 0x1234);
|
||||||
|
let bitstream = [0x00, 0x00, 0x00, 0x01, 0x65, 0xAA, 0xBB];
|
||||||
|
let frame = EncodedFrame {
|
||||||
|
frame_index: 7,
|
||||||
|
frame_type: FrameType::Key,
|
||||||
|
rtp_timestamp: 90_000,
|
||||||
|
processing_latency: 0x0102,
|
||||||
|
bitstream: &bitstream,
|
||||||
|
};
|
||||||
|
let out = tx.packetize(&frame).unwrap();
|
||||||
|
#[rustfmt::skip]
|
||||||
|
let payload: [u8; 16] = [
|
||||||
|
0x01, // frame header type
|
||||||
|
0x02, 0x01, // processing latency 0x0102, LE
|
||||||
|
0x02, // frame type: key
|
||||||
|
0x0F, 0x00, 0x00, 0x00, // last shard payload length 15, LE
|
||||||
|
0x00, 0x00, 0x00, 0x01, 0x65, 0xAA, 0xBB, // the bitstream
|
||||||
|
0x00, // zero padding to the full shard
|
||||||
|
];
|
||||||
|
#[rustfmt::skip]
|
||||||
|
let mut data = vec![
|
||||||
|
0x90, // RTP byte 0: version 2, extension bit
|
||||||
|
0x00, // payload type 0
|
||||||
|
0x12, 0x34, // sequence 0x1234, BE
|
||||||
|
0x00, 0x01, 0x5F, 0x90, // timestamp 90000, BE
|
||||||
|
0x00, 0x00, 0x00, 0x00, // SSRC 0
|
||||||
|
0x00, 0x00, 0x00, 0x00, // reserved
|
||||||
|
0x00, 0x34, 0x12, 0x00, // stream packet index 0x1234 << 8 = 0x00123400, LE
|
||||||
|
0x07, 0x00, 0x00, 0x00, // frame index 7, LE
|
||||||
|
0x07, // flags: picture data 0x01 | end of frame 0x02 | start of frame 0x04
|
||||||
|
0x00, // reserved
|
||||||
|
0x10, // multi-FEC flags (U15)
|
||||||
|
0x00, // multi-FEC blocks: this block 0 (bits 4-5), last block 0 (bits 6-7)
|
||||||
|
0x40, 0x06, 0x40, 0x00, // FEC info 0x00400640, LE: 100 << 4 | shard 0 << 12 | k 1 << 22
|
||||||
|
];
|
||||||
|
data.extend_from_slice(&payload);
|
||||||
|
#[rustfmt::skip]
|
||||||
|
let mut parity = vec![
|
||||||
|
0x90, 0x00, // RTP byte 0, payload type 0
|
||||||
|
0x12, 0x35, // sequence 0x1235: the parity packet takes the next number
|
||||||
|
0x00, 0x01, 0x5F, 0x90, // the frame's timestamp
|
||||||
|
0x00, 0x00, 0x00, 0x00, // SSRC 0
|
||||||
|
0x00, 0x00, 0x00, 0x00, // reserved
|
||||||
|
0x00, 0x35, 0x12, 0x00, // stream packet index 0x1235 << 8, LE
|
||||||
|
0x07, 0x00, 0x00, 0x00, // frame index 7
|
||||||
|
0x00, // flags 0 on parity packets
|
||||||
|
0x00, // reserved
|
||||||
|
0x10, // multi-FEC flags
|
||||||
|
0x00, // block 0 of 0
|
||||||
|
0x40, 0x16, 0x40, 0x00, // FEC info 0x00401640: 100 << 4 | shard 1 << 12 | k 1 << 22
|
||||||
|
];
|
||||||
|
// k = 1, m = 1: the Cauchy matrix is [[1 / ((1 + 0) XOR 0)]] = [[1]], so the parity is the data packet itself
|
||||||
|
// and its payload part equals the data payload.
|
||||||
|
parity.extend_from_slice(&payload);
|
||||||
|
assert_eq!(out, vec![data, parity]);
|
||||||
|
assert_eq!(tx.next_sequence(), 0x1236);
|
||||||
|
assert_eq!(tx.stats(), VideoPacketizerStats { frames: 1, packets: 2, parity_packets: 1, fec_reduced_blocks: 0 });
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn fixed_vector_cauchy_parity_k3_m1() {
|
||||||
|
// packetSize 20: 4 bytes of payload. 8 + 4 = 12 bytes of frame data = 3 data shards, last one full (4 bytes).
|
||||||
|
// At 33 %: m = ceil(3 * 33 / 100) = 1. PROTOCOL.md 5.3 gives P = [01 8e f4] for k = 3, m = 1.
|
||||||
|
let mut tx = sender(20, 33, 0, false, 0);
|
||||||
|
let bitstream = [0x00, 0x00, 0x01, 0x09];
|
||||||
|
let frame = EncodedFrame {
|
||||||
|
frame_index: 0x0102_0304,
|
||||||
|
frame_type: FrameType::Predicted,
|
||||||
|
rtp_timestamp: 1,
|
||||||
|
processing_latency: 0xBEEF,
|
||||||
|
bitstream: &bitstream,
|
||||||
|
};
|
||||||
|
let out = tx.packetize(&frame).unwrap();
|
||||||
|
assert_eq!(out.len(), 4);
|
||||||
|
let shards: [[u8; 4]; 3] = [
|
||||||
|
[0x01, 0xEF, 0xBE, 0x01], // header type, latency 0xBEEF LE, predicted
|
||||||
|
[0x04, 0x00, 0x00, 0x00], // last shard payload length 4, LE
|
||||||
|
[0x00, 0x00, 0x01, 0x09], // bitstream
|
||||||
|
];
|
||||||
|
for (i, s) in shards.iter().enumerate() {
|
||||||
|
assert_eq!(&out[i][PAYLOAD_OFFSET..], s, "data shard {i}");
|
||||||
|
// FEC info: 33 << 4 | i << 12 | 3 << 22
|
||||||
|
let info = (33u32 << 4) | ((i as u32) << 12) | (3 << 22);
|
||||||
|
assert_eq!(&out[i][28..32], &info.to_le_bytes(), "FEC info of shard {i}");
|
||||||
|
}
|
||||||
|
let p = [0x01u8, 0x8E, 0xF4];
|
||||||
|
let want: Vec<u8> = (0..4).map(|x| (0..3).fold(0, |acc, i| acc ^ gf::mul(p[i], shards[i][x]))).collect();
|
||||||
|
assert_eq!(&out[3][PAYLOAD_OFFSET..], want.as_slice(), "parity = 01*d0 + 8e*d1 + f4*d2");
|
||||||
|
assert_eq!(&out[3][28..32], &((33u32 << 4) | (3 << 12) | (3 << 22)).to_le_bytes(), "parity FEC info");
|
||||||
|
assert_eq!(out[3][24], 0, "parity flags");
|
||||||
|
assert_eq!(&out[3][2..4], &3u16.to_be_bytes(), "parity sequence");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn frame_header_writer_round_trips() {
|
||||||
|
for (t, byte) in
|
||||||
|
[(FrameType::Predicted, 1u8), (FrameType::Key, 2), (FrameType::Recovery, 5), (FrameType::Other(9), 9)]
|
||||||
|
{
|
||||||
|
for (lat, last) in [(0u16, 1u32), (0xFFFF, 4064), (0x1234, 0x0A0B_0C0D)] {
|
||||||
|
let h = write_frame_header(t, lat, last);
|
||||||
|
let mut want = vec![0x01];
|
||||||
|
want.extend_from_slice(&lat.to_le_bytes());
|
||||||
|
want.push(byte);
|
||||||
|
want.extend_from_slice(&last.to_le_bytes());
|
||||||
|
assert_eq!(h.to_vec(), want);
|
||||||
|
let back = parse_frame_header(&h).unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
(back.header_type, back.processing_latency, back.frame_type, back.last_payload_len),
|
||||||
|
(1, lat, t, last)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ================================================================================================ the FEC plan
|
||||||
|
|
||||||
|
/// Parity the client asks for a block of `k`: `max(ceil(k * pct / 100), min)`.
|
||||||
|
fn target(k: usize, pct: u8, min: u8) -> usize {
|
||||||
|
(k * usize::from(pct)).div_ceil(100).max(usize::from(min))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Parity a block of `k` gets at percentage `p` (the receiver's formula).
|
||||||
|
fn m_at(k: usize, p: usize) -> usize {
|
||||||
|
(k * p).div_ceil(100)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether the least percentage (at or above the request) that gives a block of `k` its target is an 8-bit value
|
||||||
|
/// and keeps the block within 255 shards. Parity comes in steps of `ceil(k * p / 100)`, so for `k > 100` the least
|
||||||
|
/// step can overshoot the target.
|
||||||
|
fn achievable(k: usize, pct: u8, min: u8) -> bool {
|
||||||
|
let t = target(k, pct, min);
|
||||||
|
let p = (usize::from(pct)..=255).find(|&p| m_at(k, p) >= t);
|
||||||
|
k <= 255 && p.is_some_and(|p| k + m_at(k, p) <= 255)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn fec_plan_properties() {
|
||||||
|
for n in (1..=MAX_DATA_SHARDS_PER_FRAME).filter(|n| *n < 40 || n % 7 == 0 || *n > 1000) {
|
||||||
|
for pct in PERCENTAGES.into_iter().chain([3, 33, 34, 99]) {
|
||||||
|
for min in [0u8, 1, 2, 3, 4, 10, 255] {
|
||||||
|
let ctx = format!("n {n} pct {pct} min {min}");
|
||||||
|
let plan = plan_fec_blocks(n, pct, min).unwrap();
|
||||||
|
assert!((1..=MAX_FEC_BLOCKS).contains(&plan.len()), "{ctx}: {} blocks", plan.len());
|
||||||
|
assert_eq!(plan.iter().map(|b| usize::from(b.data_shards)).sum::<usize>(), n, "{ctx}");
|
||||||
|
let first_k = plan[0].data_shards;
|
||||||
|
for (i, b) in plan.iter().enumerate() {
|
||||||
|
let (k, m, p) =
|
||||||
|
(usize::from(b.data_shards), usize::from(b.parity_shards), usize::from(b.fec_percentage));
|
||||||
|
assert!(k >= 1 && k + m <= 255, "{ctx}: k {k} m {m}");
|
||||||
|
assert_eq!(m, parity_count(k, b.fec_percentage).unwrap(), "{ctx}: m follows from the percentage");
|
||||||
|
if i + 1 < plan.len() {
|
||||||
|
assert_eq!(b.data_shards, first_k, "{ctx}: every block but the last carries the same k");
|
||||||
|
} else {
|
||||||
|
assert!(b.data_shards <= first_k, "{ctx}");
|
||||||
|
}
|
||||||
|
let t = target(k, pct, min);
|
||||||
|
assert_eq!(
|
||||||
|
b.reduced,
|
||||||
|
!achievable(k, pct, min),
|
||||||
|
"{ctx}: reduced exactly when the target cannot fit"
|
||||||
|
);
|
||||||
|
if b.reduced {
|
||||||
|
// The most parity that fits: one percent more would not.
|
||||||
|
assert!(m < t, "{ctx}");
|
||||||
|
assert!(p == 255 || k + m_at(k, p + 1) > 255, "{ctx}: k {k} p {p}: not the most that fits");
|
||||||
|
} else {
|
||||||
|
// The least percentage, at or above the request, that gives the target.
|
||||||
|
assert!(m >= t && p >= usize::from(pct), "{ctx}: k {k} m {m} p {p}");
|
||||||
|
assert!(p == usize::from(pct) || m_at(k, p - 1) < t, "{ctx}: k {k} p {p}: raised too far");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Fewest blocks: one block fewer could not carry the frame with the requested parity.
|
||||||
|
if plan.len() > 1 && !plan[0].reduced {
|
||||||
|
let fewer = plan.len() - 1;
|
||||||
|
assert!(!achievable(n.div_ceil(fewer), pct, min), "{ctx}: {} blocks where {fewer} do", plan.len());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
assert_err!(plan_fec_blocks(0, 20, 0), Error::Malformed { .. });
|
||||||
|
assert_too_large!(
|
||||||
|
plan_fec_blocks(MAX_DATA_SHARDS_PER_FRAME + 1, 0, 0),
|
||||||
|
MAX_DATA_SHARDS_PER_FRAME,
|
||||||
|
MAX_DATA_SHARDS_PER_FRAME + 1
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn minimum_parity_raises_the_written_percentage() {
|
||||||
|
// One data shard at 0 % with at least 2 parity packets: 101 % is the smallest percentage giving
|
||||||
|
// m = ceil(1 * 101 / 100) = 2.
|
||||||
|
let plan = plan_fec_blocks(1, 0, 2).unwrap();
|
||||||
|
assert_eq!((plan[0].data_shards, plan[0].parity_shards, plan[0].fec_percentage), (1, 2, 101));
|
||||||
|
// 3 shards, at least 2: 34 % (ceil(1.02) = 2), not 67 % (which would give 3).
|
||||||
|
let plan = plan_fec_blocks(3, 0, 2).unwrap();
|
||||||
|
assert_eq!((plan[0].parity_shards, plan[0].fec_percentage), (2, 34));
|
||||||
|
// Already enough: unchanged.
|
||||||
|
let plan = plan_fec_blocks(10, 50, 2).unwrap();
|
||||||
|
assert_eq!((plan[0].parity_shards, plan[0].fec_percentage, plan[0].reduced), (5, 50, false));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ================================================================================================ round trips
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn round_trip_random_sizes() {
|
||||||
|
for seed in 0..12u64 {
|
||||||
|
let mut rng = SeqRng::new(seed);
|
||||||
|
let packet_size =
|
||||||
|
if seed < PACKET_SIZES.len() as u64 { PACKET_SIZES[seed as usize] } else { 17 + rng.below(4064) as u16 };
|
||||||
|
let pct = PERCENTAGES[rng.below(PERCENTAGES.len())];
|
||||||
|
let min = [0u8, 1, 2, 4][rng.below(4)];
|
||||||
|
let payload = usize::from(packet_size) - 16;
|
||||||
|
let first_sequence = rng.next_u64() as u16;
|
||||||
|
let mut tx = sender(packet_size, pct, min, false, first_sequence);
|
||||||
|
let mut seq = first_sequence;
|
||||||
|
let first_index = rng.next_u64() as u32;
|
||||||
|
let sent: Vec<Sent> = sizes(&mut rng, payload, 16)
|
||||||
|
.into_iter()
|
||||||
|
.enumerate()
|
||||||
|
.map(|(i, len)| send(&mut tx, &mut rng, first_index.wrapping_add(i as u32), len))
|
||||||
|
.collect();
|
||||||
|
for s in &sent {
|
||||||
|
seq = check_layout(s, packet_size, pct, min, false, seq);
|
||||||
|
}
|
||||||
|
assert_eq!(tx.next_sequence(), seq);
|
||||||
|
let all: Vec<Vec<u8>> = sent.iter().flat_map(|s| s.datagrams.clone()).collect();
|
||||||
|
check(&sent, &[], &receive(&mut receiver(packet_size, false), &all));
|
||||||
|
let stats = tx.stats();
|
||||||
|
assert_eq!(stats.frames, sent.len() as u64);
|
||||||
|
assert_eq!(stats.packets, all.len() as u64);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn round_trip_with_up_to_m_lost_per_block() {
|
||||||
|
for seed in 100..112u64 {
|
||||||
|
let mut rng = SeqRng::new(seed);
|
||||||
|
let packet_size = PACKET_SIZES[rng.below(PACKET_SIZES.len())];
|
||||||
|
let pct = [10u8, 20, 50, 100, 200, 255][rng.below(6)];
|
||||||
|
let min = [0u8, 1, 2][rng.below(3)];
|
||||||
|
let payload = usize::from(packet_size) - 16;
|
||||||
|
let mut tx = sender(packet_size, pct, min, false, rng.next_u64() as u16);
|
||||||
|
let sent: Vec<Sent> = sizes(&mut rng, payload, 14)
|
||||||
|
.into_iter()
|
||||||
|
.enumerate()
|
||||||
|
.map(|(i, l)| send(&mut tx, &mut rng, i as u32, l))
|
||||||
|
.collect();
|
||||||
|
let mut datagrams = Vec::new();
|
||||||
|
for s in &sent {
|
||||||
|
datagrams.extend(with_loss(&mut rng, s, false, |r, m| if r.below(3) == 0 { m } else { r.below(m + 1) }));
|
||||||
|
}
|
||||||
|
let out = receive(&mut receiver(packet_size, false), &datagrams);
|
||||||
|
check(&sent, &[], &out);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn every_data_shard_lost_is_rebuilt_when_parity_covers_it() {
|
||||||
|
// 100 %: m = k, so the parity alone carries the frame.
|
||||||
|
let mut rng = SeqRng::new(7);
|
||||||
|
let mut tx = sender(64, 100, 0, false, 0);
|
||||||
|
let sent: Vec<Sent> = (0..6).map(|i| send(&mut tx, &mut rng, i, 48 * (1 + 5 * i as usize))).collect();
|
||||||
|
let mut datagrams = Vec::new();
|
||||||
|
for s in &sent {
|
||||||
|
datagrams.extend(s.datagrams.iter().filter(|d| place(d, false).shard >= place(d, false).k).cloned());
|
||||||
|
}
|
||||||
|
let out = receive(&mut receiver(64, false), &datagrams);
|
||||||
|
check(&sent, &[], &out);
|
||||||
|
assert!(out.frames.iter().all(|f| f.recovered_shards > 0));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn more_than_m_lost_reports_the_frame_lost() {
|
||||||
|
for seed in 200..216u64 {
|
||||||
|
let mut rng = SeqRng::new(seed);
|
||||||
|
let packet_size = PACKET_SIZES[1 + rng.below(PACKET_SIZES.len() - 1)];
|
||||||
|
let pct = [0u8, 10, 20, 50, 100][rng.below(5)];
|
||||||
|
let payload = usize::from(packet_size) - 16;
|
||||||
|
let mut tx = sender(packet_size, pct, 0, false, 0xFFF0);
|
||||||
|
let sent: Vec<Sent> = (0..7)
|
||||||
|
.map(|i| {
|
||||||
|
let len = 1 + rng.below(payload * 30);
|
||||||
|
send(&mut tx, &mut rng, 1000 + i, len)
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
let victim = 1 + rng.below(5);
|
||||||
|
let mut datagrams = Vec::new();
|
||||||
|
for (i, s) in sent.iter().enumerate() {
|
||||||
|
if i == victim {
|
||||||
|
// One block loses m + 1 packets, the others up to m.
|
||||||
|
let blocks = blocks_of(s, false);
|
||||||
|
let hit = *blocks.keys().nth(rng.below(blocks.len())).unwrap();
|
||||||
|
let mut keep = vec![true; s.datagrams.len()];
|
||||||
|
for (b, (positions, m)) in &blocks {
|
||||||
|
let n = if *b == hit { m + 1 } else { rng.below(m + 1) };
|
||||||
|
for j in rng.subset(positions.len(), n) {
|
||||||
|
keep[positions[j]] = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
datagrams.extend(s.datagrams.iter().zip(keep).filter(|(_, k)| *k).map(|(d, _)| d.clone()));
|
||||||
|
} else {
|
||||||
|
datagrams.extend(s.datagrams.iter().cloned());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let out = receive(&mut receiver(packet_size, false), &datagrams);
|
||||||
|
check(&sent, &[1000 + victim as u32], &out);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn reordered_and_duplicated() {
|
||||||
|
for seed in 300..310u64 {
|
||||||
|
let mut rng = SeqRng::new(seed);
|
||||||
|
let packet_size = PACKET_SIZES[rng.below(PACKET_SIZES.len())];
|
||||||
|
let pct = [0u8, 20, 50][rng.below(3)];
|
||||||
|
let payload = usize::from(packet_size) - 16;
|
||||||
|
let mut tx = sender(packet_size, pct, 1, false, rng.next_u64() as u16);
|
||||||
|
let sent: Vec<Sent> = sizes(&mut rng, payload, 12)
|
||||||
|
.into_iter()
|
||||||
|
.enumerate()
|
||||||
|
.map(|(i, l)| send(&mut tx, &mut rng, i as u32, l))
|
||||||
|
.collect();
|
||||||
|
let mut datagrams = Vec::new();
|
||||||
|
for pair in sent.chunks(2) {
|
||||||
|
// Two frames' datagrams interleaved in random order, with random duplicates.
|
||||||
|
let mut window: Vec<Vec<u8>> = pair.iter().flat_map(|s| s.datagrams.clone()).collect();
|
||||||
|
let dups: Vec<Vec<u8>> =
|
||||||
|
(0..rng.below(window.len() + 1)).map(|_| window[rng.below(window.len())].clone()).collect();
|
||||||
|
window.extend(dups);
|
||||||
|
rng.shuffle(&mut window);
|
||||||
|
if datagrams.is_empty() {
|
||||||
|
// The receiver starts at the frame of the first datagram it sees: let that be frame 0's.
|
||||||
|
let first = window.iter().position(|d| pair[0].datagrams.contains(d));
|
||||||
|
window.swap(0, first.expect("a datagram of frame 0"));
|
||||||
|
}
|
||||||
|
datagrams.extend(window);
|
||||||
|
}
|
||||||
|
// And a few stale duplicates of earlier frames at the end.
|
||||||
|
for _ in 0..5 {
|
||||||
|
let s = &sent[rng.below(sent.len())];
|
||||||
|
datagrams.push(s.datagrams[rng.below(s.datagrams.len())].clone());
|
||||||
|
}
|
||||||
|
check(&sent, &[], &receive(&mut receiver(packet_size, false), &datagrams));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn sequence_numbers_continue_across_frames_and_wrap() {
|
||||||
|
let mut rng = SeqRng::new(9);
|
||||||
|
let mut tx = sender(64, 50, 0, false, 0xFFF0);
|
||||||
|
let mut seq = 0xFFF0u16;
|
||||||
|
let mut sent = Vec::new();
|
||||||
|
for i in 0..10u32 {
|
||||||
|
let s = send(&mut tx, &mut rng, (u32::MAX - 4).wrapping_add(i), 48 * 3);
|
||||||
|
seq = check_layout(&s, 64, 50, 0, false, seq);
|
||||||
|
sent.push(s);
|
||||||
|
}
|
||||||
|
assert!(seq < 0xFFF0, "the sequence wrapped");
|
||||||
|
assert_eq!(tx.next_sequence(), seq);
|
||||||
|
let all: Vec<Vec<u8>> = sent.iter().flat_map(|s| s.datagrams.clone()).collect();
|
||||||
|
check(&sent, &[], &receive(&mut receiver(64, false), &all));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn parity_matches_an_independent_cauchy_encoder() {
|
||||||
|
// Parity over whole packets (5.3): bytes 32 on of parity j = sum_i 1 / ((m + i) XOR j) * data_i, with headers
|
||||||
|
// of the parity packets written afterwards.
|
||||||
|
let mut rng = SeqRng::new(11);
|
||||||
|
for (packet_size, pct, len) in [(64u16, 50u8, 48 * 9), (100, 20, 84 * 30), (1024, 100, 1008 * 4 + 3), (17, 255, 40)]
|
||||||
|
{
|
||||||
|
let mut tx = sender(packet_size, pct, 0, false, 0);
|
||||||
|
let s = send(&mut tx, &mut rng, 5, len);
|
||||||
|
for (positions, m) in blocks_of(&s, false).values() {
|
||||||
|
let k = positions.len() - m;
|
||||||
|
let data: Vec<Vec<u8>> = positions[..k].iter().map(|&i| s.datagrams[i].clone()).collect();
|
||||||
|
let matrix: Vec<u8> = (0..*m).flat_map(|j| (0..k).map(move |i| gf::inv(((m + i) ^ j) as u8))).collect();
|
||||||
|
let parity = gf::encode(&matrix, &data, *m);
|
||||||
|
for (j, &pos) in positions[k..].iter().enumerate() {
|
||||||
|
assert_eq!(&s.datagrams[pos][PAYLOAD_OFFSET..], &parity[j][PAYLOAD_OFFSET..], "parity {j}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn several_megabyte_frames() {
|
||||||
|
let mut rng = SeqRng::new(13);
|
||||||
|
let packet_size = 4080; // largest: 4064 bytes of payload, 4096-byte datagrams
|
||||||
|
let mut tx = sender(packet_size, 20, 2, false, 0);
|
||||||
|
let max = tx.max_bitstream_len();
|
||||||
|
assert_eq!(max, (MAX_DATA_SHARDS_PER_FRAME * 4064 - FRAME_HEADER_LEN).min(MAX_FRAME_BYTES - FRAME_HEADER_LEN));
|
||||||
|
let big = send(&mut tx, &mut rng, 1, 3_000_000);
|
||||||
|
let lossy = with_loss(&mut rng, &big, false, |_, m| m);
|
||||||
|
let out = receive(&mut receiver(packet_size, false), &lossy);
|
||||||
|
check(std::slice::from_ref(&big), &[], &out);
|
||||||
|
// The largest frame: 4 blocks of 255 data shards, no room for parity, so the FEC is lowered and counted.
|
||||||
|
let before = tx.stats().fec_reduced_blocks;
|
||||||
|
let largest = send(&mut tx, &mut rng, 2, max);
|
||||||
|
assert_eq!(tx.stats().fec_reduced_blocks - before, 4);
|
||||||
|
assert_eq!(largest.datagrams.len(), MAX_DATA_SHARDS_PER_FRAME);
|
||||||
|
let out = receive(&mut receiver(packet_size, false), &largest.datagrams);
|
||||||
|
check(std::slice::from_ref(&largest), &[], &out);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ================================================================================================ encryption
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn video_cipher_encrypt_matches_dotnet_vectors() {
|
||||||
|
let v = common::video_vectors();
|
||||||
|
let c = VideoCipher::new(v.arr16("key"));
|
||||||
|
for (name, counter, frame) in
|
||||||
|
[("v_0", 0u64, 0u32), ("v_1", 1, 0), ("v_big_counter", 0x0102_0304_0506_0708, 0x1122_3344), ("v_1040", 7, 3)]
|
||||||
|
{
|
||||||
|
assert_eq!(
|
||||||
|
c.encrypt(counter, frame, &v.bytes(&format!("{name}_plain"))).unwrap(),
|
||||||
|
v.bytes(&format!("{name}_packet")),
|
||||||
|
"{name}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
let too_big = vec![0u8; MAX_VIDEO_PACKET_BYTES - ENCRYPTION_PREFIX_LEN + 1];
|
||||||
|
assert_too_large!(c.encrypt(0, 0, &too_big), MAX_VIDEO_PACKET_BYTES, MAX_VIDEO_PACKET_BYTES + 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn encrypted_stream_round_trips_with_loss() {
|
||||||
|
let mut rng = SeqRng::new(17);
|
||||||
|
let mut tx = sender(1024, 20, 1, true, 100);
|
||||||
|
let mut clear = sender(1024, 20, 1, false, 100);
|
||||||
|
let mut counter = 0u64;
|
||||||
|
let mut sent = Vec::new();
|
||||||
|
for i in 0..10u32 {
|
||||||
|
let len = rng.below(1008 * 12);
|
||||||
|
let b = bitstream(&mut rng, len);
|
||||||
|
let mut r2 = rng.clone();
|
||||||
|
let s = send_bytes(&mut tx, &mut rng, i, b.clone());
|
||||||
|
let c = send_bytes(&mut clear, &mut r2, i, b);
|
||||||
|
assert_eq!(s.datagrams.len(), c.datagrams.len());
|
||||||
|
for (d, p) in s.datagrams.iter().zip(&c.datagrams) {
|
||||||
|
// IV = 8-byte LE counter, 3 zero bytes, 'V'; then the frame number, LE (PROTOCOL.md 7).
|
||||||
|
assert_eq!(&d[..8], &counter.to_le_bytes(), "nonce counter");
|
||||||
|
assert_eq!(&d[8..12], &[0, 0, 0, b'V']);
|
||||||
|
assert_eq!(&d[12..16], &i.to_le_bytes(), "frame number");
|
||||||
|
assert_eq!(
|
||||||
|
&VideoCipher::new(KEY).decrypt(d).unwrap(),
|
||||||
|
p,
|
||||||
|
"FEC before encryption: the plaintext is the clear packet"
|
||||||
|
);
|
||||||
|
counter += 1;
|
||||||
|
}
|
||||||
|
sent.push(s);
|
||||||
|
}
|
||||||
|
let mut datagrams = Vec::new();
|
||||||
|
for s in &sent {
|
||||||
|
datagrams.extend(with_loss(&mut rng, s, true, |r, m| r.below(m + 1)));
|
||||||
|
}
|
||||||
|
check(&sent, &[], &receive(&mut receiver(1024, true), &datagrams));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ================================================================================================ refusals
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn config_refusals() {
|
||||||
|
for size in [0u16, 1, 16] {
|
||||||
|
assert_err!(VideoPacketizer::new(config(size, 20, 0, false, 0)), Error::Malformed { .. }, "{size}");
|
||||||
|
}
|
||||||
|
assert!(VideoPacketizer::new(config(17, 20, 0, false, 0)).is_ok());
|
||||||
|
assert!(VideoPacketizer::new(config(4080, 20, 0, false, 0)).is_ok());
|
||||||
|
assert_err!(VideoPacketizer::new(config(4081, 20, 0, false, 0)), Error::Malformed { .. });
|
||||||
|
// Sealed datagrams carry 32 more bytes and must stay within the receiver's cap too.
|
||||||
|
assert!(VideoPacketizer::new(config(4048, 20, 0, true, 0)).is_ok());
|
||||||
|
assert_err!(VideoPacketizer::new(config(4049, 20, 0, true, 0)), Error::Malformed { .. });
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn oversized_frame_is_refused_and_nothing_advances() {
|
||||||
|
for (packet_size, encrypt) in [(17u16, false), (64, true), (1024, false)] {
|
||||||
|
let mut rng = SeqRng::new(u64::from(packet_size));
|
||||||
|
let mut tx = sender(packet_size, 20, 0, encrypt, 77);
|
||||||
|
let max = tx.max_bitstream_len();
|
||||||
|
let payload = usize::from(packet_size) - 16;
|
||||||
|
assert_eq!(max, (MAX_DATA_SHARDS_PER_FRAME * payload).min(MAX_FRAME_BYTES) - FRAME_HEADER_LEN);
|
||||||
|
let first = send(&mut tx, &mut rng, 0, 10);
|
||||||
|
let (seq, stats) = (tx.next_sequence(), tx.stats());
|
||||||
|
let big = vec![1u8; max + 1];
|
||||||
|
let frame = EncodedFrame {
|
||||||
|
frame_index: 1,
|
||||||
|
frame_type: FrameType::Key,
|
||||||
|
rtp_timestamp: 0,
|
||||||
|
processing_latency: 0,
|
||||||
|
bitstream: &big,
|
||||||
|
};
|
||||||
|
assert_too_large!(tx.packetize(&frame), max, max + 1);
|
||||||
|
assert_eq!((tx.next_sequence(), tx.stats()), (seq, stats), "a refused frame changes nothing");
|
||||||
|
// The next frame follows on directly, and the receiver sees no gap (also no nonce reuse when sealed).
|
||||||
|
let second = send(&mut tx, &mut rng, 1, max);
|
||||||
|
let all: Vec<Vec<u8>> = [&first, &second].iter().flat_map(|s| s.datagrams.clone()).collect();
|
||||||
|
check(&[first, second], &[], &receive(&mut receiver(packet_size, encrypt), &all));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ================================================================================================ generated
|
||||||
|
|
||||||
|
proptest! {
|
||||||
|
#![proptest_config(ProptestConfig { cases: 32, ..ProptestConfig::default() })]
|
||||||
|
|
||||||
|
/// Any sizes, packet sizes, percentages and minimums; up to m lost per block; identical frames out.
|
||||||
|
#[test]
|
||||||
|
fn generated_round_trips(
|
||||||
|
seed in any::<u64>(),
|
||||||
|
packet_size in 17u16..1500,
|
||||||
|
pct in any::<u8>(),
|
||||||
|
min in 0u8..8,
|
||||||
|
frames in 1usize..6,
|
||||||
|
encrypt in any::<bool>(),
|
||||||
|
) {
|
||||||
|
let mut rng = SeqRng::new(seed);
|
||||||
|
let payload = usize::from(packet_size) - 16;
|
||||||
|
let mut tx = sender(packet_size, pct, min, encrypt, rng.next_u64() as u16);
|
||||||
|
let max = tx.max_bitstream_len();
|
||||||
|
let first = rng.next_u64() as u32;
|
||||||
|
let sent: Vec<Sent> = (0..frames)
|
||||||
|
.map(|i| { let len = rng.below(payload * 30).min(max); send(&mut tx, &mut rng, first.wrapping_add(i as u32), len) })
|
||||||
|
.collect();
|
||||||
|
let mut datagrams = Vec::new();
|
||||||
|
for s in &sent {
|
||||||
|
datagrams.extend(with_loss(&mut rng, s, encrypt, |r, m| r.below(m + 1)));
|
||||||
|
}
|
||||||
|
check(&sent, &[], &receive(&mut receiver(packet_size, encrypt), &datagrams));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -14,7 +14,9 @@ GPL-licensed implementation. This file says what may be read, what may not, and
|
|||||||
| Crate docs (docs.rs, crates.io, crate READMEs) | per crate | Read freely. |
|
| Crate docs (docs.rs, crates.io, crate READMEs) | per crate | Read freely. |
|
||||||
| Our own measurements | ours | Captures through our own relay ([tools/lab-relay](../tools/lab-relay)). Mark allowed **one** capture on his PC (answer 16, 2026-11-25), done exactly as [LAB_CAPTURE.md](LAB_CAPTURE.md) says; never his TV, never 192.168.100.217. Recordings stay local (on E:, approved for Play remotely) under `E:\build\play-remotely\lab\`, out of git; only facts and test vectors derived from them go in, with the date and setup. |
|
| Our own measurements | ours | Captures through our own relay ([tools/lab-relay](../tools/lab-relay)). Mark allowed **one** capture on his PC (answer 16, 2026-11-25), done exactly as [LAB_CAPTURE.md](LAB_CAPTURE.md) says; never his TV, never 192.168.100.217. Recordings stay local (on E:, approved for Play remotely) under `E:\build\play-remotely\lab\`, out of git; only facts and test vectors derived from them go in, with the date and setup. |
|
||||||
| Official Sunshine and Moonlight PC **binaries** in that capture | GPL-3.0 (we only run them) | Black-box peers: run, observe their traffic, their `--help` output, their own logs and the files/registry keys they write. Never open their source, never disassemble or decompile them. |
|
| Official Sunshine and Moonlight PC **binaries** in that capture | GPL-3.0 (we only run them) | Black-box peers: run, observe their traffic, their `--help` output, their own logs and the files/registry keys they write. Never open their source, never disassemble or decompile them. |
|
||||||
|
| Arena Domi Remote (Android, a GPL app built apart from Domi repos) and the official Moonlight PC app, as **clients of Lumen** | GPL-3.0 (we only run them) | Black-box peers (Mark, 2026-12-04, D2): lumen-host logs what they send to it. Same limits as the row above. Their workspaces and source are never opened; the Remote app's own workers drive it and hand over facts only. |
|
||||||
| READMEs and wikis of forbidden projects | n/a | For facts only (licence, release notes, compatibility statements). Never their source files. |
|
| READMEs and wikis of forbidden projects | n/a | For facts only (licence, release notes, compatibility statements). Never their source files. |
|
||||||
|
| Public OS and SDK documentation (Microsoft Learn; NVIDIA, AMD and Intel encoder SDK docs and API headers; libopus and ViGEm docs) | per vendor | Read for the host side (Lumen), facts in our own words, each page logged. Allowed in the Lumen host lead's brief of 2026-12-04. Never the source of GPL or LGPL projects that wrap these APIs. |
|
||||||
|
|
||||||
### Approved by Mark (answer 15, 2026-11-25): "Yes, with attribution"
|
### Approved by Mark (answer 15, 2026-11-25): "Yes, with attribution"
|
||||||
|
|
||||||
@@ -33,6 +35,10 @@ Never open, read, paste or port code from: **Sunshine, Moonlight (any client: Qt
|
|||||||
moonlight-common-c, Moonlight's ENet fork, Apollo, Vibeshine, Rubylight, chiaki** (and forks of them). That also
|
moonlight-common-c, Moonlight's ENet fork, Apollo, Vibeshine, Rubylight, chiaki** (and forks of them). That also
|
||||||
means their source files on GitHub. Their READMEs and wikis are fine for facts.
|
means their source files on GitHub. Their READMEs and wikis are fine for facts.
|
||||||
|
|
||||||
|
**For host work (Lumen), also forbidden** (Mark, 2026-12-04, decision D2 in [LUMEN-HOST-PLAN.md](LUMEN-HOST-PLAN.md)):
|
||||||
|
the source of **OBS Studio** and **FFmpeg** (including any GPL or LGPL code that wraps NVENC, AMF, Quick Sync,
|
||||||
|
Desktop Duplication or WASAPI). Their documentation pages are fine for facts, like the READMEs above.
|
||||||
|
|
||||||
### Second-hand GPL facts
|
### Second-hand GPL facts
|
||||||
|
|
||||||
Moonshine credits Sunshine for "groundwork" on the host side, and a few Moonshine comments cite Sunshine or
|
Moonshine credits Sunshine for "groundwork" on the host side, and a few Moonshine comments cite Sunshine or
|
||||||
@@ -81,3 +87,7 @@ All entries by the DomiStream protocol engineer. Pinned commits are the ones rea
|
|||||||
| S-19 | 2026-11-25 | GitHub release API: [Moonlight PC v6.2.0](https://api.github.com/repos/moonlight-stream/moonlight-qt/releases/latest), [Sunshine v2026.914.233613](https://api.github.com/repos/SunshineStream/Sunshine/releases/tags/v2026.914.233613) | Asset names, sizes and sha256 digests for the lab capture pins. Release metadata only. |
|
| S-19 | 2026-11-25 | GitHub release API: [Moonlight PC v6.2.0](https://api.github.com/repos/moonlight-stream/moonlight-qt/releases/latest), [Sunshine v2026.914.233613](https://api.github.com/repos/SunshineStream/Sunshine/releases/tags/v2026.914.233613) | Asset names, sizes and sha256 digests for the lab capture pins. Release metadata only. |
|
||||||
| S-20 | 2026-11-25 | ArenaTV `docs/research/sunshine-api.md` and `docs/research/this-pc.md` (Domi's own research from LizardByte's docs) | Sunshine's API calls, `--creds`, `bind_address`, port offsets, first-run behaviour, this PC's adapters and old install. |
|
| S-20 | 2026-11-25 | ArenaTV `docs/research/sunshine-api.md` and `docs/research/this-pc.md` (Domi's own research from LizardByte's docs) | Sunshine's API calls, `--creds`, `bind_address`, port offsets, first-run behaviour, this PC's adapters and old install. |
|
||||||
| S-21 | 2026-11-30 | [Moonshine](https://github.com/hgaiser/moonshine) at `f184d5e` (same pin as S-9): `src/session/stream/control/mod.rs` again (client message parsing and the control loop), `src/session/stream/mod.rs` (`StreamConfig`), `src/session/stream/video/mod.rs` (PING handling), `src/config.rs` (nothing relevant); the repository tree listing | BSD-2. U10, as facts only: the host reads **no body** from START_B (0x0307), Ping (0x0200), LOSS_STATS, FRAME_STATS or the IDR request; START_A (0x0305) is not a type it knows; inside the encrypted frame an unknown type or a failed decryption is skipped, outside it an unknown type or a bad length ends the session; INVALIDATE_REF_FRAMES `first`/`last` at message bytes 4..8 and 12..16 (LE), short bodies mean "from 0"; each Ping resets a stop deadline, `StreamConfig.timeout` default 60 s; the client-to-host IV is `seq LE ‖ 6 zero ‖ 'C' 'C'`; host messages go reliable on channel 0; the video receiver waits for START_B and takes exactly the 4 bytes `PING`, each PING updating the client address. No value in these parts cites Sunshine or moonlight-common-c (the HDR payload's Sunshine note is the known S-9 case). Used for the probe's default bodies (all empty) and the PROTOCOL.md 3.3 facts. |
|
| S-21 | 2026-11-30 | [Moonshine](https://github.com/hgaiser/moonshine) at `f184d5e` (same pin as S-9): `src/session/stream/control/mod.rs` again (client message parsing and the control loop), `src/session/stream/mod.rs` (`StreamConfig`), `src/session/stream/video/mod.rs` (PING handling), `src/config.rs` (nothing relevant); the repository tree listing | BSD-2. U10, as facts only: the host reads **no body** from START_B (0x0307), Ping (0x0200), LOSS_STATS, FRAME_STATS or the IDR request; START_A (0x0305) is not a type it knows; inside the encrypted frame an unknown type or a failed decryption is skipped, outside it an unknown type or a bad length ends the session; INVALIDATE_REF_FRAMES `first`/`last` at message bytes 4..8 and 12..16 (LE), short bodies mean "from 0"; each Ping resets a stop deadline, `StreamConfig.timeout` default 60 s; the client-to-host IV is `seq LE ‖ 6 zero ‖ 'C' 'C'`; host messages go reliable on channel 0; the video receiver waits for START_B and takes exactly the 4 bytes `PING`, each PING updating the client address. No value in these parts cites Sunshine or moonlight-common-c (the HDR payload's Sunshine note is the known S-9 case). Used for the probe's default bodies (all empty) and the PROTOCOL.md 3.3 facts. |
|
||||||
|
| S-22 | 2026-12-04 | Microsoft Learn: [DXGI 1.5 improvements](https://learn.microsoft.com/windows/win32/direct3ddxgi/dxgi-1-5-improvements), [IDXGIOutput5::DuplicateOutput1](https://learn.microsoft.com/windows/win32/api/dxgi1_5/nf-dxgi1_5-idxgioutput5-duplicateoutput1), [IDXGIOutput1::DuplicateOutput](https://learn.microsoft.com/windows/win32/api/dxgi1_2/nf-dxgi1_2-idxgioutput1-duplicateoutput), [Desktop duplication](https://learn.microsoft.com/windows-hardware/drivers/display/desktop-duplication-api), [HDR and advanced colour](https://learn.microsoft.com/windows/win32/direct3darticles/high-dynamic-range), [GraphicsCaptureSession](https://learn.microsoft.com/uwp/api/windows.graphics.capture.graphicscapturesession) (`IsBorderRequired`, `IsCursorCaptureEnabled`), [SendInput](https://learn.microsoft.com/windows/win32/api/winuser/nf-winuser-sendinput), [MOUSEINPUT](https://learn.microsoft.com/windows/win32/api/winuser/ns-winuser-mouseinput), [Security considerations for assistive technologies](https://learn.microsoft.com/windows/win32/winauto/uiauto-securityoverview), [UAC policy for UIAccess in secure locations](https://learn.microsoft.com/windows/client-management/mdm/policy-csp-localpoliciessecurityoptions), [CreateSyntheticPointerDevice](https://learn.microsoft.com/windows/win32/api/winuser/nf-winuser-createsyntheticpointerdevice), [InjectSyntheticPointerInput](https://learn.microsoft.com/windows/win32/api/winuser/nf-winuser-injectsyntheticpointerinput), [Loopback recording](https://learn.microsoft.com/windows/win32/coreaudio/loopback-recording), [AUDIOCLIENT_PROCESS_LOOPBACK_PARAMS](https://learn.microsoft.com/windows/win32/api/audioclientactivationparams/ns-audioclientactivationparams-audioclient_process_loopback_params) | For [LUMEN-HOST-PLAN.md](LUMEN-HOST-PLAN.md): `DuplicateOutput1` takes a list of formats and can deliver HDR/WCG surfaces unconverted, the list should always hold `B8G8R8A8_UNORM`; E_ACCESSDENIED on the secure desktop unless LocalSystem; four duplicating processes per session by default; re-create after desktop switches and mode changes. WGC draws a border, removable only from build 20348 after user consent; cursor capture from 19041. `SendInput` is subject to UIPI and fails silently; absolute moves are 0..65535, `MOUSEEVENTF_VIRTUALDESK` maps to the whole virtual desktop; relative moves get pointer speed applied. UIAccess needs Authenticode signing, a secure install location and is meant for assistive technology. Synthetic touch/pen injection from Windows 10 1809. WASAPI loopback captures the render mix in shared mode; per-process loopback from build 20348. |
|
||||||
|
| S-23 | 2026-12-04 | NVIDIA [video-sdk-samples](https://github.com/NVIDIA/video-sdk-samples) at `aa3544d`: `Samples/NvCodec/NvEncoder/nvEncodeAPI.h` (API 8.1, sha256 `4d061c34…6042a`); NVIDIA [VideoProcessingFramework](https://github.com/NVIDIA/VideoProcessingFramework) at `e82364f`: `src/TC/third_party/nvEncodeAPI.h` (API 12.0, sha256 `067c5159…b4ad`); GitHub repository metadata of both | Both headers carry NVIDIA's MIT notice for the header file; the repositories are Apache-2.0 / unlicensed samples and the second is archived. Declarations used for the L0 spike shim (struct versions, preset and tuning enums, `NvEncGetEncodePresetConfigEx`, resource registration). No sample `.cpp` file was opened. |
|
||||||
|
| S-24 | 2026-12-04 | [NVENC Video Encoder API Programming Guide](https://docs.nvidia.com/video-technologies/video-codec-sdk/13.0/nvenc-video-encoder-api-prog-guide/index.html) (SDK 13.0) | Loading `nvEncodeAPI` at run time and `NvEncodeAPICreateInstance`; `NV_ENC_DEVICE_TYPE_DIRECTX` sessions; registering, mapping and unmapping D3D11 textures; tuning info (low latency, ultra low latency), presets P1-P7, CBR filler, forcing IDR, `NvEncInvalidateRefFrames`, intra refresh, look-ahead latency; lock/unlock of the bitstream; async mode only on Windows 10+ WDDM, recommended there; Main10 settings. |
|
||||||
|
| S-25 | 2026-12-04 | Licences via the GitHub and crates.io APIs and `COPYING` files: nefarius/ViGEmClient (MIT, archived), nefarius/ViGEmBus (BSD-3-Clause, archived), xiph/opus `COPYING` (BSD-style), crates `opus`, `audiopus_sys`, `vigem-client`, `nvidia-video-codec-sdk`, `nvenc`, `windows` | Licence and status only; no source files of these projects were opened. |
|
||||||
|
|||||||
@@ -0,0 +1,568 @@
|
|||||||
|
# Lumen host: the plan
|
||||||
|
|
||||||
|
Status: **plan, 2026-12-04; Mark's go for phase one (L0 + L1) on 2026-12-04**, with all six decisions of section 8
|
||||||
|
accepted as proposed. Later milestones start after phase one is reported.
|
||||||
|
|
||||||
|
Goal (Mark, 2026-12-04): "move away from Sunshine". Today Arena Domi's Play remotely wraps Sunshine, a separate
|
||||||
|
GPL-3.0 program that Arena Domi installs and drives only through its local settings API. Lumen is Arena Domi's own
|
||||||
|
streaming host. It replaces Sunshine on the PC, so that Arena Domi Remote (Android), the Windows client and Arena
|
||||||
|
Domi TV stream from Lumen instead. Sunshine stays as a hidden fallback until Mark removes it.
|
||||||
|
|
||||||
|
This file is public, like the rest of DomiStream. It holds the architecture, the split between DomiStream and the
|
||||||
|
private Arena Domi repository, the milestones, the risks and the tests. Network addresses, the owner's devices beyond the
|
||||||
|
reference PC's hardware, and the private Play remotely design stay in Arena's `docs/ROADMAP-REMOTE.md` (section
|
||||||
|
"Lumen host").
|
||||||
|
|
||||||
|
Words used here:
|
||||||
|
- **host**: the PC that runs the game and streams it; **client**: the phone, TV or PC that shows it.
|
||||||
|
- **GameStream**: the protocol that Sunshine and the Moonlight-family clients speak, as described in
|
||||||
|
[PROTOCOL.md](PROTOCOL.md).
|
||||||
|
- **lumen-host**: the Windows program that is the Lumen host (section 1.1).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 0. Ground rules this plan keeps
|
||||||
|
|
||||||
|
- **Clean room** ([CLEAN_ROOM.md](CLEAN_ROOM.md)). No code of Sunshine, Moonlight (any client, including
|
||||||
|
moonlight-common-c), Apollo, Vibeshine, Rubylight or chiaki is opened, pasted or ported. That includes the GPL
|
||||||
|
fork that Arena Domi Remote is built from: its workspace is never opened by anyone working on Lumen, and nothing
|
||||||
|
of it enters a Domi repository. Host-side facts come from the Wolf docs, Moonshine (a BSD-2 host, see 6.1), stock
|
||||||
|
ENet, tokio-enet, fec-rs, public OS and SDK documentation, and our own measurements. Every source is logged in the
|
||||||
|
source log in the same PR that uses it.
|
||||||
|
- **Sans-I/O protocol code stays here**; sockets, TLS, the GPU, audio devices and input injection live in the
|
||||||
|
program that uses DomiStream (section 3).
|
||||||
|
- **Hostile input**: everything a client sends is parsed strictly, every length is capped before it allocates, and
|
||||||
|
every parser has a fuzz target.
|
||||||
|
- **No admin rights.** lumen-host runs as the signed-in user, never as a service or as SYSTEM. The only elevation
|
||||||
|
in the plan is the one Mark already allowed at "Turn on Play remotely", and whether Lumen's firewall rules may use
|
||||||
|
it is decided: D1, yes, the same single step.
|
||||||
|
- **Nothing leaves the PC by default.** lumen-host listens only on the addresses Play remotely allows; every
|
||||||
|
session start and stop is audit-recorded, like today.
|
||||||
|
- **No injection into a game process, no DirectX/Vulkan hooks, no reading game memory.** Lumen captures the display
|
||||||
|
the game is shown on and injects input through public Windows input APIs, like a keyboard, mouse or pad would.
|
||||||
|
- **Measure, don't guess.** Every latency claim comes from the harness (section 7.4).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. Host architecture
|
||||||
|
|
||||||
|
```
|
||||||
|
lumen-host (one process, signed-in user, medium integrity)
|
||||||
|
┌──────────────────────────────────────────────────────────────────────────────────────────┐
|
||||||
|
│ capture ──► colour convert + scale ──► encode ──► packetize + FEC ──► pace ──► UDP video │
|
||||||
|
│ (DXGI dup., (GPU shader: FP16 scRGB (NVENC, (DomiStream │ │
|
||||||
|
│ FP16 or → NV12 BT.709 or P010 zero copy) host side) │ │
|
||||||
|
│ BGRA8) BT.2020 PQ, limited/full) │ │
|
||||||
|
│ WASAPI loopback ──► resample ──► Opus ──► packetize + FEC + AES-CBC ─────────► UDP audio │
|
||||||
|
│ control (ENet host + AES-GCM) ◄──► input mapper ──► SendInput / ViGEmBus / pointer inject │
|
||||||
|
│ HTTP/HTTPS (pairing, serverinfo, applist, launch) and RTSP (session setup), TLS via rustls │
|
||||||
|
│ session: launch game from Arena's library, watch it, game mode, audit, end │
|
||||||
|
└──────────────────────────────────────────────────────────────────────────────────────────┘
|
||||||
|
▲ arena-host (in Arena Domi): turns Lumen on/off, pairing gate, grants, which engine per device
|
||||||
|
```
|
||||||
|
|
||||||
|
### 1.1 Process model
|
||||||
|
|
||||||
|
- **One program, `lumen-host.exe`**, separate from the Arena Domi window and from the tray agent. A crash in it
|
||||||
|
never takes the window or the agent down, and it can be stopped cleanly.
|
||||||
|
- **Two states.** *Idle*: only the HTTP/HTTPS and RTSP listeners are open (a few sockets, no GPU, no audio device,
|
||||||
|
no threads busy), so a phone can see the PC and pair. *Streaming*: capture, encode, audio and input start when a
|
||||||
|
paired client launches a game, and stop when the session ends. One streaming session at a time in the first
|
||||||
|
version.
|
||||||
|
- **Started by Arena Domi**, never by Windows as a service. Who starts it at sign-in (the tray agent is the natural
|
||||||
|
owner, because it always runs) is decided: D4, the tray agent, once Lumen is the default.
|
||||||
|
- **Priorities**: the idle listeners run at below-normal priority. While streaming, the capture/encode thread and
|
||||||
|
the packet pacer register with the Multimedia Class Scheduler Service (no admin needed) and everything else stays
|
||||||
|
normal or below. The cost to the game is measured (section 7.4), not assumed.
|
||||||
|
|
||||||
|
### 1.2 Capture
|
||||||
|
|
||||||
|
| | DXGI Desktop Duplication (`IDXGIOutput5::DuplicateOutput1`) | Windows.Graphics.Capture |
|
||||||
|
| :-- | :-- | :-- |
|
||||||
|
| What it captures | a whole output (monitor), any game shown on it, fullscreen included | a monitor or one window |
|
||||||
|
| HDR | yes: pass a list of formats that includes `R16G16B16A16_FLOAT` and the FP16 scRGB desktop arrives without conversion | yes, by choosing the frame pool's pixel format |
|
||||||
|
| Capture border | none | a yellow border; it can be turned off only from Windows 10 build 20348 (`IsBorderRequired`) and after the user grants borderless access |
|
||||||
|
| Cursor | given separately (shape + position): we draw it, or not | `IsCursorCaptureEnabled` from Windows 10 2004 |
|
||||||
|
| Limits | E_ACCESSDENIED on the secure desktop (UAC prompt, lock screen) unless the process runs as LocalSystem; at most four duplicating processes per session by default; must be re-created after a mode change or a fullscreen switch | per-window capture survives window moves; needs the WinRT interop |
|
||||||
|
|
||||||
|
**Choice: Desktop Duplication first, Windows.Graphics.Capture as a later option** for single-window streaming on
|
||||||
|
Windows 11, where the border can be turned off. Reasons: the reference PC runs Windows 10 22H2 (build 19045), where
|
||||||
|
WGC would draw a yellow border over the game; duplication captures exclusive-fullscreen games; and it hands us FP16
|
||||||
|
directly. Sources: S-22 (section 9).
|
||||||
|
|
||||||
|
- **DPI awareness**: lumen-host is per-monitor DPI aware (v2). Measured in L0: without it `DuplicateOutput1`
|
||||||
|
fails with `DXGI_ERROR_UNSUPPORTED` and output sizes are DPI-virtualised.
|
||||||
|
- **Formats asked for**: `R16G16B16A16_FLOAT`, `R10G10B10A2_UNORM`, `B8G8R8A8_UNORM` (the last one always, as
|
||||||
|
Microsoft asks). The format that arrives decides the colour path (1.3).
|
||||||
|
- **Frames only on change**: duplication delivers a frame only when something changed. The pacer repeats the last
|
||||||
|
encoded frame (or sends nothing, if the client tolerates gaps; measured) so that the client sees its frame rate.
|
||||||
|
- **The secure desktop** (UAC prompt, lock screen, Ctrl+Alt+Del) cannot be captured without SYSTEM rights, and
|
||||||
|
input cannot reach it either (1.6). lumen-host keeps the stream alive and sends a still frame that says "Finish
|
||||||
|
this on the PC", then resumes when the desktop comes back (`EVENT_SYSTEM_DESKTOPSWITCH` / re-creating the
|
||||||
|
duplication). This is an accepted limitation of the no-admin rule, not a bug to fix later.
|
||||||
|
- **Which monitor** (the reference PC has a 1440p HDR primary display and a 2160p second display):
|
||||||
|
1. the monitor that shows the launched game's main window (found from the game's process, re-checked when the
|
||||||
|
window moves);
|
||||||
|
2. otherwise the client's own choice ("Stream this display", per device, in Settings → Play remotely);
|
||||||
|
3. otherwise the primary monitor.
|
||||||
|
A monitor switch during a stream re-creates the duplication and sends an IDR frame; the client keeps its
|
||||||
|
resolution.
|
||||||
|
- **Resolution**: the client asks for a size in ANNOUNCE. Lumen never changes the PC's display mode in the first
|
||||||
|
version (the owner's desktop stays as it is); it scales on the GPU in the colour pass (for example 2160p to 1080p
|
||||||
|
for a phone) and keeps the aspect ratio with black bars. A virtual display per client is roadmap Day 6.
|
||||||
|
- **GPU**: the duplication device is created on the adapter that drives the output. If the encoder is on another
|
||||||
|
adapter (laptops), one cross-adapter copy is made; on the reference PC both are the same GPU, so there is no copy.
|
||||||
|
|
||||||
|
### 1.3 Colour: SDR, HDR, limited or full range
|
||||||
|
|
||||||
|
The rule: **what the phone shows must look like what the PC shows**, for the same content, so the colour path is
|
||||||
|
explicit at every step and tested with patterns (7.5).
|
||||||
|
|
||||||
|
| Desktop (capture format) | Client asks for | Conversion on the GPU (one compute pass, fused with scaling and the cursor) | Encoder input | Signalled in the bitstream (VUI) |
|
||||||
|
| :-- | :-- | :-- | :-- | :-- |
|
||||||
|
| SDR (BGRA8, sRGB) | SDR | RGB → Y'CbCr BT.709, limited or full range | NV12 | BT.709 primaries, transfer and matrix; full-range flag as negotiated |
|
||||||
|
| HDR (FP16 scRGB, linear) | SDR | scale by the display's **SDR white level** (so SDR apps keep the brightness they have on the PC), tone-map highlights above SDR white with a fixed curve, encode with the sRGB/BT.709 transfer | NV12 | as above |
|
||||||
|
| HDR (FP16 scRGB) | HDR | linear BT.709 → BT.2020 primaries → PQ (SMPTE ST 2084), 10-bit | P010 | BT.2020, PQ, BT.2020 non-constant matrix; mastering metadata from the output's description (`IDXGIOutput6::GetDesc1`) |
|
||||||
|
| HDR10 game in `R10G10B10A2` | HDR | pass through when the output is already in BT.2020/PQ | P010 | as above |
|
||||||
|
|
||||||
|
- **Range**: the client tells the host its colour space and range in ANNOUNCE (`encoderCscMode`, PROTOCOL.md 2.4).
|
||||||
|
The bit meanings are **unknown** (U6 territory); they are settled by measurement: what Arena Domi Remote and our
|
||||||
|
own clients send for each of their settings, and how the decoded test pattern looks (7.5). Until a client's value
|
||||||
|
is understood, Lumen uses **BT.709 limited range** for SDR, the most common decoder default, and says so in the
|
||||||
|
stream's VUI, so a correct decoder shows correct colours either way.
|
||||||
|
- **HDR to the client** needs the host-to-client HDR message (`0x010e`, PROTOCOL.md 3.3). Its layout is
|
||||||
|
GPL-provenance ([M*]): it is **not** used from Moonshine's note; it is settled by our own measurement (6.2) before
|
||||||
|
Lumen sends HDR. Until then Lumen streams SDR to every client, tone-mapped as above.
|
||||||
|
- **Chroma**: 4:2:0 first. 4:4:4 (text mode) is roadmap Day 5.
|
||||||
|
- The SDR white level is read per display from Windows (`DisplayConfigGetDeviceInfo`, SDR white level), not
|
||||||
|
assumed.
|
||||||
|
|
||||||
|
### 1.4 Encode
|
||||||
|
|
||||||
|
- **NVENC first** (the reference PC has an NVIDIA Ampere GPU: H.264 and HEVC 8/10-bit encode; AV1 encode needs a
|
||||||
|
newer generation). AMD AMF and Intel Quick Sync come later behind the same `Encoder` trait, and Media Foundation's
|
||||||
|
hardware encoder is the generic fallback.
|
||||||
|
- **Zero copy**: the colour pass writes into a D3D11 texture that is registered with NVENC as an input resource, so
|
||||||
|
a frame never leaves the GPU between capture and the bitstream. The bitstream (a few kilobytes) is the only thing
|
||||||
|
read back to the CPU.
|
||||||
|
- **Low-latency settings** (named here as the NVENC programming guide names them; the guide is read and logged in
|
||||||
|
milestone L0 before any of this is written): ultra-low-latency tuning, no B-frames, no look-ahead, CBR with a VBV
|
||||||
|
of about one frame, an infinite GOP with IDR only on request, reference-frame invalidation when the client reports
|
||||||
|
a lost range (`INVALIDATE_REF_FRAMES`) and supports it, optional intra refresh instead of IDR frames, and slices
|
||||||
|
sized to the video packet size where that helps the FEC blocks.
|
||||||
|
- **Codec choice**: HEVC by default (smaller frames at the same quality, HDR possible), H.264 for clients without
|
||||||
|
HEVC; the client's ANNOUNCE (`bitStreamFormat`) decides, within what serverinfo advertised.
|
||||||
|
- **Bitrate**: from the client's request (`configuredBitrateKbps`), capped by what the encoder supports; adaptive
|
||||||
|
bitrate belongs to Lumen's own transport (roadmap Day 4).
|
||||||
|
- **Interface to NVENC**: NVIDIA's public API header and the driver's `nvEncodeAPI64.dll`, loaded at run time, so
|
||||||
|
nothing of NVIDIA ships in Arena Domi. The header is MIT-licensed by its own notice; L0 settled which one (section
|
||||||
|
10: API 12.0, because current drivers refuse the older API's presets). We do not read
|
||||||
|
the source of GPL or LGPL projects that wrap NVENC (FFmpeg, OBS Studio and the like); see 6.1.
|
||||||
|
|
||||||
|
### 1.5 Audio
|
||||||
|
|
||||||
|
- **Capture**: WASAPI loopback on the default render device (shared mode), which is the full mix the PC plays.
|
||||||
|
Per-process loopback (only the game, without voice chat or notifications) needs Windows 10 build 20348 or newer,
|
||||||
|
so it is an option for Windows 11 PCs, not the reference PC. Sources: S-22.
|
||||||
|
- **The PC keeps its own sound** in the first version (Lumen changes no audio setting). Muting the PC's speakers
|
||||||
|
while streaming is a later, opt-in choice.
|
||||||
|
- **Encode**: libopus (BSD-3-Clause) through a Rust binding whose licence is checked and logged; 48 kHz, stereo
|
||||||
|
first, 5.1/7.1 when the surround mapping is measured (U26). Frame duration from ANNOUNCE (`packetDuration`),
|
||||||
|
constant bitrate, because the audio FEC needs equally long packets (PROTOCOL.md 6.4).
|
||||||
|
- **Audio FEC** needs the parity matrix (U16), which is GPL-provenance. Lumen first sends audio **without** parity
|
||||||
|
packets and checks that every client plays it (6.2); the matrix is then measured and solved by us (PROTOCOL.md
|
||||||
|
U16) before parity is sent.
|
||||||
|
- **Audio encryption**: AES-128-CBC with the session key, as PROTOCOL.md 6.3 says (DomiStream already holds the
|
||||||
|
cipher; the host needs the encrypt side).
|
||||||
|
|
||||||
|
### 1.6 Input injection
|
||||||
|
|
||||||
|
Everything a client sends arrives as INPUT_DATA on the control channel (PROTOCOL.md section 4). DomiStream already
|
||||||
|
parses it (`input::parse_input`); lumen-host maps each event to a Windows call.
|
||||||
|
|
||||||
|
| Event | Windows call | Notes |
|
||||||
|
| :-- | :-- | :-- |
|
||||||
|
| Mouse relative move | `SendInput`, `MOUSEEVENTF_MOVE` | what games read (raw input). Windows applies the pointer-speed settings to relative moves on the desktop; games reading raw input get the raw delta |
|
||||||
|
| Mouse absolute move | `SendInput`, `MOUSEEVENTF_ABSOLUTE \| MOUSEEVENTF_VIRTUALDESK` | the client's position (in the stream's picture) is mapped to the streamed monitor's rectangle inside the virtual desktop, then to 0..65535. The mapping is a pure function with tests (letterboxing, scaling, monitors at negative coordinates) |
|
||||||
|
| Buttons, wheel, horizontal wheel | `SendInput` | wheel in multiples of 120, high-resolution deltas passed through |
|
||||||
|
| Keyboard | `SendInput` with **scan codes** (`KEYEVENTF_SCANCODE`) | many games read scan codes, not virtual keys. A pure table maps GameStream key codes (PROTOCOL.md 4, Wolf's key table) to scan codes. Text (UTF8_TEXT) goes as `KEYEVENTF_UNICODE` |
|
||||||
|
| Gamepad | **ViGEmBus** (Mark: "ViGEmBus for now"), through the MIT-licensed ViGEmClient library or a binding of it (licence logged) | one virtual Xbox 360 or DualShock 4 pad per client pad (CONTROLLER_ARRIVAL decides the type), rumble back to the client as RUMBLE_DATA. If ViGEmBus is not installed, pads are refused with a plain message, nothing else breaks. Our own virtual gamepad driver replaces it later (open point 13 of the roadmap) |
|
||||||
|
| Touch, pen (later) | `InjectSyntheticPointerInput` (Windows 10 1809+) | only when a client sends real touch (TOUCH/PEN layouts are U21); not needed for touch-to-mouse below |
|
||||||
|
|
||||||
|
**Touch-to-mouse, designed deliberately.** The 2026-12-04 evidence: the phone sent only *relative* mouse moves and
|
||||||
|
left-button press/release, never an absolute position. So a tap could not click where the finger was. The mapping
|
||||||
|
we want on every touch client:
|
||||||
|
|
||||||
|
| Gesture on the phone | What the PC gets |
|
||||||
|
| :-- | :-- |
|
||||||
|
| finger down and up without moving (tap) | absolute move to that point, left press, left release |
|
||||||
|
| long press (finger still for 500 ms; the threshold is tuned by tests) | absolute move to that point, right press, right release; the client vibrates once |
|
||||||
|
| one-finger drag after the finger moved | absolute moves while the finger moves, left held from the start (drag and drop) |
|
||||||
|
| two-finger drag | wheel (vertical) and horizontal wheel, in proportion to the distance, no button |
|
||||||
|
| two-finger tap | right click at the midpoint (desktop habit; optional) |
|
||||||
|
|
||||||
|
The gesture recogniser is **client-side** and pure, so it lives in DomiStream (`input::touch`, new) and every Arena
|
||||||
|
client uses the same code. It turns timed touch points into GameStream events (MOUSE_MOVE_ABS with the stream's
|
||||||
|
reference size, buttons, scroll); lumen-host only maps absolute positions correctly. For **Arena Domi Remote**,
|
||||||
|
which is a GPL app no Lumen worker may read, the same behaviour is handed over as a **written specification with
|
||||||
|
test cases** (gesture in, packets out), never as code, and its own workers implement it there. The input e2e
|
||||||
|
(7.3) checks the result against the PC, whatever client produced it.
|
||||||
|
|
||||||
|
**Integrity levels (UIPI).** `SendInput` reaches only windows of equal or lower integrity, and the failure is
|
||||||
|
silent. lumen-host runs at medium integrity, so:
|
||||||
|
- a game or launcher that runs **as administrator** gets no input from Lumen. lumen-host checks the foreground
|
||||||
|
window's process integrity when input starts failing to land and tells the client "This game runs as
|
||||||
|
administrator, so Arena Domi can't control it", once per session;
|
||||||
|
- the **secure desktop** (UAC prompts, lock screen) gets no input (and no capture, 1.2);
|
||||||
|
- `uiAccess` in the manifest would lift the first limit only for a signed program installed under Program Files,
|
||||||
|
and Microsoft reserves it for assistive technology. The plan does not use it (D6, accepted).
|
||||||
|
|
||||||
|
### 1.7 Sessions and launching games
|
||||||
|
|
||||||
|
Sunshine needs an app list written through its API and a hook program (`prep-cmd`) to learn when a game starts.
|
||||||
|
Lumen does not:
|
||||||
|
- **App list** = Arena Domi's visible library, read directly (the same mapping Play remotely uses today: Steam and
|
||||||
|
Epic by their launcher links, GOG and manual games by their `.exe` and folder; web games skipped). The ids clients
|
||||||
|
see are stable per game. Covers come from Arena Domi's own cover source, as today.
|
||||||
|
- **Desktop** is not in the list by default. It becomes a per-device choice ("Allow this device to see the whole
|
||||||
|
desktop"), off for TVs; phones use it with touch-to-mouse.
|
||||||
|
- **Launch**: lumen-host starts the game through the same launch path the Arena Domi window uses, watches for its
|
||||||
|
process and window (to pick the monitor, 1.2), turns game mode on, records "Play remotely started: <game> on
|
||||||
|
<device>" in the audit log, and starts the streams.
|
||||||
|
- **Quit game**: lumen-host asks the game to close (closes its main window), waits up to 10 seconds, and if it is
|
||||||
|
still running leaves it running and tells the client "The game is still open on the PC". It never kills a game
|
||||||
|
(unsaved progress). Ending the session turns game mode off and records "Play remotely ended".
|
||||||
|
- **Client gone without Quit** (TV switched off): the control channel times out (PROTOCOL.md 3.3: periodic pings),
|
||||||
|
the stream stops at once, the game keeps running, and the session ends after a grace period so the device can
|
||||||
|
come back (`resume`).
|
||||||
|
|
||||||
|
### 1.8 Network
|
||||||
|
|
||||||
|
- **GameStream first**, unchanged on the wire, so that clients that speak GameStream work without changes: our own
|
||||||
|
`gs-probe`, Arena Domi Remote, and Arena Domi TV (built on DomiStream). lumen-host speaks HTTP and HTTPS
|
||||||
|
(serverinfo, pairing, applist, launch, resume, cancel), RTSP (OPTIONS, DESCRIBE, SETUP, ANNOUNCE, PLAY), the ENet
|
||||||
|
control channel with AES-GCM, RTP video with Reed-Solomon FEC, and RTP Opus audio with AES-CBC.
|
||||||
|
- **Binding**: lumen-host binds every listening socket itself, to exactly the addresses Play remotely allows (the
|
||||||
|
Via Domi interface, loopback, and the home network only where Mark's decisions say so). Unlike Sunshine, Lumen can
|
||||||
|
bind several addresses at once, so the loopback/VPN forwarder planned for Sunshine is not needed for Lumen.
|
||||||
|
- **Beside Sunshine**: while both are installed, Lumen uses its own port base (Sunshine's default ports + 1000:
|
||||||
|
HTTP 48989, HTTPS 48984, RTSP 49010, video 48998, control 48999, audio 49000), so the two never collide.
|
||||||
|
A GameStream client learns the HTTPS port from serverinfo, the RTSP address from the launch answer and the stream
|
||||||
|
ports from RTSP (PROTOCOL.md sections 0, 1.2, 1.4; U4 and U5 say what is still to confirm), so a client only needs
|
||||||
|
"this PC on port 48989". Whether Arena Domi Remote accepts a host with a port is checked
|
||||||
|
black-box in L1 (risk R10). When Sunshine is gone, Lumen can take the standard ports.
|
||||||
|
- **Then Lumen's own transport** (roadmap Day 4, a separate plan): frame-aware packets, adaptive FEC, slice pacing,
|
||||||
|
an input lane and congestion control inside the Via Domi tunnel, chosen by Arena clients through a capability
|
||||||
|
flag, with GameStream as the fallback. Nothing in this plan's milestones depends on it.
|
||||||
|
|
||||||
|
### 1.9 Pairing: Tessera grants, no PIN for Arena clients
|
||||||
|
|
||||||
|
GameStream pairing proves, with a 4-digit PIN, that a client certificate belongs to someone the owner trusts. Arena
|
||||||
|
Domi already decides trust another way: every device holds its own key, and the PC's owner grants it Play remotely
|
||||||
|
with one click (no PIN, no code, Mark's decision). With Lumen, the host side of pairing is ours, so:
|
||||||
|
- **Arena clients (Arena Domi TV, our Windows and Android clients)**: the device's grant decides. The device sends
|
||||||
|
its signed pair request to Arena Domi as today; when the grant holds, lumen-host completes the GameStream pairing
|
||||||
|
for that device's client certificate itself, without a PIN anywhere (no PIN generated by the client to forward,
|
||||||
|
no submission to another program). A device that already holds a grant from the Sunshine days is accepted by
|
||||||
|
Lumen without asking the owner again.
|
||||||
|
- **Arena Domi Remote (today)**: it pairs the GameStream way. The owner types the 4 digits the phone shows into
|
||||||
|
Arena Domi's "Enter the code from your phone" box, exactly as with Sunshine today; lumen-host holds the pending
|
||||||
|
pairing and the box supplies its PIN. The same box, the same click count. Whether Arena Domi Remote should learn
|
||||||
|
the grant-based pairing instead was decided against (D5): it keeps the code box.
|
||||||
|
- **The host's identity**: the GameStream host certificate and its RSA key are made by lumen-host on first run and
|
||||||
|
the key is kept in Custos, never in a file. The PC's Play remotely signing key (Tessera) stays what it is.
|
||||||
|
- **Pairing state** (paired client certificates, which device they belong to) is public data on disk, each record
|
||||||
|
signed by the host key; an edited record fails its signature and is dropped.
|
||||||
|
- Clients paired with Sunshine are **not** imported into Lumen (that would mean reading Sunshine's state and
|
||||||
|
copying its identity). Each client pairs with Lumen once; for Arena clients that is invisible (the grant carries
|
||||||
|
over), for Arena Domi Remote it is one typed code.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Migration: Lumen beside Sunshine, then instead of it
|
||||||
|
|
||||||
|
| Stage | What changes | Who sees it |
|
||||||
|
| :-- | :-- | :-- |
|
||||||
|
| A. Beside | lumen-host runs on its own ports (1.8) next to Sunshine, turned on by a hidden developer switch. Only test clients use it | nobody |
|
||||||
|
| B. Per client | Arena Domi keeps an **engine per device** (`sunshine` or `lumen`). Arena Domi TV learns its engine and port from the "Find my PC" answer, so it switches with no action. Arena Domi Remote gets Lumen as a second entry for the same PC (or by its own update) | the owner, in Settings → Play remotely → Devices ("Streams with: Lumen") |
|
||||||
|
| C. Switch | a client moves to Lumen when Lumen passes **the same end-to-end suite** for that client as Sunshine does (7.6) and the harness shows Lumen's median and p95 at least as good (the roadmap's Day 3 gate). Order: gs-probe and the Windows client, then Arena Domi Remote, then Arena Domi TV | each switch is reported to Mark with its evidence |
|
||||||
|
| D. Default | Lumen is the default engine for every client. Sunshine is a hidden fallback under "Show expert options" (roadmap J4): still installed, used only for a device set to it | "Sunshine" appears only under expert options |
|
||||||
|
| E. Removal | when Mark says so, Arena Domi removes the Sunshine **it installed** with the existing single elevated step (it also removes the firewall rules named for Sunshine), and Lumen moves to the standard ports. A Sunshine that was on the PC before Arena Domi is left alone, as today | one UAC prompt, at Mark's request |
|
||||||
|
|
||||||
|
- **Fallback while both exist**: if lumen-host fails to start a session, Arena clients may retry on Sunshine
|
||||||
|
automatically (stages B to D), and the failure is reported, never hidden.
|
||||||
|
- **Uninstalling Arena Domi** removes lumen-host, its firewall rules (in the same single elevated step that removes
|
||||||
|
the others), its pairing records and its host key in Custos. Nothing of Lumen survives an uninstall.
|
||||||
|
- **Turning Play remotely off** stops lumen-host; the firewall rules stay until uninstall (Mark's rule for
|
||||||
|
Sunshine's rules, applied to Lumen's).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. What lives where
|
||||||
|
|
||||||
|
### 3.1 DomiStream (this repo, public, sans-I/O)
|
||||||
|
|
||||||
|
**Reused as it is** (already written and tested for the client): the pairing crypto (AES, SHA-256, RSA signatures,
|
||||||
|
certificate parsing and our DER writer), session keys, Reed-Solomon (`fec::ReedSolomon::encode` exists), RTP and
|
||||||
|
the video/audio packet headers, the control frame cipher and message codec, `input::parse_input` and the gamepad
|
||||||
|
messages, the RTSP request parser and framer, the SDP parser, the HTTP XML reader, the ENet wire structs, the clock
|
||||||
|
and randomness seams.
|
||||||
|
|
||||||
|
**Added** (each with tests written first, a fuzz target for each parser, and the mutation pass):
|
||||||
|
|
||||||
|
| Module (proposed) | What |
|
||||||
|
| :-- | :-- |
|
||||||
|
| `host::pairing` | the host's pairing state machine: the phases of PROTOCOL.md 1.5 from the other side (server challenge, checks of the client's hashes and signature, host signature), a pending-PIN slot fed by the caller |
|
||||||
|
| `host::http` | request-line and query parsing (strict, capped), and the XML answers: serverinfo, applist, launch/resume/cancel, pair, errors |
|
||||||
|
| `rtsp::server` | the host's RTSP session: request order, CSeq, SETUP ports, the DESCRIBE answer (SDP writer), a strict ANNOUNCE parser into a typed stream configuration |
|
||||||
|
| `enet::host` | the accepting side of ENet: connect, verify connect, reliable channel, ping and timeouts |
|
||||||
|
| `control::host` | the host side of the control channel: client-to-host decryption, host-to-client messages (rumble, HDR mode once measured, termination) |
|
||||||
|
| `video::packetizer` | an encoded frame → RTP + NV-header packets, FEC blocks with parity, optional encryption |
|
||||||
|
| `audio::packetizer` | Opus packets → RTP, AES-CBC, parity once U16 is settled |
|
||||||
|
| `input::touch` | the client-side gesture recogniser of 1.6 (pure, timed points in, events out) |
|
||||||
|
| `input::keymap` | GameStream key codes ↔ scan codes, as a pure table both sides can use |
|
||||||
|
| `pacing`, `harness` | the frame pacer's maths and the harness statistics (median, p95, clock offset) |
|
||||||
|
|
||||||
|
The client and host halves are tested **against each other in memory**: a DomiStream client and a DomiStream host
|
||||||
|
run a whole session in one test (pairing, RTSP, control, video with loss and FEC recovery, audio), with no socket.
|
||||||
|
That catches every asymmetric mistake before a real client is involved. The release that adds the host side is
|
||||||
|
`stream-v0.2.0`.
|
||||||
|
|
||||||
|
### 3.2 Arena Domi (private)
|
||||||
|
|
||||||
|
- **lumen-host's I/O**: sockets and TLS (rustls, server side, client certificates checked against the paired list),
|
||||||
|
capture, the colour pass, NVENC, WASAPI and Opus, input injection and ViGEmBus, launching and watching games,
|
||||||
|
pacing threads. Proposed home: inside `crates/arena-host` (the Play remotely crate), with `lumen-host.exe` as a
|
||||||
|
new binary of that crate. Each Windows API sits behind a trait (`Capturer`, `Encoder`, `AudioSource`, `Injector`,
|
||||||
|
`Pads`, `Launcher`) with a fake, so the logic is tested without a GPU or a desktop.
|
||||||
|
- **arena-host** keeps the pairing gate, grants, devices, the engine per device, the code box, audit records and
|
||||||
|
turning Lumen on and off.
|
||||||
|
- **Capture and encode** could instead live in DomiCapture (public, CPAL-1.0), which the roadmap names for the
|
||||||
|
zero-copy encode path and which Pictor Domi will share. That crate has no code yet and belongs to the Arena build
|
||||||
|
lead's plan; D3: capture/encode start in arena-host and move to DomiCapture at L4.
|
||||||
|
- What touches files outside Play remotely's agreed folders (installer, tray agent, shared seams) goes through the
|
||||||
|
Arena build lead, one small PR each, as agreed on 2026-11-25.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Risks, and how each is retired early
|
||||||
|
|
||||||
|
| # | Risk | Retired by | When |
|
||||||
|
| :-- | :-- | :-- | :-- |
|
||||||
|
| R1 | **Clean room.** The host side of GameStream is best documented in GPL code, and GPL-provenance values sit in permissive sources (the audio parity matrix, the HDR message layout) | Sources limited to section 0's list; Moonshine read as a host for facts only; GPL-provenance values never used until measured (6.2); every PR adds its source rows; the GPL Remote app's workers and Lumen's workers never share a workspace, code or review; each PR body carries a clean-room checklist (sources read, none forbidden, provenance of every constant) | every PR, from L0 |
|
||||||
|
| R2 | **Interop with real clients**: a host must accept exactly what clients send (U5, U6, U9, U10 from the host side) | the in-memory client↔host test (L1); Sunshine as a black-box oracle (our gs-probe's byte logs of what Sunshine sends); then the first real client (Arena Domi Remote in the Android emulator, black-box) against lumen-host's listeners at the end of L1, before any video work depends on it | L1 |
|
||||||
|
| R3 | **Audio FEC matrix (U16)** is GPL-provenance | send audio without parity and verify clients play it; solve the matrix from Sunshine's captured parity (our measurement) | L2, L6 |
|
||||||
|
| R4 | **Colours differ between phone and PC** (range, transfer, HDR) | SDR BT.709 limited by default with correct VUI; test patterns decoded on the client and compared (7.5); HDR only after the HDR message is measured | L4 |
|
||||||
|
| R5 | **Input that cannot land**: elevated games, the secure desktop (UIPI) | detect and tell the client; accepted as the price of "no admin rights" (D6) | L3 |
|
||||||
|
| R6 | **Firewall rules need admin**; inbound connections on a public-profile network are blocked without them | decision D1 before L5; until then the emulator connects over loopback, which needs no rule | L5 |
|
||||||
|
| R7 | **ViGEmBus** is a third-party driver that its authors no longer develop | used only if Mark installed it; pads are refused cleanly without it; our own driver later (roadmap open point 13) | L3 |
|
||||||
|
| R8 | **Anti-cheat** may dislike desktop capture, synthetic input or virtual pads | Lumen never touches the game process; a short list of games is tested before the switch (C) and any that refuse are listed in the client ("Streaming isn't allowed by this game") | L6 |
|
||||||
|
| R9 | **Cost to the game** (GPU time of the colour pass, NVENC sessions, CPU) | the harness reports the game's frame rate with and without streaming; target under 3 % loss, measured | L2, L6 |
|
||||||
|
| R10 | **A client that cannot use a non-standard port** | checked black-box in L1 (Arena Domi Remote with port 48989); if it fails, the fork's workers get a written requirement, or Lumen waits for stage E for that client | L1 |
|
||||||
|
| R11 | **Desktop Duplication limits**: at most four duplicating processes; Arena's own overlay capture, Sunshine and Lumen all duplicate | one Lumen session at a time; lumen-host releases its duplication when idle; the error (`DXGI_ERROR_NOT_CURRENTLY_AVAILABLE`) is reported in plain words | L2 |
|
||||||
|
| R12 | **Licences of the native pieces** (NVENC header, libopus, ViGEmClient, their Rust bindings) | each read and logged before it is added; only MIT, BSD, Apache, ISC, zlib or CPAL; NVIDIA's DLL is the driver's, never shipped | L0 |
|
||||||
|
| R13 | **Codec patents** if Arena Domi is sold (roadmap open point 9) | the encoder is the user's GPU's hardware; flagged to Mark, not decided here | before sale |
|
||||||
|
| R14 | **Estimates**: GameStream host work has unknowns we cannot see before real clients connect | milestones end in demos, each small; the plan is re-estimated after L1 with real numbers | L1 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Milestones
|
||||||
|
|
||||||
|
Estimates are working days of one engineer (with QA writing tests first, as DomiStream did), on this PC, gated by
|
||||||
|
the load rule. Each milestone ends in a demo Mark can see. Total: **about 18 days, 22 to 23 with a 25 % margin**.
|
||||||
|
|
||||||
|
| # | Milestone | Content | Days | Demo for Mark |
|
||||||
|
| :-- | :-- | :-- | :-- | :-- |
|
||||||
|
| L0 | Spikes | Read and log the NVENC programming guide and header licence, libopus and ViGEmClient licences. A throwaway Rust spike, run only with Mark present: duplicate the HDR desktop in FP16, convert to NV12 and P010 on the GPU, encode 10 s of HEVC with NVENC, write the file; time each step | 1 | a 10 s HEVC file of a test pattern window (SDR and HDR) and a table: capture, convert and encode time per frame |
|
||||||
|
| L1 | Host protocol + first contact | DomiStream host side of section 3.1 (pairing, HTTP, RTSP server, ANNOUNCE, ENet host, control host, both packetizers), the in-memory client↔host session test, fuzz targets. A lumen-host skeleton (listeners on loopback only, no capture) that Arena Domi Remote in the Android emulator can find, pair with (code box) and list games from | 4 | the emulator on this PC pairs with Lumen and shows Arena Domi's game list; test and fuzz report |
|
||||||
|
| L2 | First stream | Capture (SDR path, and FP16 → SDR), NVENC HEVC/H.264 low latency, pacing, WASAPI + Opus (no audio parity), keyboard and relative mouse, launch from the library, quit, game mode and audit; beside Sunshine on its own ports | 4 | a game streams from Lumen to the emulator, with sound and keyboard/mouse, while Sunshine is still installed |
|
||||||
|
| L3 | Input, all of it | absolute mouse mapping, wheel, scan-code keyboard, text, ViGEmBus pads with rumble, the touch-to-mouse spec and `input::touch`, UIPI detection; the input e2e (7.3) running green | 2 | a scripted tap, long press and two-finger scroll land at the right places in the Arena input probe; e2e report |
|
||||||
|
| L4 | Colour and displays | capture/encode move from arena-host to DomiCapture (D3); range/colour-space negotiation from measurement, HDR → SDR tone mapping checked, monitor choice and switching, GPU scaling; HDR to HDR clients only if the HDR message has been measured | 2 | test pattern on the PC and on the phone side by side, with the measured colour differences |
|
||||||
|
| L5 | Pairing and per-device engine | Tessera-grant pairing with no PIN for Arena clients, the code box for Arena Domi Remote, the engine per device, Lumen's binding on the allowed addresses, firewall rules (after D1), the installer seam | 2 | gs-probe pairs with Lumen with no PIN; the phone pairs with a code; Settings shows "Streams with: Lumen" |
|
||||||
|
| L6 | Harness and the Day 3 gate | the same-PC latency harness (7.4), Lumen against Sunshine, tuning (pacing, VBV, slices, priorities), the game's frame-rate cost, a 2-hour soak, audio parity once U16 is solved | 2 | the harness table: median and p95 for Lumen and Sunshine, and the gate answer |
|
||||||
|
| L7 | Switch-over | stage C for each client that passes, Sunshine as the hidden fallback (stage D), uninstall path checked | 1 | Arena Domi Remote and the Windows client streaming from Lumen by default; Sunshine only under expert options |
|
||||||
|
|
||||||
|
Not in these estimates: Arena Domi TV itself (it switches when it exists, because it is built on DomiStream),
|
||||||
|
Lumen's own transport (roadmap Day 4), AMF/Quick Sync, 4:4:4, a virtual display per client, and the iOS client
|
||||||
|
(5.2).
|
||||||
|
|
||||||
|
### 5.1 The first build phase (accepted: Mark's go, 2026-12-04)
|
||||||
|
|
||||||
|
**L0 + L1**: the spikes (to retire the GPU and licence risks while they are cheap) and the DomiStream host side
|
||||||
|
with the in-memory session test, ending with Arena Domi Remote in the emulator pairing with a Lumen skeleton over
|
||||||
|
loopback. Nothing touches Sunshine, the owner's desktop, mouse or windows, except the one L0 spike run with Mark
|
||||||
|
present. About 5 days.
|
||||||
|
|
||||||
|
### 5.2 Later client phase: iOS
|
||||||
|
|
||||||
|
Every Domi app eventually runs on Windows, Android and iOS (Mark, 2026-12-04). Lumen's host does not change for
|
||||||
|
iOS: an iOS client speaks GameStream (later Lumen's own transport) to the same lumen-host. The iOS client is its own
|
||||||
|
phase after the switch-over (L7): DomiStream compiles for `aarch64-apple-ios` (it is pure Rust with no I/O, so the
|
||||||
|
check is a build and the test suite on that target), VideoToolbox decodes, the same `input::touch` recogniser maps
|
||||||
|
gestures, and the client pairs through a Tessera grant like Arena's other clients, with no PIN. It is planned and
|
||||||
|
estimated when phase L7 is done; no Moonlight iOS code is read for it (the clean room covers every client).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. Sources and measurements for the host side
|
||||||
|
|
||||||
|
### 6.1 What may be read
|
||||||
|
|
||||||
|
- Everything already allowed in [CLEAN_ROOM.md](CLEAN_ROOM.md), with one point made explicit: **Moonshine is a
|
||||||
|
host**, so its host-side code (BSD-2) is the most useful permissive reference for Lumen's state machines; it is
|
||||||
|
read for facts, logged, and never copied.
|
||||||
|
- Public OS and SDK documentation: Microsoft Learn (DXGI, Windows.Graphics.Capture, Core Audio, input, display
|
||||||
|
configuration), NVIDIA's Video Codec SDK documentation and API header, AMD AMF and Intel oneVPL documentation, the
|
||||||
|
libopus documentation, the ViGEm documentation, the Opus and RTP RFCs, ITU-R BT.709 / BT.2020 / BT.2100 and SMPTE
|
||||||
|
ST 2084.
|
||||||
|
- **Forbidden for host work** (D2, Mark 2026-12-04): the source of OBS Studio (GPL-2.0) and of FFmpeg (LGPL/GPL)
|
||||||
|
is not read either, because both contain encoder and capture code that would be tempting to port.
|
||||||
|
|
||||||
|
### 6.2 Measurements we make ourselves
|
||||||
|
|
||||||
|
- **Sunshine as a black-box oracle.** Our own `gs-probe` (a GameStream client) connects to the pinned Sunshine and
|
||||||
|
logs what it sends, as allowed today ([LIVE-INTEROP.md](LIVE-INTEROP.md)): headers, packet layouts, FEC parity
|
||||||
|
(to solve the audio matrix, U16), the HDR message bytes with HDR on (its layout), timings.
|
||||||
|
- **Clients as black boxes** (D2, accepted). Arena Domi Remote (in the Android emulator) and the official
|
||||||
|
Moonlight PC app connect to lumen-host, and lumen-host logs what they send: ANNOUNCE values per client setting
|
||||||
|
(range, codec, HDR), input packets per gesture, ENet details. We run the binaries and read our own logs; we never
|
||||||
|
open their source, disassemble or decompile them.
|
||||||
|
- Every fact found this way goes into PROTOCOL.md with a measurement tag, the date and the setup.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 7. Test strategy
|
||||||
|
|
||||||
|
### 7.1 Tests first
|
||||||
|
|
||||||
|
- **DomiStream**: tests before code for every new parser and state machine (host pairing, HTTP requests, RTSP
|
||||||
|
server, ANNOUNCE, ENet host, control host), the packetizers and the gesture recogniser. Vectors come from
|
||||||
|
independent tools (OpenSSL, Python) and from the client half (round trips); property tests: packetize →
|
||||||
|
lose up to the parity count → depacketize gives the same frame; any gesture sequence gives balanced button
|
||||||
|
presses. Mutation pass as in [MUTATION.md](MUTATION.md).
|
||||||
|
- **Fuzzing**: one libFuzzer target per new parser (HTTP request and query, RTSP request, ANNOUNCE/SDP, ENet host
|
||||||
|
datagram, control client-to-host frame, INPUT_DATA already exists), 60 s each per release and a long run for the
|
||||||
|
pairing and ENet host targets, 0 crashes required.
|
||||||
|
- **arena-host / lumen-host**: the pure parts (coordinate mapping, key map, colour matrices and the tone curve,
|
||||||
|
engine choice, app list, quit logic) are unit-tested; the I/O sits behind traits with fakes, so a whole session
|
||||||
|
(control in, injector calls out) runs in a test without a desktop.
|
||||||
|
|
||||||
|
### 7.2 GPU tests
|
||||||
|
|
||||||
|
Capture → convert → encode → decode on the reference GPU with known patterns (colour bars, grey ramps, a PQ ramp),
|
||||||
|
compared numerically (PSNR and colour difference thresholds). They need the real GPU and desktop, so they are
|
||||||
|
`#[ignore]` by default and run only under the load rule, and only with Mark's agreement when they capture his
|
||||||
|
display.
|
||||||
|
|
||||||
|
### 7.3 The input e2e, from L2 on
|
||||||
|
|
||||||
|
The **Arena input probe** (our own tool: a window that logs every mouse, key, touch and pointer event with its
|
||||||
|
coordinates) is shown on the streamed display; a client streams it and sends scripted input; the probe's log is the
|
||||||
|
assertion.
|
||||||
|
|
||||||
|
| Step | Client | Expected in the probe log |
|
||||||
|
| :-- | :-- | :-- |
|
||||||
|
| tap at stream point (x, y) | emulator (adb tap) and gs-probe | left down and up at the mapped PC point, within 2 px |
|
||||||
|
| long press 800 ms | emulator (adb swipe from a point to itself) | right down and up at that point, no left click |
|
||||||
|
| two-finger drag up | emulator (an instrumentation test APK of our own that injects a two-pointer gesture) | wheel events with the right sign and no buttons |
|
||||||
|
| one-finger drag | emulator | left down, moves along the path, left up |
|
||||||
|
| typed text and key combos | gs-probe | the same characters and scan codes, in order |
|
||||||
|
| pad buttons and sticks | gs-probe | the virtual pad's state (the probe reads XInput) |
|
||||||
|
|
||||||
|
- **Two tiers.** The *hermetic* tier replaces `SendInput` with a recording fake and checks the calls; it runs in
|
||||||
|
every test run. The *live* tier injects for real, so it moves the PC's pointer: it runs only in a sitting agreed
|
||||||
|
with Mark (or in a Windows Sandbox or virtual machine, where the software encoder stands in for NVENC).
|
||||||
|
- The emulator connects over loopback, so no firewall rule and no network outside the PC are involved.
|
||||||
|
- Against Arena Domi Remote the gesture rows will fail until its workers implement the touch spec (1.6); the e2e is
|
||||||
|
how that is checked, and it is reported as a client gap, not hidden.
|
||||||
|
|
||||||
|
### 7.4 Latency harness, from L2 on
|
||||||
|
|
||||||
|
- **Same PC, one clock**: the client (gs-probe with hardware decode, later the emulator) sends a click at t0; the
|
||||||
|
probe flips a large patch from black to white on that click; the client timestamps the first decoded frame that
|
||||||
|
shows white (t1). t1 − t0 is the input-to-decoded latency, without the client's display. 200 samples per run,
|
||||||
|
alternating Lumen and Sunshine runs, median and p95 reported.
|
||||||
|
- **Inside lumen-host**: each frame carries timestamps for capture, convert done, encode done and last packet sent,
|
||||||
|
logged to a local trace, so a regression points at its stage.
|
||||||
|
- **Cost to the game**: the game's frame rate with and without a stream (Arena Domi's own frametime statistics).
|
||||||
|
- **Away from home** (Via Domi) needs two clocks: the harness maths in DomiStream estimates the offset; that is the
|
||||||
|
roadmap's Day 2/4 harness and is reused when it exists.
|
||||||
|
|
||||||
|
### 7.5 Colour tests
|
||||||
|
|
||||||
|
A colour-pattern window (bars, ramps, near-black steps, an SDR-white patch) is streamed; the client saves a decoded
|
||||||
|
frame; the PC saves the captured frame; both are converted to the same space and compared patch by patch. This
|
||||||
|
settles the range and colour-space values (1.3) per client.
|
||||||
|
|
||||||
|
### 7.6 The switch-over suite (one per client)
|
||||||
|
|
||||||
|
Pair → list games → launch → 60 s of video and audio → input e2e → quit → reconnect after a dropped connection →
|
||||||
|
pair removal refuses the client → a 2-hour soak without memory or handle growth. A client moves to Lumen (stage C)
|
||||||
|
when this suite passes on Lumen as it does on Sunshine, and the harness says Lumen is at least as fast.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 8. Decisions (Mark, 2026-12-04: all six accepted as proposed)
|
||||||
|
|
||||||
|
| # | Question | Decision |
|
||||||
|
| :-- | :-- | :-- |
|
||||||
|
| D1 | Lumen needs Windows firewall rules for `lumen-host.exe` on its ports, which needs admin | **Yes**: the existing single UAC step at "Turn on Play remotely" also creates Lumen's rules (scoped to `lumen-host.exe`, its ports and the allowed addresses). No new prompt. They stay until uninstall, like Sunshine's |
|
||||||
|
| D2 | Black-box logging of what clients send to Lumen; OBS Studio and FFmpeg sources | **Yes**: lumen-host may log what Arena Domi Remote and the official Moonlight PC app send to it (run and observe only, never source, disassembly or decompiling). **OBS Studio and FFmpeg source are forbidden for host work** ([CLEAN_ROOM.md](CLEAN_ROOM.md)) |
|
||||||
|
| D3 | Where capture and encode live | **arena-host first**, behind traits; they **move to DomiCapture at L4** |
|
||||||
|
| D4 | Who starts lumen-host at sign-in | **The tray agent**, once Lumen is the default engine (stage D). Before that, Arena Domi starts it when Play remotely uses Lumen |
|
||||||
|
| D5 | Arena Domi Remote: the code box or a no-PIN spec | **Keep the code box.** No grant-based pairing spec is published into the GPL app |
|
||||||
|
| D6 | Games running as administrator | **Accepted**: they get no input from Lumen, and the client shows a clear message ("This game runs as administrator, so Arena Domi can't control it") |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 9. Sources used for this plan
|
||||||
|
|
||||||
|
Logged as S-22 in [CLEAN_ROOM.md](CLEAN_ROOM.md): Microsoft Learn pages on DXGI 1.5 and `DuplicateOutput1`,
|
||||||
|
Desktop Duplication, HDR and advanced colour, `GraphicsCaptureSession` (`IsBorderRequired`,
|
||||||
|
`IsCursorCaptureEnabled`), `SendInput` and `MOUSEINPUT`, the UIAccess security considerations and the UAC policy
|
||||||
|
for UIAccess, `CreateSyntheticPointerDevice` / `InjectSyntheticPointerInput`, and WASAPI loopback recording with
|
||||||
|
process loopback activation. Everything else here comes from this repository's own documents and the 2026-12-04
|
||||||
|
live evidence (the phone's input packets).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 10. L0 results (2026-12-04)
|
||||||
|
|
||||||
|
**Done:** the licence reading and the GPU spike. The spike is a throwaway Rust program with a small C shim over the
|
||||||
|
NVENC header, kept outside git. It showed no window, injected nothing and opened no socket. The desktop bitstreams
|
||||||
|
never left memory (nothing of the screen was written to disk); only two synthetic-pattern encodes were written, and
|
||||||
|
they stay outside git.
|
||||||
|
|
||||||
|
**Licences** (logged as S-23 to S-25 in [CLEAN_ROOM.md](CLEAN_ROOM.md)):
|
||||||
|
|
||||||
|
| Piece | Licence | Note |
|
||||||
|
| :-- | :-- | :-- |
|
||||||
|
| `nvEncodeAPI.h`, API **12.0**, from NVIDIA's own public repository (VideoProcessingFramework, Apache-2.0 repository, archived) | MIT (the header's own notice) | used. No account and no licence acceptance needed |
|
||||||
|
| `nvEncodeAPI.h`, API 8.1, NVIDIA's video-sdk-samples | MIT | **not usable**: the driver refuses its presets (below) |
|
||||||
|
| NVENC API 12.1 or newer headers | NVIDIA's SDK download (account and terms) | not needed for anything planned; if a later feature needs it, that download is Mark's decision |
|
||||||
|
| libopus | BSD-3-Clause style (Xiph COPYING) | for L2 |
|
||||||
|
| `opus` crate / `audiopus_sys` | Apache-2.0 or MIT / ISC | candidates for L2, chosen then |
|
||||||
|
| ViGEmClient | MIT (repository archived) | the client library for ViGEmBus |
|
||||||
|
| ViGEmBus | BSD-3-Clause (repository archived) | Mark installs it himself; never shipped |
|
||||||
|
| `vigem-client` crate | MIT | candidate binding for L3 |
|
||||||
|
| `windows` crate | MIT or Apache-2.0 | used by the spike |
|
||||||
|
|
||||||
|
**Measured on the reference PC** (RTX 3090, driver NVENC API maximum 13.1; primary 2560x1440 HDR; one run,
|
||||||
|
idle desktop):
|
||||||
|
|
||||||
|
| What | Result |
|
||||||
|
| :-- | :-- |
|
||||||
|
| Display state | both outputs report colour space `RGB_FULL_G2084_NONE_P2020` (HDR on); primary 10 bits per colour; peak 1499 nits, full frame 799; SDR white level 240 nits |
|
||||||
|
| Desktop Duplication | the HDR desktop arrives as `R16G16B16A16_FLOAT` (FP16 scRGB), as planned. **Needs per-monitor DPI awareness**: without it `DuplicateOutput1` returned `DXGI_ERROR_UNSUPPORTED` and the 4K output showed as 2560x1440 |
|
||||||
|
| NVENC with the API 8.1 header | `nvEncGetEncodePresetConfig` refuses the legacy low-latency preset (`NV_ENC_ERR_UNSUPPORTED_PARAM`) and initialisation without a preset fails (`NV_ENC_ERR_INVALID_PARAM`) |
|
||||||
|
| NVENC with the API 12.0 header | preset P1, tuning "ultra low latency", CBR 20 Mbit/s, VBV one frame, infinite GOP: works, 8-bit and 10-bit HEVC; the first access unit is VPS, SPS, PPS, IDR |
|
||||||
|
| Copy of the captured frame (GPU, waited) | 1.6 ms (one sample: the desktop was idle, so only one new frame arrived) |
|
||||||
|
| Colour pass FP16 → NV12 / P010, 2560x1440 (one compute dispatch, waited) | median 0.57 / 0.50 ms, p95 1.01 / 0.93 ms |
|
||||||
|
| NVENC HEVC 2560x1440, synchronous | 8-bit median 2.56 ms, p95 2.70 ms; 10-bit median 2.56 ms, p95 2.80 ms |
|
||||||
|
| NVENC HEVC 1920x1080 (pattern) | median 1.4 to 1.5 ms, p95 1.7 to 2.5 ms |
|
||||||
|
| Capture to bitstream, sum of medians, 1440p | about **4.7 ms** on the host |
|
||||||
|
|
||||||
|
What L0 did not settle (and where it is settled): capture timing under motion and at a game's frame rate (L2,
|
||||||
|
with the harness); whether the colour pass matches what a decoder shows (L4, the pattern files are the start);
|
||||||
|
the asynchronous NVENC mode, which NVIDIA recommends on Windows (L2).
|
||||||
|
|
||||||
@@ -468,6 +468,12 @@ Reed-Solomon erasure code over GF(2^8), polynomial `0x11D` [F] [W5]:
|
|||||||
`P = [[8e f4 47 a7], [f4 8e a7 47]]`; `k = 3, m = 1`: `P = [[01 8e f4]]`.
|
`P = [[8e f4 47 a7], [f4 8e a7 47]]`; `k = 3, m = 1`: `P = [[01 8e f4]]`.
|
||||||
The capture settles it without any loss: parity packets are always sent, so our encoder must reproduce the
|
The capture settles it without any loss: parity packets are always sent, so our encoder must reproduce the
|
||||||
captured parity bytes (offset 32 on) of every block.
|
captured parity bytes (offset 32 on) of every block.
|
||||||
|
- **Host side (Lumen, `video::packetizer`).** Our own choices, not from a source, until a capture compares them
|
||||||
|
with a real host: the fewest blocks (at most 4) in which every block can carry the requested parity within
|
||||||
|
`k + m <= 255`, every block but the last carrying `k = ceil(n / blocks)` data shards; per block the least
|
||||||
|
percentage, at or above the requested one, whose `m` reaches `minRequiredFecPackets`; a frame too big for that
|
||||||
|
gets the most parity that still fits (counted in the packetizer's stats). Data shards in order, then the block's
|
||||||
|
parity, block by block; RTP sequence numbers run on across frames, one per packet.
|
||||||
- The audio code is **not** this matrix (section 6.4).
|
- The audio code is **not** this matrix (section 6.4).
|
||||||
|
|
||||||
### 5.4 Feedback
|
### 5.4 Feedback
|
||||||
@@ -526,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
|
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.
|
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
|
### 6.5 Decoding
|
||||||
|
|
||||||
**Not DomiStream.** DomiStream outputs each Opus packet (or a "lost" marker) in sequence order plus the multistream
|
**Not DomiStream.** DomiStream outputs each Opus packet (or a "lost" marker) in sequence order plus the multistream
|
||||||
|
|||||||
@@ -211,3 +211,10 @@ path = "fuzz_targets/rtsp_client.rs"
|
|||||||
test = false
|
test = false
|
||||||
doc = false
|
doc = false
|
||||||
bench = false
|
bench = false
|
||||||
|
|
||||||
|
[[bin]]
|
||||||
|
name = "video_packetizer_roundtrip"
|
||||||
|
path = "fuzz_targets/video_packetizer_roundtrip.rs"
|
||||||
|
test = false
|
||||||
|
doc = false
|
||||||
|
bench = false
|
||||||
|
|||||||
@@ -0,0 +1,125 @@
|
|||||||
|
//! Fuzzes the host's video packetizer against the client's depacketizer (`docs/PROTOCOL.md` 5.2, 5.3, 7).
|
||||||
|
//! Arbitrary frame bytes and parameters (packet size, FEC percentage, minimum parity, encryption, frame type,
|
||||||
|
//! latency) → packetize two frames → lose up to `m` packets of every block → depacketize: both frames must come back
|
||||||
|
//! byte-exact, in order, with their headers. Every valid configuration must be accepted and every frame within
|
||||||
|
//! `max_bitstream_len` packetized.
|
||||||
|
//! How to run: see the comment at the top of `fuzz/Cargo.toml`.
|
||||||
|
|
||||||
|
#![no_main]
|
||||||
|
|
||||||
|
use libfuzzer_sys::fuzz_target;
|
||||||
|
|
||||||
|
use core::time::Duration;
|
||||||
|
use std::collections::BTreeMap;
|
||||||
|
|
||||||
|
use domistream::Instant;
|
||||||
|
use domistream::fec::parity_count;
|
||||||
|
use domistream::video::packet::parse_video_packet;
|
||||||
|
use domistream::video::packetizer::{EncodedFrame, VideoPacketizer, VideoPacketizerConfig};
|
||||||
|
use domistream::video::{FrameType, VideoCipher, VideoConfig, VideoDepacketizer, VideoEvent};
|
||||||
|
|
||||||
|
const KEY: [u8; 16] = *b"fuzz-video-key!!";
|
||||||
|
|
||||||
|
/// xorshift64*, seeded from the input: which packets are lost.
|
||||||
|
struct Rng(u64);
|
||||||
|
|
||||||
|
impl Rng {
|
||||||
|
fn below(&mut self, n: usize) -> usize {
|
||||||
|
self.0 ^= self.0 >> 12;
|
||||||
|
self.0 ^= self.0 << 25;
|
||||||
|
self.0 ^= self.0 >> 27;
|
||||||
|
(self.0.wrapping_mul(0x2545_F491_4F6C_DD1D) >> 33) as usize % n.max(1)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fuzz_target!(|data: &[u8]| {
|
||||||
|
let Some((head, body)) = data.split_first_chunk::<10>() else { return };
|
||||||
|
let [s0, s1, pct, min, flags, loss, split, l0, l1, first] = *head;
|
||||||
|
// 17..=4048: every packet size the receiver accepts, sealed or not.
|
||||||
|
let packet_size = 17 + u16::from_le_bytes([s0, s1]) % 4032;
|
||||||
|
let encrypt = flags & 1 != 0;
|
||||||
|
let frame_type = match (flags >> 1) & 3 {
|
||||||
|
0 => FrameType::Predicted,
|
||||||
|
1 => FrameType::Key,
|
||||||
|
2 => FrameType::Recovery,
|
||||||
|
_ => FrameType::Other((flags >> 3) | 0x08), // 8..=31: never a value with its own name (1, 2, 5)
|
||||||
|
};
|
||||||
|
let lossy = flags & 0x80 != 0;
|
||||||
|
let cipher = || encrypt.then(|| VideoCipher::new(KEY));
|
||||||
|
let config = VideoPacketizerConfig {
|
||||||
|
packet_size,
|
||||||
|
fec_percentage: pct,
|
||||||
|
min_required_fec_packets: min,
|
||||||
|
cipher: cipher(),
|
||||||
|
first_sequence: u16::from_le_bytes([first, s0]),
|
||||||
|
};
|
||||||
|
let mut tx = VideoPacketizer::new(config).expect("a valid configuration is accepted");
|
||||||
|
let mut rx =
|
||||||
|
VideoDepacketizer::new(VideoConfig { packet_size, cipher: cipher(), frame_timeout: Duration::from_millis(20) })
|
||||||
|
.expect("the receiver accepts the same packet size");
|
||||||
|
|
||||||
|
let cut = body.len() * usize::from(split) / 255;
|
||||||
|
let (a, b) = body.split_at(cut);
|
||||||
|
let frames = [a, b];
|
||||||
|
let mut rng = Rng(u64::from_le_bytes([s0, s1, pct, min, flags, loss, split, l0]) | 1);
|
||||||
|
let mut datagrams = Vec::new();
|
||||||
|
for (i, bitstream) in frames.iter().enumerate() {
|
||||||
|
assert!(bitstream.len() <= tx.max_bitstream_len(), "fuzz inputs stay far below the frame cap");
|
||||||
|
let frame = EncodedFrame {
|
||||||
|
frame_index: 0xFFFF_FFFF_u32.wrapping_add(i as u32),
|
||||||
|
frame_type,
|
||||||
|
rtp_timestamp: u32::from(l1) << 8,
|
||||||
|
processing_latency: u16::from_le_bytes([l0, l1]),
|
||||||
|
bitstream,
|
||||||
|
};
|
||||||
|
let out = tx.packetize(&frame).expect("a frame within the cap is packetized");
|
||||||
|
// Group by block (from the plaintext), then lose up to m of each block.
|
||||||
|
let mut blocks: BTreeMap<u8, (Vec<usize>, usize)> = BTreeMap::new();
|
||||||
|
for (j, d) in out.iter().enumerate() {
|
||||||
|
let plain = if encrypt { VideoCipher::new(KEY).decrypt(d).expect("our own seal opens") } else { d.clone() };
|
||||||
|
let p = parse_video_packet(&plain).expect("our own packet parses");
|
||||||
|
let m = parity_count(usize::from(p.nv.fec.data_shards), p.nv.fec.fec_percentage).expect("consistent FEC");
|
||||||
|
blocks.entry(p.nv.fec.block_index).or_insert_with(|| (Vec::new(), m)).0.push(j);
|
||||||
|
}
|
||||||
|
let mut keep = vec![true; out.len()];
|
||||||
|
if lossy {
|
||||||
|
for (positions, m) in blocks.values() {
|
||||||
|
let mut left = positions.clone();
|
||||||
|
for _ in 0..rng.below(m + 1).min(left.len()) {
|
||||||
|
let pick = left.swap_remove(rng.below(left.len()));
|
||||||
|
if let Some(k) = keep.get_mut(pick) {
|
||||||
|
*k = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Sent in order; every block keeps at least k packets, so frame 0 starts the receiver.
|
||||||
|
datagrams.extend(out.into_iter().zip(keep).filter(|(_, k)| *k).map(|(d, _)| d));
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut us = 1_000u64;
|
||||||
|
let mut got = Vec::new();
|
||||||
|
for d in &datagrams {
|
||||||
|
rx.push(Instant::from_micros(us), d).expect("within the receiver's cap");
|
||||||
|
us += 10;
|
||||||
|
while let Some(e) = rx.poll_event() {
|
||||||
|
got.push(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _ in 0..8 {
|
||||||
|
us += 1_000_000;
|
||||||
|
let _ = rx.handle_timeout(Instant::from_micros(us));
|
||||||
|
while let Some(e) = rx.poll_event() {
|
||||||
|
got.push(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
assert_eq!(got.len(), 2, "two frames out: {got:?}");
|
||||||
|
for (i, (e, want)) in got.iter().zip(frames).enumerate() {
|
||||||
|
let VideoEvent::Frame(f) = e else { panic!("frame {i} lost: {e:?}") };
|
||||||
|
assert_eq!(f.frame_index, 0xFFFF_FFFF_u32.wrapping_add(i as u32));
|
||||||
|
assert!(f.bitstream == want, "frame {i}: {} bytes out, {} in", f.bitstream.len(), want.len());
|
||||||
|
assert_eq!(f.header.frame_type, frame_type);
|
||||||
|
assert_eq!(f.header.processing_latency, u16::from_le_bytes([l0, l1]));
|
||||||
|
assert_eq!(f.rtp_timestamp, u32::from(l1) << 8);
|
||||||
|
}
|
||||||
|
});
|
||||||
Reference in New Issue
Block a user