[domistream] Session: a whole GameStream session between our client and our host, in memory
serverinfo over HTTP, pairing with the owner typing the phone's code, serverinfo over HTTPS (PairStatus 1), applist, launch (keys handed over), RTSP with one connection per request (the host's StreamConfig equals the client's ANNOUNCE), ENet + START_B, sealed video over a lossy link (exactly the parity budget lost per block, then a burst beyond it reported lost and answered with reference invalidation and an IDR request, then a recovery frame), sealed audio without parity (losses reported), typed input and a gamepad state, rumble, graceful termination, ENet disconnect and cancel. Also the Tessera-trusted path (no /pair, pinned host certificate) and an unpaired client refused over HTTPS. START_B, PERIODIC_PING and the IDR request go with empty bodies over the probe-style stack because ControlStream refuses them (U10).
This commit is contained in:
@@ -0,0 +1,962 @@
|
|||||||
|
//! A whole GameStream session between DomiStream's client and DomiStream's host (Lumen's protocol half), in memory,
|
||||||
|
//! with simulated time and seeded randomness (`docs/LUMEN-HOST-PLAN.md` 3.1, 7.1). Every stage goes through both
|
||||||
|
//! sides' own parsers and writers, so an asymmetric mistake shows here before a real client is involved:
|
||||||
|
//!
|
||||||
|
//! serverinfo (HTTP) → pairing with the owner typing the phone's code → serverinfo (HTTPS, paired) → applist → launch
|
||||||
|
//! (session keys handed over) → RTSP (the host's stream config equals the client's ANNOUNCE) → ENet + START_B →
|
||||||
|
//! video over a lossy link (FEC within the parity budget, then a burst beyond it, the client asks for recovery) →
|
||||||
|
//! audio (losses reported, no parity) → input and gamepad → rumble → termination, ENet disconnect, cancel.
|
||||||
|
//!
|
||||||
|
//! Also: a Tessera-trusted client that never pairs over the wire, and an unpaired client that HTTPS refuses.
|
||||||
|
//!
|
||||||
|
//! What the client cannot do with its shipped API is said where it happens: `ControlStream` refuses START_B,
|
||||||
|
//! PERIODIC_PING and the IDR request (bodies UNKNOWN U10, PROTOCOL.md 3.3), so the client side of control here is the
|
||||||
|
//! probe-style stack (`EnetClient` + `ControlCipher`) that sends those three with empty bodies, as `tools/gs-probe` does.
|
||||||
|
|
||||||
|
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::indexing_slicing, missing_docs)]
|
||||||
|
|
||||||
|
mod common;
|
||||||
|
|
||||||
|
use core::time::Duration;
|
||||||
|
|
||||||
|
use common::wire::{Endpoint, Impair, Wire, at};
|
||||||
|
use common::{HOST_KEY_PEM, SeqRng, pem_blocks};
|
||||||
|
use domistream::audio::{
|
||||||
|
AudioCipher, AudioConfig, AudioDepacketizer, AudioEvent, AudioFec, AudioPacketizer, AudioPacketizerConfig,
|
||||||
|
AudioParity,
|
||||||
|
};
|
||||||
|
use domistream::control::host::{DEFAULT_STOP_TIMEOUT, TERMINATION_GRACEFUL};
|
||||||
|
use domistream::control::message::encode_client_message;
|
||||||
|
use domistream::control::{
|
||||||
|
ClientControlMessage, ClientMessage, ControlCipher, ControlHost, ControlHostConfig, ControlHostEvent, Direction,
|
||||||
|
HostMessage, MessageType, parse_host_message,
|
||||||
|
};
|
||||||
|
use domistream::enet::{Delivery, EnetClient, EnetConfig, EnetEvent, EnetHostConfig, EnetHostState, EnetState};
|
||||||
|
use domistream::host::http::{
|
||||||
|
HostInfo, LaunchRequest, Route, app_list_xml, error_xml, launch_xml, ok_xml, pair_answer_xml, parse_request_head,
|
||||||
|
server_info_xml,
|
||||||
|
};
|
||||||
|
use domistream::host::pairing::{
|
||||||
|
HostIdentity, HostPairingConfig, HostPairingSession, HostPairingStep, PairAnswer, PairPhase, PairRequest,
|
||||||
|
PairedClient, Transport,
|
||||||
|
};
|
||||||
|
use domistream::http::launch::{AudioLayout, LaunchParams, launch_request};
|
||||||
|
use domistream::http::{
|
||||||
|
App, HttpRequest, Scheme, ServerInfo, app_list_request, cancel_request, parse_app_list, parse_launch_response,
|
||||||
|
parse_server_info, parse_status_response, server_info_request,
|
||||||
|
};
|
||||||
|
use domistream::input::{ButtonFlags, GamepadState, InputEvent, MouseButton};
|
||||||
|
use domistream::pairing::{
|
||||||
|
ClientIdentity, PairedHost, PairingSession, PairingStep, Pin, ServerCert, parse_pair_response,
|
||||||
|
};
|
||||||
|
use domistream::rtsp::client::{PING_PAYLOAD, VideoCodec};
|
||||||
|
use domistream::rtsp::sdp::{FeatureFlags, parse_surround_params};
|
||||||
|
use domistream::rtsp::server::{
|
||||||
|
ChromaSampling, DEFAULT_SESSION_TIMEOUT_SECS, StreamConfig as HostStreamConfig, SurroundSettings,
|
||||||
|
};
|
||||||
|
use domistream::rtsp::{
|
||||||
|
EncryptionFlags, HostOffer, NegotiatedStream, RtspClient, RtspFramer, RtspProgress, RtspServer, ServerConfig,
|
||||||
|
ServerEvent, StreamConfig as ClientStreamConfig, StreamPorts,
|
||||||
|
};
|
||||||
|
use domistream::video::packet::FRAME_HEADER_LEN;
|
||||||
|
use domistream::video::packetizer::{FecBlock, plan_fec_blocks};
|
||||||
|
use domistream::video::{
|
||||||
|
EncodedFrame, FrameType, VideoCipher, VideoConfig, VideoDepacketizer, VideoEvent, VideoPacketizer,
|
||||||
|
VideoPacketizerConfig,
|
||||||
|
};
|
||||||
|
use domistream::{Error, Instant, SessionKeys};
|
||||||
|
|
||||||
|
const UID: &str = "0123456789ABCDEF";
|
||||||
|
const DEVICE: &str = "Arena Domi TV test";
|
||||||
|
const HOST_ADDR: &str = "192.0.2.10";
|
||||||
|
const RTSP_PORT: u16 = 48010;
|
||||||
|
const PORTS: StreamPorts = StreamPorts { audio: 48000, video: 47998, control: 47999 };
|
||||||
|
const ALL: u8 = EncryptionFlags::CONTROL_V2 | EncryptionFlags::VIDEO | EncryptionFlags::AUDIO;
|
||||||
|
/// The host's video FEC percentage: Moonshine's default (S-31).
|
||||||
|
const FEC_PERCENT: u8 = 20;
|
||||||
|
|
||||||
|
// ================================================================================================ identities
|
||||||
|
|
||||||
|
fn host_identity() -> HostIdentity {
|
||||||
|
let key = pem_blocks(HOST_KEY_PEM, "PRIVATE KEY").pop().expect("host key PEM");
|
||||||
|
HostIdentity::from_der(&common::pairing_vectors().bytes("host_cert_der"), &key).expect("test-only host identity")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn client_identity(name: &str) -> ClientIdentity {
|
||||||
|
let v = common::pairing_vectors();
|
||||||
|
ClientIdentity::from_der(&v.bytes(&format!("{name}_cert_der")), &v.bytes(&format!("{name}_key_pkcs8_der")))
|
||||||
|
.expect("test-only client identity")
|
||||||
|
}
|
||||||
|
|
||||||
|
// ================================================================================================ the host's HTTP side
|
||||||
|
|
||||||
|
/// Lumen's HTTP and HTTPS listeners as the caller of `host::http` and `host::pairing` builds them.
|
||||||
|
struct LumenHttp {
|
||||||
|
identity: HostIdentity,
|
||||||
|
info: HostInfo,
|
||||||
|
apps: Vec<App>,
|
||||||
|
/// Clients whose certificate HTTPS accepts (paired, or recorded from a Tessera grant).
|
||||||
|
paired: Vec<PairedClient>,
|
||||||
|
pairing: Option<HostPairingSession>,
|
||||||
|
/// The code the owner types into "Enter the code from your phone" when a pairing request is held.
|
||||||
|
owner_code: Option<Pin>,
|
||||||
|
launched: Option<LaunchRequest>,
|
||||||
|
rng: SeqRng,
|
||||||
|
now: Instant,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl LumenHttp {
|
||||||
|
fn new(seed: u64) -> Self {
|
||||||
|
Self {
|
||||||
|
identity: host_identity(),
|
||||||
|
info: HostInfo {
|
||||||
|
hostname: "Lumen test host".into(),
|
||||||
|
app_version: "7.1.431.-1".into(),
|
||||||
|
gfe_version: "3.23.0.74".into(),
|
||||||
|
unique_id: "LUMEN-TEST-HOST-1".into(),
|
||||||
|
https_port: 47984,
|
||||||
|
http_port: 47989,
|
||||||
|
mac: Some([0x02, 0, 0x5e, 0x10, 0x20, 0x30]),
|
||||||
|
local_ip: HOST_ADDR.into(),
|
||||||
|
max_luma_pixels_hevc: 1_869_449_984,
|
||||||
|
codec_mode_support: 0x0101,
|
||||||
|
current_game: 0,
|
||||||
|
state_prefix: "LUMEN".into(),
|
||||||
|
},
|
||||||
|
apps: vec![
|
||||||
|
App { id: 1, title: "Desktop".into(), hdr_supported: false },
|
||||||
|
App { id: 881_100, title: "Hollow & <Knight>".into(), hdr_supported: false },
|
||||||
|
App { id: 4_000_000_000, title: "Forza Horizon 5".into(), hdr_supported: true },
|
||||||
|
],
|
||||||
|
paired: Vec::new(),
|
||||||
|
pairing: None,
|
||||||
|
owner_code: None,
|
||||||
|
launched: None,
|
||||||
|
rng: SeqRng::new(seed),
|
||||||
|
now: Instant::ZERO,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn is_paired(&self, cert_der: &[u8]) -> bool {
|
||||||
|
self.paired.iter().any(|p| p.matches(cert_der).unwrap())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One GET: the head through the host's strict parser, the answer from the host's XML writers. HTTPS routes other
|
||||||
|
/// than `/pair` and `/serverinfo` need a paired certificate (refused with status 401 otherwise).
|
||||||
|
fn serve(&mut self, request: &HttpRequest, transport: Transport<'_>) -> Vec<u8> {
|
||||||
|
self.now = self.now.saturating_add(Duration::from_millis(40));
|
||||||
|
let head = format!("GET {} HTTP/1.1\r\nHost: {HOST_ADDR}\r\n\r\n", request.path_and_query);
|
||||||
|
let parsed = parse_request_head(head.as_bytes()).expect("the host parses every request our client builds");
|
||||||
|
assert_eq!(parsed.unique_id.as_deref(), Some(UID));
|
||||||
|
// The host reads every parameter our client sends, except `updateState=1` on `/pair` (U1: whether a host
|
||||||
|
// needs it is unknown; Lumen's parser keeps it for the logs and does not need it).
|
||||||
|
let unread: Vec<&str> = parsed.other_params.iter().map(|(name, _)| name.as_str()).collect();
|
||||||
|
let allowed: &[&str] = if matches!(parsed.route, Route::Pair(_)) { &["updateState"] } else { &[] };
|
||||||
|
assert_eq!(unread, allowed, "parameters the host does not read");
|
||||||
|
let paired = match transport {
|
||||||
|
Transport::Https { client_cert_der } => self.is_paired(client_cert_der),
|
||||||
|
Transport::Http => false,
|
||||||
|
};
|
||||||
|
match parsed.route {
|
||||||
|
Route::ServerInfo => server_info_xml(&self.info, transport.scheme(), paired).unwrap(),
|
||||||
|
Route::Pair(p) => self.pair(&p, transport),
|
||||||
|
_ if !paired => error_xml(401, "This device is not paired with Arena Domi").unwrap(),
|
||||||
|
Route::AppList => app_list_xml(&self.apps).unwrap(),
|
||||||
|
Route::Launch(l) => {
|
||||||
|
self.info.current_game = l.app_id;
|
||||||
|
self.launched = Some(l);
|
||||||
|
launch_xml(HOST_ADDR, RTSP_PORT).unwrap()
|
||||||
|
}
|
||||||
|
Route::Cancel => {
|
||||||
|
self.info.current_game = 0;
|
||||||
|
ok_xml()
|
||||||
|
}
|
||||||
|
other => panic!("the session test does not use {other:?}"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `/pair`: phase 1 opens a new attempt and is held until the owner types the code.
|
||||||
|
fn pair(&mut self, request: &PairRequest, transport: Transport<'_>) -> Vec<u8> {
|
||||||
|
if matches!(request.phase, PairPhase::GetServerCert { .. }) {
|
||||||
|
self.pairing = Some(HostPairingSession::new(&self.identity, HostPairingConfig::default(), self.now));
|
||||||
|
}
|
||||||
|
let Some(session) = self.pairing.as_mut() else { return pair_answer_xml(&PairAnswer::Refused).unwrap() };
|
||||||
|
let answer = match session.handle(&self.identity, request, transport, self.now, &mut self.rng) {
|
||||||
|
Ok(HostPairingStep::Answer(a)) => a,
|
||||||
|
Ok(HostPairingStep::HoldForPin) => {
|
||||||
|
let code = self.owner_code.take().expect("the owner has the phone's code to type");
|
||||||
|
self.now = self.now.saturating_add(Duration::from_secs(4));
|
||||||
|
session.supply_pin(&self.identity, code, self.now).unwrap_or(PairAnswer::Refused)
|
||||||
|
}
|
||||||
|
Ok(HostPairingStep::Paired(client)) => {
|
||||||
|
self.paired.push(client);
|
||||||
|
PairAnswer::Paired
|
||||||
|
}
|
||||||
|
Err(_) => PairAnswer::Refused,
|
||||||
|
};
|
||||||
|
pair_answer_xml(&answer).unwrap()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The client's HTTP(S) call. Over HTTPS the client presents its certificate and pins the host's: the TLS stack's
|
||||||
|
/// job in the app (PROTOCOL.md 1.1), an explicit check here.
|
||||||
|
fn get(host: &mut LumenHttp, request: &HttpRequest, client: &ClientIdentity, pinned: Option<&ServerCert>) -> Vec<u8> {
|
||||||
|
match request.scheme {
|
||||||
|
Scheme::Http => host.serve(request, Transport::Http),
|
||||||
|
Scheme::Https => {
|
||||||
|
let pin = pinned.expect("HTTPS only with a pinned host certificate");
|
||||||
|
assert_eq!(
|
||||||
|
pin.matches(host.identity.cert_der()),
|
||||||
|
Ok(true),
|
||||||
|
"TLS: the host presents the pinned certificate"
|
||||||
|
);
|
||||||
|
host.serve(request, Transport::Https { client_cert_der: client.cert_der() })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Pairs `client` with `host`: the phone makes the code, the owner types it on the PC (`docs/LUMEN-HOST-PLAN.md`
|
||||||
|
/// 1.9). The client pins the phase-1 `plaincert` for the HTTPS phase 5.
|
||||||
|
fn pair(host: &mut LumenHttp, client: &ClientIdentity, rng: &mut SeqRng) -> PairedHost {
|
||||||
|
let code = Pin::generate(rng).unwrap();
|
||||||
|
host.owner_code = Some(code);
|
||||||
|
let (mut session, mut request) = PairingSession::start(client, UID, DEVICE, code, rng).unwrap();
|
||||||
|
let mut plaincert: Option<ServerCert> = None;
|
||||||
|
for _ in 0..5 {
|
||||||
|
let body = get(host, &request, client, plaincert.as_ref());
|
||||||
|
if plaincert.is_none() {
|
||||||
|
let pem = parse_pair_response(&body).unwrap().plain_cert.expect("phase 1 carries plaincert");
|
||||||
|
plaincert = Some(ServerCert::from_pem(&pem).unwrap());
|
||||||
|
}
|
||||||
|
match session.handle_response(client, 200, &body, rng).expect("every phase passes") {
|
||||||
|
PairingStep::Send(next) => request = next,
|
||||||
|
PairingStep::Paired(paired) => return paired,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
panic!("pairing did not finish in five round trips");
|
||||||
|
}
|
||||||
|
|
||||||
|
// ================================================================================================ RTSP
|
||||||
|
|
||||||
|
fn client_stream_config() -> ClientStreamConfig {
|
||||||
|
ClientStreamConfig {
|
||||||
|
width: 1920,
|
||||||
|
height: 1080,
|
||||||
|
fps: 60,
|
||||||
|
bitrate_kbps: 20_000,
|
||||||
|
packet_size: 1024,
|
||||||
|
codec: VideoCodec::Hevc,
|
||||||
|
hdr: false,
|
||||||
|
audio: AudioLayout::Stereo,
|
||||||
|
audio_packet_duration_ms: 5,
|
||||||
|
min_fec_packets: 2,
|
||||||
|
reference_frame_invalidation: true,
|
||||||
|
encryption: EncryptionFlags(ALL),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn rtsp_server_config() -> ServerConfig {
|
||||||
|
ServerConfig {
|
||||||
|
ports: PORTS,
|
||||||
|
offer: HostOffer {
|
||||||
|
feature_flags: FeatureFlags(3),
|
||||||
|
encryption_supported: EncryptionFlags(ALL),
|
||||||
|
reference_frame_invalidation: true,
|
||||||
|
h264: true,
|
||||||
|
hevc: true,
|
||||||
|
av1: false,
|
||||||
|
hdr: false,
|
||||||
|
yuv444: false,
|
||||||
|
opus_configs: vec![parse_surround_params("21101").unwrap()],
|
||||||
|
},
|
||||||
|
required_encryption: EncryptionFlags(EncryptionFlags::CONTROL_V2),
|
||||||
|
// Our client echoes the SETUP session id, so the strict setting holds.
|
||||||
|
require_session_header: true,
|
||||||
|
session_timeout_secs: DEFAULT_SESSION_TIMEOUT_SECS,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What the host must read from our client's ANNOUNCE for `c` (the attributes `rtsp::sdp::build_announce` writes).
|
||||||
|
fn announced_by(c: &ClientStreamConfig, enabled: EncryptionFlags) -> HostStreamConfig {
|
||||||
|
let channels = c.audio.channels();
|
||||||
|
HostStreamConfig {
|
||||||
|
width: c.width,
|
||||||
|
height: c.height,
|
||||||
|
max_fps: c.fps,
|
||||||
|
packet_size: c.packet_size,
|
||||||
|
bitrate_kbps: c.bitrate_kbps,
|
||||||
|
codec: c.codec,
|
||||||
|
min_fec_packets: c.min_fec_packets,
|
||||||
|
video_qos_traffic_type: 5,
|
||||||
|
audio_packet_duration_ms: c.audio_packet_duration_ms,
|
||||||
|
audio_qos_traffic_type: 4,
|
||||||
|
max_reference_frames: if c.reference_frame_invalidation { 0 } else { 1 },
|
||||||
|
reference_frame_invalidation: c.reference_frame_invalidation,
|
||||||
|
dynamic_range_mode: u32::from(c.hdr),
|
||||||
|
encoder_csc_mode: if c.hdr { 5 } else { 0 },
|
||||||
|
chroma: ChromaSampling::Yuv420,
|
||||||
|
encryption: enabled,
|
||||||
|
surround: SurroundSettings {
|
||||||
|
enabled: channels > 2,
|
||||||
|
channels,
|
||||||
|
channel_mask: c.audio.channel_mask(),
|
||||||
|
high_quality: true,
|
||||||
|
},
|
||||||
|
unknown_attributes: 0,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// OPTIONS … PLAY, one TCP connection per request (PROTOCOL.md 2.5), bytes cut 7 at a time by both framers.
|
||||||
|
fn negotiate(
|
||||||
|
session_url: &str,
|
||||||
|
config: ClientStreamConfig,
|
||||||
|
server: &mut RtspServer,
|
||||||
|
) -> (NegotiatedStream, Vec<ServerEvent>) {
|
||||||
|
let mut client = RtspClient::new(session_url, config).unwrap();
|
||||||
|
let mut events = Vec::new();
|
||||||
|
for _ in 0..7 {
|
||||||
|
let request = client.poll_request().expect("the client has its next request");
|
||||||
|
let mut to_server = RtspFramer::for_requests();
|
||||||
|
let mut replies = Vec::new();
|
||||||
|
for piece in request.chunks(7) {
|
||||||
|
to_server.push(piece).unwrap();
|
||||||
|
while let Some(message) = to_server.next_message().unwrap() {
|
||||||
|
replies.push(server.handle_request(&message));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
assert_eq!(replies.len(), 1, "one request, one answer");
|
||||||
|
assert_eq!(replies[0].status, 200, "{:?}", replies[0].error);
|
||||||
|
events.extend(core::iter::from_fn(|| server.poll_event()));
|
||||||
|
let mut to_client = RtspFramer::new();
|
||||||
|
let mut answers = Vec::new();
|
||||||
|
for piece in replies[0].bytes.chunks(7) {
|
||||||
|
to_client.push(piece).unwrap();
|
||||||
|
answers.extend(to_client.next_message().unwrap());
|
||||||
|
}
|
||||||
|
assert_eq!(answers.len(), 1, "the answer is framed by Content-Length");
|
||||||
|
if let RtspProgress::Ready(n) = client.handle_response(&answers[0]).unwrap() {
|
||||||
|
return (n, events);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
panic!("RTSP never finished");
|
||||||
|
}
|
||||||
|
|
||||||
|
// ================================================================================================ control
|
||||||
|
|
||||||
|
/// The client's control stream, probe-style (see the top of this file).
|
||||||
|
struct ClientControl {
|
||||||
|
enet: EnetClient,
|
||||||
|
cipher: ControlCipher,
|
||||||
|
next_sequence: u32,
|
||||||
|
last_host_sequence: Option<u32>,
|
||||||
|
host_messages: Vec<HostMessage>,
|
||||||
|
enet_events: Vec<EnetEvent>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ClientControl {
|
||||||
|
fn connect(rikey: [u8; 16], rng: &mut SeqRng) -> Self {
|
||||||
|
let config = EnetConfig {
|
||||||
|
channel_count: 1,
|
||||||
|
mtu: 1392,
|
||||||
|
connect_data: 0,
|
||||||
|
ping_interval: Duration::from_millis(500),
|
||||||
|
timeout: Duration::from_secs(10),
|
||||||
|
};
|
||||||
|
Self {
|
||||||
|
enet: EnetClient::connect(config, Instant::ZERO, rng).unwrap(),
|
||||||
|
cipher: ControlCipher::new(rikey),
|
||||||
|
next_sequence: 0,
|
||||||
|
last_host_sequence: None,
|
||||||
|
host_messages: Vec::new(),
|
||||||
|
enet_events: Vec::new(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn send_plain(&mut self, now: Instant, plain: &[u8]) {
|
||||||
|
let frame = self.cipher.seal(self.next_sequence, Direction::ClientToHost, plain).unwrap();
|
||||||
|
self.enet.send(now, 0, Delivery::Reliable, &frame).unwrap();
|
||||||
|
self.next_sequence += 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
fn send(&mut self, now: Instant, message: &ClientMessage) {
|
||||||
|
self.send_plain(now, &encode_client_message(message).unwrap());
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A message with an empty body: START_B, PERIODIC_PING, IDR request (PROTOCOL.md 3.3).
|
||||||
|
fn send_empty(&mut self, now: Instant, message_type: MessageType) {
|
||||||
|
let mut plain = (message_type as u16).to_le_bytes().to_vec();
|
||||||
|
plain.extend_from_slice(&0u16.to_le_bytes());
|
||||||
|
self.send_plain(now, &plain);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn drain(&mut self) {
|
||||||
|
while let Some(event) = self.enet.poll_event() {
|
||||||
|
match event {
|
||||||
|
EnetEvent::Received { data, .. } => {
|
||||||
|
let (sequence, plain) = self.cipher.open(Direction::HostToClient, &data).expect("host frames open");
|
||||||
|
assert!(self.last_host_sequence.is_none_or(|last| sequence > last), "host sequence goes up");
|
||||||
|
self.last_host_sequence = Some(sequence);
|
||||||
|
self.host_messages.push(parse_host_message(&plain).expect("the client reads every host message"));
|
||||||
|
}
|
||||||
|
other => self.enet_events.push(other),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Endpoint for ClientControl {
|
||||||
|
fn transmit(&mut self, now: Instant) -> Option<Vec<u8>> {
|
||||||
|
self.enet.poll_transmit(now)
|
||||||
|
}
|
||||||
|
fn receive(&mut self, now: Instant, datagram: &[u8]) {
|
||||||
|
let _ = self.enet.handle_datagram(now, datagram);
|
||||||
|
self.drain();
|
||||||
|
}
|
||||||
|
fn deadline(&self) -> Option<Instant> {
|
||||||
|
self.enet.poll_timeout()
|
||||||
|
}
|
||||||
|
fn tick(&mut self, now: Instant) {
|
||||||
|
self.enet.handle_timeout(now).unwrap();
|
||||||
|
self.drain();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Lumen's control listener for this client's address: the first datagram must be the CONNECT.
|
||||||
|
struct HostControl {
|
||||||
|
config: ControlHostConfig,
|
||||||
|
host: Option<ControlHost>,
|
||||||
|
events: Vec<ControlHostEvent>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl HostControl {
|
||||||
|
fn h(&mut self) -> &mut ControlHost {
|
||||||
|
self.host.as_mut().expect("accepted")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn messages(&self) -> Vec<ClientControlMessage> {
|
||||||
|
self.events
|
||||||
|
.iter()
|
||||||
|
.filter_map(|e| match e {
|
||||||
|
ControlHostEvent::Message(m) => Some(m.clone()),
|
||||||
|
_ => None,
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn drain(&mut self) {
|
||||||
|
if let Some(h) = self.host.as_mut() {
|
||||||
|
self.events.extend(core::iter::from_fn(|| h.poll_event()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Endpoint for HostControl {
|
||||||
|
fn transmit(&mut self, now: Instant) -> Option<Vec<u8>> {
|
||||||
|
self.host.as_mut()?.poll_transmit(now)
|
||||||
|
}
|
||||||
|
fn receive(&mut self, now: Instant, datagram: &[u8]) {
|
||||||
|
match self.host.as_mut() {
|
||||||
|
None => self.host = ControlHost::accept(self.config.clone(), now, datagram).ok(),
|
||||||
|
Some(h) => {
|
||||||
|
let _ = h.handle_datagram(now, datagram);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
self.drain();
|
||||||
|
}
|
||||||
|
fn deadline(&self) -> Option<Instant> {
|
||||||
|
self.host.as_ref()?.poll_timeout()
|
||||||
|
}
|
||||||
|
fn tick(&mut self, now: Instant) {
|
||||||
|
if let Some(h) = self.host.as_mut() {
|
||||||
|
h.handle_timeout(now).unwrap();
|
||||||
|
}
|
||||||
|
self.drain();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type Control = Wire<ClientControl, HostControl>;
|
||||||
|
|
||||||
|
/// Runs the control wire until the host has seen `n` messages; returns the new ones.
|
||||||
|
fn host_receives(w: &mut Control, n: usize) -> Vec<ClientControlMessage> {
|
||||||
|
let before = w.host.messages().len();
|
||||||
|
assert!(w.run_until(w.now_ms + 10_000, |w| w.host.messages().len() >= before + n), "the host never got them");
|
||||||
|
w.host.messages()[before..].to_vec()
|
||||||
|
}
|
||||||
|
|
||||||
|
// ================================================================================================ media
|
||||||
|
|
||||||
|
/// A synthetic HEVC access unit of exactly `len` bytes (at least 6): start code, a NAL header (IDR_W_RADL for a key
|
||||||
|
/// frame, TRAIL_R otherwise), random payload.
|
||||||
|
fn access_unit(rng: &mut SeqRng, len: usize, key: bool) -> Vec<u8> {
|
||||||
|
let mut au = vec![0, 0, 0, 1, if key { 0x26 } else { 0x02 }, 0x01];
|
||||||
|
au.extend(rng.bytes(len - 6));
|
||||||
|
au
|
||||||
|
}
|
||||||
|
|
||||||
|
/// How the lossy link treats one FEC block: the indices (data first, then parity) it drops.
|
||||||
|
type LossPlan<'a> = &'a mut dyn FnMut(&FecBlock, &mut SeqRng) -> Vec<usize>;
|
||||||
|
|
||||||
|
/// The worst loss FEC still repairs: exactly `m` of the block's `k + m` datagrams, at least one of them data.
|
||||||
|
fn within_budget(b: &FecBlock, rng: &mut SeqRng) -> Vec<usize> {
|
||||||
|
let (k, m) = (usize::from(b.data_shards), usize::from(b.parity_shards));
|
||||||
|
let mut lost = rng.subset(k + m, m);
|
||||||
|
if !lost.is_empty() && lost.iter().all(|&i| i >= k) {
|
||||||
|
lost[0] = rng.below(k);
|
||||||
|
}
|
||||||
|
lost
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Sends one frame over the link: drops what `loss` picks per block, duplicates one survivor, shuffles the rest.
|
||||||
|
/// Returns the data shards lost (what FEC must rebuild) and the duplicates sent.
|
||||||
|
fn send_frame(
|
||||||
|
packetizer: &mut VideoPacketizer,
|
||||||
|
receiver: &mut VideoDepacketizer,
|
||||||
|
frame: &EncodedFrame<'_>,
|
||||||
|
min_parity: u8,
|
||||||
|
loss: LossPlan<'_>,
|
||||||
|
rng: &mut SeqRng,
|
||||||
|
now: Instant,
|
||||||
|
) -> (usize, usize) {
|
||||||
|
let packets = packetizer.packetize(frame).unwrap();
|
||||||
|
let payload = usize::from(client_stream_config().packet_size) - 16;
|
||||||
|
let shards = (FRAME_HEADER_LEN + frame.bitstream.len()).div_ceil(payload);
|
||||||
|
let plan = plan_fec_blocks(shards, FEC_PERCENT, min_parity).unwrap();
|
||||||
|
assert_eq!(plan.iter().map(|b| usize::from(b.data_shards + b.parity_shards)).sum::<usize>(), packets.len());
|
||||||
|
let mut survivors = Vec::new();
|
||||||
|
let mut data_lost = 0;
|
||||||
|
let mut start = 0;
|
||||||
|
for block in &plan {
|
||||||
|
let size = usize::from(block.data_shards + block.parity_shards);
|
||||||
|
let lost = loss(block, rng);
|
||||||
|
data_lost += lost.iter().filter(|&&i| i < usize::from(block.data_shards)).count();
|
||||||
|
survivors.extend((0..size).filter(|i| !lost.contains(i)).map(|i| packets[start + i].clone()));
|
||||||
|
start += size;
|
||||||
|
}
|
||||||
|
let duplicate = survivors[rng.below(survivors.len())].clone();
|
||||||
|
survivors.push(duplicate);
|
||||||
|
rng.shuffle(&mut survivors);
|
||||||
|
for datagram in &survivors {
|
||||||
|
receiver.push(now, datagram).unwrap();
|
||||||
|
}
|
||||||
|
(data_lost, 1)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn video_events(receiver: &mut VideoDepacketizer, now: Instant, out: &mut Vec<VideoEvent>) {
|
||||||
|
if receiver.poll_timeout().is_some_and(|t| t <= now) {
|
||||||
|
receiver.handle_timeout(now).unwrap();
|
||||||
|
}
|
||||||
|
out.extend(core::iter::from_fn(|| receiver.poll_event()));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ================================================================================================ the session
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_whole_session_between_our_client_and_our_host() {
|
||||||
|
let mut rng = SeqRng::new(0x5E55_1011);
|
||||||
|
let client = client_identity("client");
|
||||||
|
let mut host = LumenHttp::new(0x1u64 << 40);
|
||||||
|
|
||||||
|
// serverinfo over HTTP: the host is there, this client is not paired.
|
||||||
|
let info: ServerInfo =
|
||||||
|
parse_server_info(&get(&mut host, &server_info_request(Scheme::Http, UID).unwrap(), &client, None)).unwrap();
|
||||||
|
assert_eq!((info.hostname.as_str(), info.unique_id.as_str()), ("Lumen test host", "LUMEN-TEST-HOST-1"));
|
||||||
|
assert_eq!((info.https_port, info.http_port, info.mac), (47984, Some(47989), host.info.mac));
|
||||||
|
assert_eq!((info.paired, info.current_game, info.state.as_str()), (false, 0, "LUMEN_SERVER_FREE"));
|
||||||
|
|
||||||
|
// Pairing: the owner types the phone's code; the client pins exactly the host's certificate, the host
|
||||||
|
// authorizes exactly the client's.
|
||||||
|
let paired = pair(&mut host, &client, &mut rng);
|
||||||
|
assert_eq!(paired.server_cert.der(), host.identity.cert_der());
|
||||||
|
assert_eq!(host.paired.len(), 1);
|
||||||
|
assert_eq!(host.paired[0].cert_der, client.cert_der());
|
||||||
|
assert_eq!((host.paired[0].unique_id.as_deref(), host.paired[0].device_name.as_deref()), (Some(UID), Some(DEVICE)));
|
||||||
|
let pin = Some(&paired.server_cert);
|
||||||
|
|
||||||
|
// serverinfo over HTTPS: PairStatus 1. Then the app list, byte for byte as the host holds it.
|
||||||
|
let info =
|
||||||
|
parse_server_info(&get(&mut host, &server_info_request(Scheme::Https, UID).unwrap(), &client, pin)).unwrap();
|
||||||
|
assert!(info.paired, "PairStatus 1 over HTTPS with the paired certificate");
|
||||||
|
let apps = parse_app_list(&get(&mut host, &app_list_request(UID).unwrap(), &client, pin)).unwrap();
|
||||||
|
assert_eq!(apps, host.apps);
|
||||||
|
|
||||||
|
// launch: the session keys reach the host unchanged.
|
||||||
|
let keys = SessionKeys::generate(&mut rng).unwrap();
|
||||||
|
let params = LaunchParams {
|
||||||
|
app_id: apps[2].id,
|
||||||
|
width: 1920,
|
||||||
|
height: 1080,
|
||||||
|
fps: 60,
|
||||||
|
keys: keys.clone(),
|
||||||
|
hdr: false,
|
||||||
|
audio: AudioLayout::Stereo,
|
||||||
|
};
|
||||||
|
let launch = parse_launch_response(&get(&mut host, &launch_request(¶ms, UID).unwrap(), &client, pin)).unwrap();
|
||||||
|
assert!(launch.game_session);
|
||||||
|
let session_url = launch.session_url.expect("sessionUrl0");
|
||||||
|
assert_eq!(session_url, format!("rtsp://{HOST_ADDR}:{RTSP_PORT}"));
|
||||||
|
let launched = host.launched.clone().expect("the host took the launch");
|
||||||
|
assert_eq!(launched.keys, keys);
|
||||||
|
assert_eq!(
|
||||||
|
(launched.app_id, launched.mode.width, launched.mode.height, launched.mode.fps),
|
||||||
|
(4_000_000_000, 1920, 1080, 60)
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
(launched.hdr, launched.surround_audio_info),
|
||||||
|
(Some(false), Some(AudioLayout::Stereo.surround_audio_info()))
|
||||||
|
);
|
||||||
|
assert_eq!(host.info.current_game, 4_000_000_000);
|
||||||
|
|
||||||
|
// RTSP: the host's stream config is exactly what the client announced.
|
||||||
|
let mut rtsp = RtspServer::new(rtsp_server_config(), &mut rng).unwrap();
|
||||||
|
let (negotiated, events) = negotiate(&session_url, client_stream_config(), &mut rtsp);
|
||||||
|
assert_eq!(negotiated.ports, PORTS);
|
||||||
|
assert_eq!(negotiated.encryption, EncryptionFlags(ALL));
|
||||||
|
assert_eq!(negotiated.session_id.as_deref(), Some(rtsp.session_id()));
|
||||||
|
assert_eq!(negotiated.opus, parse_surround_params("21101").unwrap());
|
||||||
|
assert!(negotiated.host.reference_frame_invalidation);
|
||||||
|
assert_eq!(negotiated.ping_payload, PING_PAYLOAD, "the PING the host's media listeners wait for");
|
||||||
|
let announced = announced_by(&client_stream_config(), negotiated.encryption);
|
||||||
|
assert_eq!(events, vec![ServerEvent::Announced(announced.clone()), ServerEvent::PlayRequested]);
|
||||||
|
assert_eq!(rtsp.announced(), Some(&announced));
|
||||||
|
assert_eq!(
|
||||||
|
(announced.width, announced.height, announced.max_fps),
|
||||||
|
(launched.mode.width, launched.mode.height, launched.mode.fps)
|
||||||
|
);
|
||||||
|
|
||||||
|
// ENet connect on the control port, then START_B. ControlStream refuses START_B (body U10), hence the probe path.
|
||||||
|
assert_err!(encode_client_message(&ClientMessage::StartB), Error::Unsupported { .. });
|
||||||
|
let host_control = HostControl {
|
||||||
|
config: ControlHostConfig {
|
||||||
|
enet: EnetHostConfig {
|
||||||
|
peer_id: 0,
|
||||||
|
channel_limit: 0x30,
|
||||||
|
mtu: 1392,
|
||||||
|
ping_interval: Duration::from_millis(500),
|
||||||
|
timeout: Duration::from_secs(10),
|
||||||
|
},
|
||||||
|
rikey: launched.keys.rikey,
|
||||||
|
stop_timeout: Some(DEFAULT_STOP_TIMEOUT),
|
||||||
|
},
|
||||||
|
host: None,
|
||||||
|
events: Vec::new(),
|
||||||
|
};
|
||||||
|
let mut w: Control = Wire::new(
|
||||||
|
ClientControl::connect(keys.rikey, &mut rng),
|
||||||
|
host_control,
|
||||||
|
Impair::lossy(30, 5),
|
||||||
|
Impair::lossy(30, 5),
|
||||||
|
77,
|
||||||
|
);
|
||||||
|
assert!(w.run_until(10_000, |w| w.client.enet.state() == EnetState::Connected
|
||||||
|
&& w.host.host.as_ref().is_some_and(|h| h.enet().state() == EnetHostState::Connected)));
|
||||||
|
assert_eq!(w.client.enet_events, vec![EnetEvent::Connected]);
|
||||||
|
assert_eq!(w.host.events, vec![ControlHostEvent::Connected]);
|
||||||
|
let t = at(w.now_ms);
|
||||||
|
w.client.send_empty(t, MessageType::StartB);
|
||||||
|
assert_eq!(host_receives(&mut w, 1), vec![ClientControlMessage::StartB]);
|
||||||
|
|
||||||
|
// A PERIODIC_PING moves the host's stop deadline out (a ControlStream client never sends one: U10).
|
||||||
|
let deadline = w.host.h().stop_deadline().expect("the stop clock runs");
|
||||||
|
w.run_for(1_000);
|
||||||
|
let t = at(w.now_ms);
|
||||||
|
w.client.send_empty(t, MessageType::PeriodicPing);
|
||||||
|
assert_eq!(host_receives(&mut w, 1), vec![ClientControlMessage::PeriodicPing]);
|
||||||
|
assert!(w.host.h().stop_deadline().unwrap() > deadline);
|
||||||
|
|
||||||
|
// Video: the packet size and minimum parity the client announced, sealed with the session key.
|
||||||
|
let mut packetizer = VideoPacketizer::new(VideoPacketizerConfig {
|
||||||
|
packet_size: announced.packet_size,
|
||||||
|
fec_percentage: FEC_PERCENT,
|
||||||
|
min_required_fec_packets: announced.min_fec_packets,
|
||||||
|
cipher: announced.encryption.contains(EncryptionFlags::VIDEO).then(|| VideoCipher::new(launched.keys.rikey)),
|
||||||
|
first_sequence: 0xFFF0, // the RTP sequence wraps inside the first frame
|
||||||
|
})
|
||||||
|
.unwrap();
|
||||||
|
let mut receiver = VideoDepacketizer::new(VideoConfig {
|
||||||
|
packet_size: client_stream_config().packet_size,
|
||||||
|
cipher: negotiated.encryption.contains(EncryptionFlags::VIDEO).then(|| VideoCipher::new(keys.rikey)),
|
||||||
|
frame_timeout: Duration::from_millis(60),
|
||||||
|
})
|
||||||
|
.unwrap();
|
||||||
|
// A large IDR (two FEC blocks), sizes at and around one shard, then varied P-frames; frame 12 loses a burst.
|
||||||
|
let mut sizes = vec![400_000, 6, 1_000, 1_001, 2_016, 3_000, 25_000, 60_000, 12_345, 1_500, 90_000];
|
||||||
|
sizes.extend((0..14).map(|_| 500 + rng.below(40_000)));
|
||||||
|
const BURST: u32 = 12;
|
||||||
|
let mut sent: Vec<(u32, FrameType, Vec<u8>)> = Vec::new();
|
||||||
|
let mut video = Vec::new();
|
||||||
|
let (mut rebuilt, mut duplicates) = (0, 0);
|
||||||
|
for (i, &len) in sizes.iter().enumerate() {
|
||||||
|
let index = i as u32;
|
||||||
|
let frame_type = if index == 0 { FrameType::Key } else { FrameType::Predicted };
|
||||||
|
let bitstream = access_unit(&mut rng, len, index == 0);
|
||||||
|
let frame = EncodedFrame {
|
||||||
|
frame_index: index,
|
||||||
|
frame_type,
|
||||||
|
rtp_timestamp: index.wrapping_mul(1500),
|
||||||
|
processing_latency: 20,
|
||||||
|
bitstream: &bitstream,
|
||||||
|
};
|
||||||
|
let now = at(w.now_ms);
|
||||||
|
let mut burst = |b: &FecBlock, rng: &mut SeqRng| {
|
||||||
|
rng.subset(usize::from(b.data_shards + b.parity_shards), usize::from(b.parity_shards) + 1)
|
||||||
|
};
|
||||||
|
let mut fine = within_budget;
|
||||||
|
let loss: LossPlan<'_> = if index == BURST { &mut burst } else { &mut fine };
|
||||||
|
let (lost, dups) =
|
||||||
|
send_frame(&mut packetizer, &mut receiver, &frame, announced.min_fec_packets, loss, &mut rng, now);
|
||||||
|
if index != BURST {
|
||||||
|
rebuilt += lost;
|
||||||
|
}
|
||||||
|
duplicates += dups;
|
||||||
|
sent.push((index, frame_type, bitstream));
|
||||||
|
w.run_for(16);
|
||||||
|
video_events(&mut receiver, at(w.now_ms), &mut video);
|
||||||
|
}
|
||||||
|
w.run_for(200);
|
||||||
|
video_events(&mut receiver, at(w.now_ms), &mut video);
|
||||||
|
|
||||||
|
// Every frame but the burst comes out byte-identical and in order; the burst is reported lost.
|
||||||
|
let lost: Vec<(u32, u32)> = video
|
||||||
|
.iter()
|
||||||
|
.filter_map(|e| if let VideoEvent::FrameLost { first, last } = e { Some((*first, *last)) } else { None })
|
||||||
|
.collect();
|
||||||
|
assert_eq!(lost, vec![(BURST, BURST)]);
|
||||||
|
let frames: Vec<_> =
|
||||||
|
video.iter().filter_map(|e| if let VideoEvent::Frame(f) = e { Some(f) } else { None }).collect();
|
||||||
|
let expected: Vec<_> = sent.iter().filter(|(i, _, _)| *i != BURST).collect();
|
||||||
|
assert_eq!(frames.len(), expected.len());
|
||||||
|
for (got, (index, frame_type, bitstream)) in frames.iter().zip(expected) {
|
||||||
|
assert_eq!(got.frame_index, *index);
|
||||||
|
assert_eq!(got.header.frame_type, *frame_type, "frame {index}");
|
||||||
|
assert_eq!(got.header.processing_latency, 20);
|
||||||
|
assert_eq!(got.rtp_timestamp, index.wrapping_mul(1500));
|
||||||
|
assert!(got.bitstream == *bitstream, "frame {index}: the bitstream differs");
|
||||||
|
}
|
||||||
|
let stats = receiver.stats();
|
||||||
|
assert!(rebuilt > 0);
|
||||||
|
assert_eq!(stats.shards_recovered, rebuilt as u64, "FEC rebuilt every data shard lost within the budget");
|
||||||
|
assert_eq!((stats.frames, stats.frames_lost, stats.packets_dropped), (frames.len() as u64, 1, duplicates as u64));
|
||||||
|
|
||||||
|
// The client asks for recovery over control: reference invalidation (the host offered it), and an IDR request
|
||||||
|
// (empty body, as above). The host sees both, then sends a recovery frame.
|
||||||
|
let t = at(w.now_ms);
|
||||||
|
w.client.send(t, &ClientMessage::InvalidateRefFrames { first: BURST, last: BURST });
|
||||||
|
w.client.send_empty(t, MessageType::IdrFrame);
|
||||||
|
assert_eq!(
|
||||||
|
host_receives(&mut w, 2),
|
||||||
|
vec![ClientControlMessage::InvalidateRefFrames { first: BURST, last: BURST }, ClientControlMessage::IdrRequest]
|
||||||
|
);
|
||||||
|
let index = sizes.len() as u32;
|
||||||
|
let bitstream = access_unit(&mut rng, 30_000, false);
|
||||||
|
let recovery = EncodedFrame {
|
||||||
|
frame_index: index,
|
||||||
|
frame_type: FrameType::Recovery,
|
||||||
|
rtp_timestamp: index * 1500,
|
||||||
|
processing_latency: 20,
|
||||||
|
bitstream: &bitstream,
|
||||||
|
};
|
||||||
|
send_frame(
|
||||||
|
&mut packetizer,
|
||||||
|
&mut receiver,
|
||||||
|
&recovery,
|
||||||
|
announced.min_fec_packets,
|
||||||
|
&mut within_budget,
|
||||||
|
&mut rng,
|
||||||
|
at(w.now_ms),
|
||||||
|
);
|
||||||
|
let mut after = Vec::new();
|
||||||
|
video_events(&mut receiver, at(w.now_ms), &mut after);
|
||||||
|
match after.as_slice() {
|
||||||
|
[VideoEvent::Frame(f)] => {
|
||||||
|
assert_eq!((f.frame_index, f.header.frame_type), (index, FrameType::Recovery));
|
||||||
|
assert!(f.bitstream == bitstream);
|
||||||
|
}
|
||||||
|
other => panic!("expected the recovery frame, got {other:?}"),
|
||||||
|
}
|
||||||
|
|
||||||
|
// Audio: Opus-sized packets sealed with the session keys; no parity, so lost packets come out as lost.
|
||||||
|
let mut audio_tx = AudioPacketizer::new(AudioPacketizerConfig {
|
||||||
|
cipher: announced.encryption.contains(EncryptionFlags::AUDIO).then(|| AudioCipher::new(&launched.keys)),
|
||||||
|
packet_duration_ms: announced.audio_packet_duration_ms,
|
||||||
|
parity: AudioParity::None,
|
||||||
|
first_sequence: 0,
|
||||||
|
first_timestamp_ms: 0,
|
||||||
|
})
|
||||||
|
.unwrap();
|
||||||
|
let mut audio_rx = AudioDepacketizer::new(AudioConfig {
|
||||||
|
cipher: negotiated.encryption.contains(EncryptionFlags::AUDIO).then(|| AudioCipher::new(&keys)),
|
||||||
|
packet_duration_ms: client_stream_config().audio_packet_duration_ms,
|
||||||
|
fec: AudioFec::Disabled,
|
||||||
|
loss_timeout: Duration::from_millis(20),
|
||||||
|
})
|
||||||
|
.unwrap();
|
||||||
|
let dropped = [6u16, 17, 18, 31];
|
||||||
|
let mut opus_sent = Vec::new();
|
||||||
|
let mut audio = Vec::new();
|
||||||
|
for sequence in 0..40u16 {
|
||||||
|
let len = 60 + rng.below(140);
|
||||||
|
let opus = rng.bytes(len);
|
||||||
|
let datagrams = audio_tx.packetize(&opus).unwrap();
|
||||||
|
assert_eq!(datagrams.len(), 1, "no parity packets (U16)");
|
||||||
|
let now = at(w.now_ms);
|
||||||
|
if !dropped.contains(&sequence) {
|
||||||
|
audio_rx.push(now, &datagrams[0]).unwrap();
|
||||||
|
}
|
||||||
|
opus_sent.push(opus);
|
||||||
|
w.run_for(5);
|
||||||
|
let now = at(w.now_ms);
|
||||||
|
if audio_rx.poll_timeout().is_some_and(|t| t <= now) {
|
||||||
|
audio_rx.handle_timeout(now).unwrap();
|
||||||
|
}
|
||||||
|
audio.extend(core::iter::from_fn(|| audio_rx.poll_event()));
|
||||||
|
}
|
||||||
|
let expected_audio: Vec<AudioEvent> = (0..40u16)
|
||||||
|
.map(|sequence| {
|
||||||
|
if dropped.contains(&sequence) {
|
||||||
|
AudioEvent::Lost { sequence }
|
||||||
|
} else {
|
||||||
|
AudioEvent::Packet {
|
||||||
|
sequence,
|
||||||
|
timestamp_ms: u32::from(sequence) * 5,
|
||||||
|
opus: opus_sent[usize::from(sequence)].clone(),
|
||||||
|
recovered: false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
assert_eq!(audio, expected_audio, "in order, losses reported, nothing rebuilt");
|
||||||
|
assert_eq!((audio_rx.stats().lost, audio_rx.stats().recovered), (dropped.len() as u64, 0));
|
||||||
|
|
||||||
|
// Input: every kind the client sends arrives typed on the host, in order.
|
||||||
|
let inputs = vec![
|
||||||
|
InputEvent::MouseMoveRel { dx: -12, dy: 7 },
|
||||||
|
InputEvent::MouseMoveAbs { x: 1464, y: 528, width: 1919, height: 1079 },
|
||||||
|
InputEvent::MouseButton { pressed: true, button: MouseButton::Left },
|
||||||
|
InputEvent::MouseButton { pressed: false, button: MouseButton::Left },
|
||||||
|
InputEvent::Key { pressed: true, flags: 0, key_code: 0x41, modifiers: 0 },
|
||||||
|
InputEvent::Key { pressed: false, flags: 0, key_code: 0x41, modifiers: 0 },
|
||||||
|
InputEvent::Scroll { amount: -120 },
|
||||||
|
InputEvent::Gamepad(GamepadState {
|
||||||
|
controller: 0,
|
||||||
|
active_mask: 1,
|
||||||
|
buttons: ButtonFlags(ButtonFlags::A | ButtonFlags::DPAD_UP | ButtonFlags::PADDLE1),
|
||||||
|
left_trigger: 0x40,
|
||||||
|
right_trigger: 0xFF,
|
||||||
|
left_stick_x: -32768,
|
||||||
|
left_stick_y: 32767,
|
||||||
|
right_stick_x: 1200,
|
||||||
|
right_stick_y: -104,
|
||||||
|
}),
|
||||||
|
];
|
||||||
|
let t = at(w.now_ms);
|
||||||
|
for e in &inputs {
|
||||||
|
w.client.send(t, &ClientMessage::Input(e.clone()));
|
||||||
|
}
|
||||||
|
let typed: Vec<ClientControlMessage> = inputs.iter().cloned().map(ClientControlMessage::Input).collect();
|
||||||
|
assert_eq!(host_receives(&mut w, inputs.len()), typed);
|
||||||
|
|
||||||
|
// Rumble from the host reaches the client.
|
||||||
|
let t = at(w.now_ms);
|
||||||
|
w.host.h().send_rumble(t, 0, 0x4000, 0xC000).unwrap();
|
||||||
|
w.host.h().send_rumble_triggers(t, 0, 0x1000, 0x2000).unwrap();
|
||||||
|
assert!(w.run_until(w.now_ms + 10_000, |w| w.client.host_messages.len() >= 2));
|
||||||
|
assert_eq!(
|
||||||
|
w.client.host_messages,
|
||||||
|
vec![
|
||||||
|
HostMessage::Rumble { controller: 0, low_frequency: 0x4000, high_frequency: 0xC000 },
|
||||||
|
HostMessage::RumbleTriggers { controller: 0, left: 0x1000, right: 0x2000 },
|
||||||
|
]
|
||||||
|
);
|
||||||
|
|
||||||
|
// Nothing on control was dropped, timed out or stopped for want of pings.
|
||||||
|
assert!(
|
||||||
|
!w.host.events.iter().any(|e| matches!(
|
||||||
|
e,
|
||||||
|
ControlHostEvent::Dropped | ControlHostEvent::TimedOut | ControlHostEvent::PingTimedOut
|
||||||
|
))
|
||||||
|
);
|
||||||
|
|
||||||
|
// Graceful termination, then the ENet disconnect; both ends close. (Should the client's one acknowledgement of
|
||||||
|
// the disconnect be lost, the host gives up after its timeout, as stock ENet does.)
|
||||||
|
let t = at(w.now_ms);
|
||||||
|
w.host.h().send_termination(t, TERMINATION_GRACEFUL).unwrap();
|
||||||
|
w.host.h().close(t).unwrap();
|
||||||
|
assert!(w.run_until(w.now_ms + 30_000, |w| w.client.enet.state() == EnetState::Disconnected
|
||||||
|
&& w.host.host.as_ref().is_some_and(|h| h.enet().state() == EnetHostState::Disconnected)));
|
||||||
|
assert_eq!(w.client.host_messages.last(), Some(&HostMessage::Termination { error_code: Some(0x8003_0023) }));
|
||||||
|
assert_eq!(w.client.enet_events, vec![EnetEvent::Connected, EnetEvent::Disconnected { data: 0 }]);
|
||||||
|
|
||||||
|
// The client quits the game; the host is free again.
|
||||||
|
parse_status_response(&get(&mut host, &cancel_request(UID).unwrap(), &client, pin)).unwrap();
|
||||||
|
let info =
|
||||||
|
parse_server_info(&get(&mut host, &server_info_request(Scheme::Https, UID).unwrap(), &client, pin)).unwrap();
|
||||||
|
assert_eq!((info.paired, info.current_game, info.state.as_str()), (true, 0, "LUMEN_SERVER_FREE"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_tessera_trusted_client_needs_no_pairing() {
|
||||||
|
let mut rng = SeqRng::new(0x7E55);
|
||||||
|
let client = client_identity("client");
|
||||||
|
let mut host = LumenHttp::new(2);
|
||||||
|
// The grant: the host records the client's certificate, the client gets the host's out of band. No PIN anywhere.
|
||||||
|
host.paired.push(PairedClient::trusted(client.cert_der()).unwrap());
|
||||||
|
let host_cert = ServerCert::from_der(host.identity.cert_der()).unwrap();
|
||||||
|
let pin = Some(&host_cert);
|
||||||
|
|
||||||
|
let info =
|
||||||
|
parse_server_info(&get(&mut host, &server_info_request(Scheme::Https, UID).unwrap(), &client, pin)).unwrap();
|
||||||
|
assert!(info.paired);
|
||||||
|
assert_eq!(parse_app_list(&get(&mut host, &app_list_request(UID).unwrap(), &client, pin)).unwrap(), host.apps);
|
||||||
|
let keys = SessionKeys::generate(&mut rng).unwrap();
|
||||||
|
let params = LaunchParams {
|
||||||
|
app_id: 1,
|
||||||
|
width: 1280,
|
||||||
|
height: 720,
|
||||||
|
fps: 30,
|
||||||
|
keys: keys.clone(),
|
||||||
|
hdr: false,
|
||||||
|
audio: AudioLayout::Stereo,
|
||||||
|
};
|
||||||
|
assert!(
|
||||||
|
parse_launch_response(&get(&mut host, &launch_request(¶ms, UID).unwrap(), &client, pin))
|
||||||
|
.unwrap()
|
||||||
|
.game_session
|
||||||
|
);
|
||||||
|
assert_eq!(host.launched.map(|l| l.keys), Some(keys));
|
||||||
|
assert!(host.pairing.is_none(), "no /pair call was made");
|
||||||
|
|
||||||
|
// The pin is what makes it safe: a host presenting another certificate is not the paired one.
|
||||||
|
let rogue_host = ServerCert::from_der(client_identity("rogue").cert_der()).unwrap();
|
||||||
|
assert_eq!(rogue_host.matches(host.identity.cert_der()), Ok(false));
|
||||||
|
assert_eq!(host_cert.matches(client_identity("rogue").cert_der()), Ok(false));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn an_unpaired_client_is_refused_over_https() {
|
||||||
|
let mut host = LumenHttp::new(3);
|
||||||
|
let paired_client = client_identity("client");
|
||||||
|
host.paired.push(PairedClient::trusted(paired_client.cert_der()).unwrap());
|
||||||
|
let stranger = client_identity("rogue");
|
||||||
|
let host_cert = ServerCert::from_der(host.identity.cert_der()).unwrap();
|
||||||
|
let pin = Some(&host_cert);
|
||||||
|
|
||||||
|
// serverinfo answers, but says "not paired"; everything else is refused.
|
||||||
|
let info =
|
||||||
|
parse_server_info(&get(&mut host, &server_info_request(Scheme::Https, UID).unwrap(), &stranger, pin)).unwrap();
|
||||||
|
assert!(!info.paired);
|
||||||
|
assert_err!(
|
||||||
|
parse_app_list(&get(&mut host, &app_list_request(UID).unwrap(), &stranger, pin)),
|
||||||
|
Error::HostStatus { code: 401 }
|
||||||
|
);
|
||||||
|
let keys = SessionKeys::generate(&mut SeqRng::new(4)).unwrap();
|
||||||
|
let params =
|
||||||
|
LaunchParams { app_id: 1, width: 1280, height: 720, fps: 30, keys, hdr: false, audio: AudioLayout::Stereo };
|
||||||
|
assert_err!(
|
||||||
|
parse_launch_response(&get(&mut host, &launch_request(¶ms, UID).unwrap(), &stranger, pin)),
|
||||||
|
Error::HostStatus { code: 401 }
|
||||||
|
);
|
||||||
|
assert!(host.launched.is_none());
|
||||||
|
// Plain HTTP never reaches the HTTPS routes either.
|
||||||
|
let over_http = HttpRequest { scheme: Scheme::Http, ..app_list_request(UID).unwrap() };
|
||||||
|
assert_err!(parse_app_list(&get(&mut host, &over_http, &paired_client, None)), Error::HostStatus { code: 401 });
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user