3e09dbc09a
Moonshine f184d5e (BSD-2, CLEAN_ROOM S-21) reads no body from START_B, PERIODIC_PING or the IDR request, ignores LOSS_STATS and FRAME_STATS, does not know START_A (skipped inside the encrypted frame, fatal outside it), and stops a stream after 60 s without a ping. No GPL-provenance value taken. - Probe defaults: START_A and START_B empty, PERIODIC_PING empty every 500 ms, an empty IDR request on frame loss; every body stays overridable by hex or `none`. - Tests: the candidates' plaintext headers, their sealed frame layout and Moonshine's client-to-host IV, and the INVALIDATE_REF_FRAMES field offsets Moonshine reads. - PROTOCOL.md 3.3 and the U10 row narrowed with the [M] facts. - LIVE-INTEROP.md: P3 decided (dev-only `sunshine-api` in arena-host behind a never-shipped feature, credentials from Custos), P4 done, table V rewritten without guessed bodies, first launch 90 s to outlast a 60 s ping deadline, the black-box list pointed at PLAY-REMOTELY's handover, §8 and §15 (§17 is the installer spec).
1209 lines
49 KiB
Rust
1209 lines
49 KiB
Rust
//! `probe launch`: HTTPS launch, RTSP, then the three UDP streams for `--seconds`.
|
|
//!
|
|
//! Control runs on DomiStream's `EnetClient` with `ControlCipher` directly (not `ControlStream`), because START_A,
|
|
//! START_B, PERIODIC_PING and the IDR request have UNKNOWN bodies (U10) that the crate refuses to guess: the probe
|
|
//! sends the bodies given on the command line and records what the host does. Video goes through
|
|
//! `VideoDepacketizer`; audio through two `AudioDepacketizer`s, one decrypting and one not, which settles U17 by
|
|
//! which of them accepts the packets.
|
|
|
|
use std::collections::BTreeMap;
|
|
use std::fs::File;
|
|
use std::io::{self, BufWriter, Write};
|
|
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, UdpSocket};
|
|
use std::sync::atomic::{AtomicBool, Ordering};
|
|
use std::sync::{Arc, mpsc};
|
|
use std::thread;
|
|
use std::time::{Duration, Instant as StdInstant};
|
|
|
|
use domistream::audio::{
|
|
AudioCipher, AudioConfig, AudioDepacketizer, AudioEvent, AudioFec, AudioPacket, parse_audio_packet,
|
|
};
|
|
use domistream::control::message::encode_client_message;
|
|
use domistream::control::{ClientMessage, ControlCipher, Direction, parse_host_message, parse_message};
|
|
use domistream::enet::protocol::parse_datagram;
|
|
use domistream::enet::{Delivery, EnetClient, EnetConfig, EnetEvent, EnetState};
|
|
use domistream::http::launch::{LaunchParams, launch_request, parse_launch_response};
|
|
use domistream::input::InputEvent;
|
|
use domistream::rtsp::client::{StreamConfig, VideoCodec};
|
|
use domistream::rtsp::{EncryptionFlags, NegotiatedStream};
|
|
use domistream::video::{FrameType, VideoCipher, VideoConfig, VideoDepacketizer, VideoEvent, parse_video_packet};
|
|
use domistream::{Instant, SessionKeys};
|
|
|
|
use crate::args::{Body, Options};
|
|
use crate::dump::PacketDump;
|
|
use crate::fec::{VideoFecCheck, VideoOutcome};
|
|
use crate::log::{J, Kind, Log, bytes, hex};
|
|
use crate::{Ctx, rtsp};
|
|
|
|
/// Control message types the probe sends with command-line bodies (PROTOCOL.md 3.3). The default bodies are empty:
|
|
/// Moonshine reads no body from START_B, PERIODIC_PING or the IDR request and skips an unknown type such as START_A
|
|
/// inside the encrypted frame (U10, [M] S-21); Sunshine is settled live.
|
|
const START_A: u16 = 0x0305;
|
|
const START_B: u16 = 0x0307;
|
|
const PERIODIC_PING: u16 = 0x0200;
|
|
const IDR_REQUEST: u16 = 0x0302;
|
|
|
|
/// Records kept per kind before the log only counts.
|
|
const LOGGED_CONTROL_DATAGRAMS: u32 = 64;
|
|
const LOGGED_HOST_MESSAGES: u32 = 200;
|
|
const LOGGED_PARSE_ERRORS: u64 = 20;
|
|
const LOGGED_FRAMES: u64 = 16;
|
|
/// Frames whose RTP timestamps are kept for U29.
|
|
const KEPT_TIMESTAMPS: usize = 600;
|
|
/// Video blocks checked against our encoder (U14).
|
|
const CHECKED_BLOCKS: u64 = 500;
|
|
/// Gap between two recovery requests on loss.
|
|
const RECOVERY_GAP: Duration = Duration::from_millis(250);
|
|
|
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
|
enum Src {
|
|
Video,
|
|
Audio,
|
|
Control,
|
|
}
|
|
|
|
enum Msg {
|
|
Datagram { src: Src, at: StdInstant, from: SocketAddr, bytes: Vec<u8> },
|
|
SocketError { src: Src, error: String },
|
|
}
|
|
|
|
fn reader(src: Src, sock: UdpSocket, tx: mpsc::Sender<Msg>, stop: Arc<AtomicBool>) {
|
|
let mut buf = vec![0u8; 65_536];
|
|
while !stop.load(Ordering::Relaxed) {
|
|
match sock.recv_from(&mut buf) {
|
|
Ok((n, from)) => {
|
|
let bytes = buf.get(..n).unwrap_or(&[]).to_vec();
|
|
if tx.send(Msg::Datagram { src, at: StdInstant::now(), from, bytes }).is_err() {
|
|
break;
|
|
}
|
|
}
|
|
Err(e) if matches!(e.kind(), io::ErrorKind::WouldBlock | io::ErrorKind::TimedOut) => {}
|
|
Err(e) => {
|
|
// Windows reports an ICMP "port unreachable" for an earlier send as a receive error
|
|
// (ConnectionReset): that is a finding (nothing listens there), not the end of the socket.
|
|
if tx.send(Msg::SocketError { src, error: e.to_string() }).is_err() {
|
|
break;
|
|
}
|
|
thread::sleep(Duration::from_millis(20));
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
#[derive(Default)]
|
|
struct VideoCounters {
|
|
datagrams: u64,
|
|
bytes: u64,
|
|
first_at_ms: Option<f64>,
|
|
first_from: Option<SocketAddr>,
|
|
decrypt_failures: u64,
|
|
parse_errors: u64,
|
|
multi_fec_flags: BTreeMap<u8, u64>,
|
|
fec_percentages: BTreeMap<u8, u64>,
|
|
data_shards: BTreeMap<u16, u64>,
|
|
frames: u64,
|
|
frames_lost: u64,
|
|
loss_events: u64,
|
|
recovered_shards: u64,
|
|
decode_ready: u64,
|
|
have_reference: bool,
|
|
frame_types: BTreeMap<String, u64>,
|
|
header_types: BTreeMap<u8, u64>,
|
|
timestamps: Vec<(u32, u32)>,
|
|
assembly_ms_sum: f64,
|
|
assembly_ms_max: f64,
|
|
es_frames: u32,
|
|
es_bytes: u64,
|
|
recovery_requests: u64,
|
|
}
|
|
|
|
#[derive(Default)]
|
|
struct AudioCounters {
|
|
datagrams: u64,
|
|
bytes: u64,
|
|
first_at_ms: Option<f64>,
|
|
first_from: Option<SocketAddr>,
|
|
data: u64,
|
|
parity: u64,
|
|
parse_errors: u64,
|
|
payload_lens: BTreeMap<usize, u64>,
|
|
lost_decrypting: u64,
|
|
lost_plain: u64,
|
|
}
|
|
|
|
#[derive(Default)]
|
|
struct ControlCounters {
|
|
sent_datagrams: u32,
|
|
received_datagrams: u32,
|
|
enet_errors: u64,
|
|
connected_at_ms: Option<f64>,
|
|
host_messages: BTreeMap<u16, u64>,
|
|
host_frames_failed: u64,
|
|
host_replays: u64,
|
|
first_host_sequence: Option<u32>,
|
|
last_host_sequence: Option<u32>,
|
|
logged_messages: u32,
|
|
sent: Vec<(String, u32)>,
|
|
ended: Option<String>,
|
|
}
|
|
|
|
struct Session<'a> {
|
|
log: &'a mut Log,
|
|
epoch: StdInstant,
|
|
host: IpAddr,
|
|
stream: NegotiatedStream,
|
|
opts: Options,
|
|
video_sock: UdpSocket,
|
|
audio_sock: UdpSocket,
|
|
control_sock: UdpSocket,
|
|
control_addr: SocketAddr,
|
|
enet: EnetClient,
|
|
cipher: ControlCipher,
|
|
next_sequence: u32,
|
|
video: VideoDepacketizer,
|
|
video_cipher: Option<VideoCipher>,
|
|
audio_decrypting: AudioDepacketizer,
|
|
audio_plain: AudioDepacketizer,
|
|
v: VideoCounters,
|
|
a: AudioCounters,
|
|
c: ControlCounters,
|
|
es: Option<BufWriter<File>>,
|
|
video_dump: PacketDump,
|
|
audio_dump: PacketDump,
|
|
fec_check: VideoFecCheck,
|
|
pings: u64,
|
|
next_ping: StdInstant,
|
|
next_periodic: Option<StdInstant>,
|
|
last_recovery: Option<StdInstant>,
|
|
nudged: bool,
|
|
foreign: u64,
|
|
socket_errors: BTreeMap<String, u64>,
|
|
}
|
|
|
|
fn ds(epoch: StdInstant, at: StdInstant) -> Instant {
|
|
Instant::from_micros(u64::try_from(at.saturating_duration_since(epoch).as_micros()).unwrap_or(u64::MAX))
|
|
}
|
|
|
|
fn std_at(epoch: StdInstant, at: Instant) -> StdInstant {
|
|
epoch + Duration::from_micros(at.as_micros())
|
|
}
|
|
|
|
fn ms_since(epoch: StdInstant, at: StdInstant) -> f64 {
|
|
at.saturating_duration_since(epoch).as_secs_f64() * 1000.0
|
|
}
|
|
|
|
fn bind(opts: &Options, host: IpAddr) -> io::Result<UdpSocket> {
|
|
let local = opts.bind.unwrap_or(match host {
|
|
IpAddr::V4(_) => IpAddr::V4(Ipv4Addr::UNSPECIFIED),
|
|
IpAddr::V6(_) => IpAddr::V6(Ipv6Addr::UNSPECIFIED),
|
|
});
|
|
let s = UdpSocket::bind(SocketAddr::new(local, 0))?;
|
|
s.set_read_timeout(Some(Duration::from_millis(100)))?;
|
|
Ok(s)
|
|
}
|
|
|
|
fn codec_ext(c: VideoCodec) -> &'static str {
|
|
match c {
|
|
VideoCodec::H264 => "h264",
|
|
VideoCodec::Hevc => "h265",
|
|
VideoCodec::Av1 => "av1.obu",
|
|
}
|
|
}
|
|
|
|
fn body_of(b: &Body) -> Option<&[u8]> {
|
|
match b {
|
|
Body::None => None,
|
|
Body::Bytes(v) => Some(v),
|
|
}
|
|
}
|
|
|
|
/// `type u16 LE`, `length u16 LE`, body: a control message before sealing (PROTOCOL.md 3.3).
|
|
pub fn raw_message(message_type: u16, body: &[u8]) -> Option<Vec<u8>> {
|
|
let len = u16::try_from(body.len()).ok()?;
|
|
let mut m = Vec::with_capacity(4 + body.len());
|
|
m.extend_from_slice(&message_type.to_le_bytes());
|
|
m.extend_from_slice(&len.to_le_bytes());
|
|
m.extend_from_slice(body);
|
|
Some(m)
|
|
}
|
|
|
|
impl Session<'_> {
|
|
fn now(&self) -> Instant {
|
|
ds(self.epoch, StdInstant::now())
|
|
}
|
|
|
|
/// Seals and queues one message; `logged` records it (periodic pings are counted only after the first three).
|
|
fn send_control_plain(&mut self, now: Instant, step: &str, name: &str, plain: &[u8], logged: bool) {
|
|
let seq = self.next_sequence;
|
|
let frame = match self.cipher.seal(seq, Direction::ClientToHost, plain) {
|
|
Ok(f) => f,
|
|
Err(e) => {
|
|
self.log.note(step, &["U10"], format!("{name}: not sealed: {e}"));
|
|
return;
|
|
}
|
|
};
|
|
match self.enet.send(now, self.opts.control_channel, Delivery::Reliable, &frame) {
|
|
Ok(()) => {
|
|
self.next_sequence = self.next_sequence.wrapping_add(1);
|
|
self.c.sent.push((name.to_owned(), seq));
|
|
if !logged {
|
|
return;
|
|
}
|
|
self.log.record(
|
|
step,
|
|
Kind::Send,
|
|
&["U10", "U11"],
|
|
J::O(vec![
|
|
("message", J::s(name)),
|
|
("sequence", J::U(u64::from(seq))),
|
|
("channel", J::U(u64::from(self.opts.control_channel))),
|
|
("plaintext", bytes(plain)),
|
|
]),
|
|
);
|
|
}
|
|
Err(e) => self.log.note(step, &["U10"], format!("{name}: ENet refused it: {e}")),
|
|
}
|
|
}
|
|
|
|
fn send_raw(&mut self, now: Instant, step: &str, name: &str, message_type: u16, body: &[u8]) {
|
|
match raw_message(message_type, body) {
|
|
Some(m) => {
|
|
let logged = name != "PERIODIC_PING" || self.c.sent.iter().filter(|(n, _)| n == name).count() < 3;
|
|
self.send_control_plain(now, step, name, &m, logged);
|
|
}
|
|
None => self.log.note(step, &["U10"], format!("{name}: body too long")),
|
|
}
|
|
}
|
|
|
|
fn send_message(&mut self, now: Instant, step: &str, name: &str, m: &ClientMessage) {
|
|
match encode_client_message(m) {
|
|
Ok(plain) => self.send_control_plain(now, step, name, &plain, true),
|
|
Err(e) => self.log.note(step, &["U10"], format!("{name}: not encoded: {e}")),
|
|
}
|
|
}
|
|
|
|
fn flush_control(&mut self, now: Instant) {
|
|
while let Some(d) = self.enet.poll_transmit(now) {
|
|
if let Err(e) = self.control_sock.send_to(&d, self.control_addr) {
|
|
self.log.note("control.send", &["U9"], format!("send failed: {e}"));
|
|
}
|
|
self.c.sent_datagrams += 1;
|
|
if self.c.sent_datagrams <= LOGGED_CONTROL_DATAGRAMS {
|
|
let parsed = parse_datagram(&d).map_or_else(|e| J::s(format!("unparsed: {e}")), |p| J::dbg(&p));
|
|
self.log.record(
|
|
"control.datagram",
|
|
Kind::Send,
|
|
&["U9"],
|
|
J::O(vec![("enet", parsed), ("bytes", bytes(&d))]),
|
|
);
|
|
}
|
|
}
|
|
}
|
|
|
|
fn drain_control(&mut self, now: Instant) {
|
|
while let Some(e) = self.enet.poll_event() {
|
|
match e {
|
|
EnetEvent::Connected => {
|
|
self.c.connected_at_ms = Some(self.log.t_ms());
|
|
self.log.record(
|
|
"control.connected",
|
|
Kind::Recv,
|
|
&["U9"],
|
|
J::O(vec![("round_trip", J::dbg(&self.enet.round_trip_time()))]),
|
|
);
|
|
if let Some(b) = body_of(&self.opts.start_a).map(<[u8]>::to_vec) {
|
|
self.send_raw(now, "control.start_a", "START_A", START_A, &b);
|
|
}
|
|
if let Some(b) = body_of(&self.opts.start_b).map(<[u8]>::to_vec) {
|
|
self.send_raw(now, "control.start_b", "START_B", START_B, &b);
|
|
}
|
|
if body_of(&self.opts.periodic_ping).is_some() {
|
|
self.next_periodic = Some(StdInstant::now());
|
|
}
|
|
}
|
|
EnetEvent::Received { channel, data } => self.host_frame(channel, &data),
|
|
EnetEvent::Disconnected { data } => {
|
|
self.c.ended = Some(format!("host disconnected (data {data:#x})"));
|
|
self.log.record(
|
|
"control.disconnected",
|
|
Kind::Recv,
|
|
&["U10"],
|
|
J::O(vec![("data", J::U(u64::from(data)))]),
|
|
);
|
|
}
|
|
EnetEvent::TimedOut => {
|
|
self.c.ended = Some("ENet timed out".into());
|
|
self.log.record("control.timed_out", Kind::Note, &["U9"], J::Null);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
fn host_frame(&mut self, channel: u8, frame: &[u8]) {
|
|
match self.cipher.open(Direction::HostToClient, frame) {
|
|
Err(e) => {
|
|
self.c.host_frames_failed += 1;
|
|
if self.c.host_frames_failed <= LOGGED_PARSE_ERRORS {
|
|
self.log.parse_error("control.host", &["U10", "U11"], &e, bytes(frame));
|
|
}
|
|
}
|
|
Ok((seq, plain)) => {
|
|
if self.c.last_host_sequence.is_some_and(|last| seq <= last) {
|
|
self.c.host_replays += 1;
|
|
}
|
|
self.c.first_host_sequence.get_or_insert(seq);
|
|
self.c.last_host_sequence = Some(seq);
|
|
let kind = parse_message(&plain).map(|m| m.message_type);
|
|
if let Ok(t) = kind {
|
|
*self.c.host_messages.entry(t).or_default() += 1;
|
|
}
|
|
self.c.logged_messages += 1;
|
|
if self.c.logged_messages <= LOGGED_HOST_MESSAGES {
|
|
let parsed =
|
|
parse_host_message(&plain).map_or_else(|e| J::s(format!("unparsed: {e}")), |m| J::dbg(&m));
|
|
self.log.record(
|
|
"control.host",
|
|
Kind::Recv,
|
|
&["U10", "U11", "U23"],
|
|
J::O(vec![
|
|
("channel", J::U(u64::from(channel))),
|
|
("sequence", J::U(u64::from(seq))),
|
|
("type", kind.map_or(J::Null, |t| J::s(format!("{t:#06x}")))),
|
|
("message", parsed),
|
|
("plaintext", bytes(&plain)),
|
|
]),
|
|
);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
fn on_control(&mut self, at: StdInstant, d: &[u8]) {
|
|
let now = ds(self.epoch, at);
|
|
self.c.received_datagrams += 1;
|
|
if self.c.received_datagrams <= LOGGED_CONTROL_DATAGRAMS {
|
|
let parsed = parse_datagram(d).map_or_else(|e| J::s(format!("unparsed: {e}")), |p| J::dbg(&p));
|
|
self.log.record("control.datagram", Kind::Recv, &["U9"], J::O(vec![("enet", parsed), ("bytes", bytes(d))]));
|
|
}
|
|
if let Err(e) = self.enet.handle_datagram(now, d) {
|
|
self.c.enet_errors += 1;
|
|
if self.c.enet_errors <= LOGGED_PARSE_ERRORS {
|
|
self.log.parse_error("control.datagram", &["U9"], &e, bytes(d));
|
|
}
|
|
}
|
|
self.drain_control(now);
|
|
}
|
|
|
|
fn on_video(&mut self, at: StdInstant, from: SocketAddr, d: &[u8]) {
|
|
let now = ds(self.epoch, at);
|
|
self.v.datagrams += 1;
|
|
self.v.bytes += d.len() as u64;
|
|
if self.v.first_at_ms.is_none() {
|
|
self.v.first_at_ms = Some(ms_since(self.epoch, at));
|
|
self.v.first_from = Some(from);
|
|
self.log.record(
|
|
"video.first",
|
|
Kind::Recv,
|
|
&["U8", "U19"],
|
|
J::O(vec![
|
|
("from", J::s(from.to_string())),
|
|
("pings_before", J::U(self.pings)),
|
|
("bytes", bytes(d.get(..64).unwrap_or(d))),
|
|
]),
|
|
);
|
|
}
|
|
let plain = match &self.video_cipher {
|
|
None => Some(d.to_vec()),
|
|
Some(c) => match c.decrypt(d) {
|
|
Ok(p) => Some(p),
|
|
Err(e) => {
|
|
self.v.decrypt_failures += 1;
|
|
if self.v.decrypt_failures <= LOGGED_PARSE_ERRORS {
|
|
self.log.parse_error("video.decrypt", &["U19"], &e, bytes(d.get(..96).unwrap_or(d)));
|
|
}
|
|
None
|
|
}
|
|
},
|
|
};
|
|
if let Some(p) = plain {
|
|
let t_us = now.as_micros();
|
|
if let Err(e) = self.video_dump.push(t_us, &p) {
|
|
self.log.note("video.dump", &[], format!("dump write failed: {e}"));
|
|
}
|
|
match parse_video_packet(&p) {
|
|
Ok(pkt) => {
|
|
*self.v.multi_fec_flags.entry(pkt.nv.multi_fec_flags).or_default() += 1;
|
|
*self.v.fec_percentages.entry(pkt.nv.fec.fec_percentage).or_default() += 1;
|
|
*self.v.data_shards.entry(pkt.nv.fec.data_shards).or_default() += 1;
|
|
let f = pkt.nv.fec;
|
|
let outcome = self.fec_check.push(
|
|
pkt.nv.frame_index,
|
|
f.block_index,
|
|
f.shard_index,
|
|
f.data_shards,
|
|
f.fec_percentage,
|
|
&p,
|
|
);
|
|
if outcome == Some(VideoOutcome::Neither) && self.fec_check.neither <= 3 {
|
|
self.log.note(
|
|
"video.fec_check",
|
|
&["U14"],
|
|
format!(
|
|
"frame {} block {}: our parity differs from the host's",
|
|
pkt.nv.frame_index, f.block_index
|
|
),
|
|
);
|
|
}
|
|
}
|
|
Err(e) => {
|
|
self.v.parse_errors += 1;
|
|
if self.v.parse_errors <= LOGGED_PARSE_ERRORS {
|
|
self.log.parse_error("video.packet", &["U13", "U15"], &e, bytes(p.get(..96).unwrap_or(&p)));
|
|
}
|
|
}
|
|
}
|
|
}
|
|
if let Err(e) = self.video.push(now, d) {
|
|
self.log.parse_error("video.push", &[], &e, bytes(d.get(..64).unwrap_or(d)));
|
|
}
|
|
self.drain_video(now);
|
|
}
|
|
|
|
fn drain_video(&mut self, now: Instant) {
|
|
while let Some(e) = self.video.poll_event() {
|
|
match e {
|
|
VideoEvent::Frame(f) => {
|
|
self.v.frames += 1;
|
|
self.v.recovered_shards += u64::from(f.recovered_shards);
|
|
*self.v.header_types.entry(f.header.header_type).or_default() += 1;
|
|
*self.v.frame_types.entry(format!("{:?}", f.header.frame_type)).or_default() += 1;
|
|
if matches!(f.header.frame_type, FrameType::Key | FrameType::Recovery) {
|
|
self.v.have_reference = true;
|
|
}
|
|
if self.v.have_reference {
|
|
self.v.decode_ready += 1;
|
|
}
|
|
let assembly = f.completed_at.saturating_duration_since(f.first_packet_at).as_secs_f64() * 1000.0;
|
|
self.v.assembly_ms_sum += assembly;
|
|
self.v.assembly_ms_max = self.v.assembly_ms_max.max(assembly);
|
|
if self.v.timestamps.len() < KEPT_TIMESTAMPS {
|
|
self.v.timestamps.push((f.frame_index, f.rtp_timestamp));
|
|
}
|
|
if self.v.frames <= LOGGED_FRAMES {
|
|
self.log.record(
|
|
"video.frame",
|
|
Kind::Recv,
|
|
&["U13", "U29"],
|
|
J::O(vec![
|
|
("frame_index", J::U(u64::from(f.frame_index))),
|
|
("header_raw", J::s(hex(&f.header.raw))),
|
|
("header", J::dbg(&f.header)),
|
|
("bitstream_len", J::U(f.bitstream.len() as u64)),
|
|
("bitstream_head", J::s(hex(f.bitstream.get(..16).unwrap_or(&f.bitstream)))),
|
|
("rtp_timestamp", J::U(u64::from(f.rtp_timestamp))),
|
|
("recovered_shards", J::U(u64::from(f.recovered_shards))),
|
|
("assembly_ms", J::F(assembly)),
|
|
]),
|
|
);
|
|
}
|
|
if self.v.es_frames < self.opts.dump_frames
|
|
&& let Some(w) = &mut self.es
|
|
&& w.write_all(&f.bitstream).is_ok()
|
|
{
|
|
self.v.es_frames += 1;
|
|
self.v.es_bytes += f.bitstream.len() as u64;
|
|
}
|
|
if self.opts.nudge_mouse && !self.nudged && self.v.have_reference {
|
|
self.nudged = true;
|
|
for dx in [1i16, -1] {
|
|
let m = ClientMessage::Input(InputEvent::MouseMoveRel { dx, dy: 0 });
|
|
self.send_message(now, "control.input", "INPUT_DATA mouse move", &m);
|
|
}
|
|
}
|
|
}
|
|
VideoEvent::FrameLost { first, last } => {
|
|
let n = u64::from(last.wrapping_sub(first)) + 1;
|
|
self.v.frames_lost += n;
|
|
self.v.loss_events += 1;
|
|
self.v.have_reference = false;
|
|
if self.v.loss_events <= LOGGED_PARSE_ERRORS {
|
|
self.log.record(
|
|
"video.lost",
|
|
Kind::Note,
|
|
&["U10"],
|
|
J::O(vec![("first", J::U(u64::from(first))), ("last", J::U(u64::from(last)))]),
|
|
);
|
|
}
|
|
self.request_recovery(now, first, last);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
fn request_recovery(&mut self, now: Instant, first: u32, last: u32) {
|
|
let at = StdInstant::now();
|
|
if self.last_recovery.is_some_and(|t| at.saturating_duration_since(t) < RECOVERY_GAP) {
|
|
return;
|
|
}
|
|
if self.opts.rfi && self.stream.host.reference_frame_invalidation {
|
|
self.last_recovery = Some(at);
|
|
self.v.recovery_requests += 1;
|
|
self.send_message(
|
|
now,
|
|
"control.invalidate",
|
|
"INVALIDATE_REF_FRAMES",
|
|
&ClientMessage::InvalidateRefFrames { first, last },
|
|
);
|
|
} else if let Some(b) = body_of(&self.opts.idr).map(<[u8]>::to_vec) {
|
|
self.last_recovery = Some(at);
|
|
self.v.recovery_requests += 1;
|
|
self.send_raw(now, "control.idr", "IDR_FRAME request", IDR_REQUEST, &b);
|
|
}
|
|
}
|
|
|
|
fn on_audio(&mut self, at: StdInstant, from: SocketAddr, d: &[u8]) {
|
|
let now = ds(self.epoch, at);
|
|
self.a.datagrams += 1;
|
|
self.a.bytes += d.len() as u64;
|
|
if self.a.first_at_ms.is_none() {
|
|
self.a.first_at_ms = Some(ms_since(self.epoch, at));
|
|
self.a.first_from = Some(from);
|
|
self.log.record(
|
|
"audio.first",
|
|
Kind::Recv,
|
|
&["U8", "U17"],
|
|
J::O(vec![
|
|
("from", J::s(from.to_string())),
|
|
("pings_before", J::U(self.pings)),
|
|
("bytes", bytes(d.get(..64).unwrap_or(d))),
|
|
]),
|
|
);
|
|
}
|
|
if let Err(e) = self.audio_dump.push(now.as_micros(), d) {
|
|
self.log.note("audio.dump", &[], format!("dump write failed: {e}"));
|
|
}
|
|
match parse_audio_packet(d) {
|
|
Ok(AudioPacket::Data { payload, .. }) => {
|
|
self.a.data += 1;
|
|
if self.a.payload_lens.len() < 64 || self.a.payload_lens.contains_key(&payload.len()) {
|
|
*self.a.payload_lens.entry(payload.len()).or_default() += 1;
|
|
}
|
|
}
|
|
Ok(AudioPacket::Parity { .. }) => self.a.parity += 1,
|
|
Err(e) => {
|
|
self.a.parse_errors += 1;
|
|
if self.a.parse_errors <= LOGGED_PARSE_ERRORS {
|
|
self.log.parse_error("audio.packet", &["U16", "U17"], &e, bytes(d.get(..64).unwrap_or(d)));
|
|
}
|
|
}
|
|
}
|
|
for (dec, which) in [(&mut self.audio_decrypting, "decrypting"), (&mut self.audio_plain, "plain")] {
|
|
if let Err(e) = dec.push(now, d) {
|
|
self.log.parse_error(&format!("audio.push.{which}"), &[], &e, bytes(d.get(..64).unwrap_or(d)));
|
|
}
|
|
}
|
|
self.drain_audio();
|
|
}
|
|
|
|
fn drain_audio(&mut self) {
|
|
while let Some(e) = self.audio_decrypting.poll_event() {
|
|
if matches!(e, AudioEvent::Lost { .. }) {
|
|
self.a.lost_decrypting += 1;
|
|
}
|
|
}
|
|
while let Some(e) = self.audio_plain.poll_event() {
|
|
if matches!(e, AudioEvent::Lost { .. }) {
|
|
self.a.lost_plain += 1;
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Timers of every state machine, pings, and the periodic control ping.
|
|
fn tick(&mut self) {
|
|
let at = StdInstant::now();
|
|
let now = ds(self.epoch, at);
|
|
if self.enet.poll_timeout().is_some_and(|t| t <= now) {
|
|
if let Err(e) = self.enet.handle_timeout(now) {
|
|
self.log.note("control.timeout", &["U9"], format!("ENet timer: {e}"));
|
|
}
|
|
self.drain_control(now);
|
|
}
|
|
if self.video.poll_timeout().is_some_and(|t| t <= now) {
|
|
let _ = self.video.handle_timeout(now);
|
|
self.drain_video(now);
|
|
}
|
|
for dec in [&mut self.audio_decrypting, &mut self.audio_plain] {
|
|
if dec.poll_timeout().is_some_and(|t| t <= now) {
|
|
let _ = dec.handle_timeout(now);
|
|
}
|
|
}
|
|
self.drain_audio();
|
|
if at >= self.next_ping {
|
|
self.next_ping = at + Duration::from_millis(u64::from(self.opts.ping_ms));
|
|
let payload = self.stream.ping_payload.clone();
|
|
for (sock, port, name) in [
|
|
(&self.video_sock, self.stream.ports.video, "video"),
|
|
(&self.audio_sock, self.stream.ports.audio, "audio"),
|
|
] {
|
|
if let Err(e) = sock.send_to(&payload, SocketAddr::new(self.host, port)) {
|
|
self.log.note("ping", &["U8"], format!("{name} ping failed: {e}"));
|
|
}
|
|
}
|
|
self.pings += 1;
|
|
if self.pings <= 3 {
|
|
self.log.record(
|
|
"ping",
|
|
Kind::Send,
|
|
&["U8"],
|
|
J::O(vec![
|
|
("payload", bytes(&payload)),
|
|
("video_port", J::U(u64::from(self.stream.ports.video))),
|
|
("audio_port", J::U(u64::from(self.stream.ports.audio))),
|
|
]),
|
|
);
|
|
}
|
|
}
|
|
if let Some(due) = self.next_periodic
|
|
&& at >= due
|
|
&& self.enet.state() == EnetState::Connected
|
|
{
|
|
self.next_periodic = Some(at + Duration::from_millis(u64::from(self.opts.periodic_ping_ms)));
|
|
if let Some(b) = body_of(&self.opts.periodic_ping).map(<[u8]>::to_vec) {
|
|
self.send_raw(now, "control.periodic_ping", "PERIODIC_PING", PERIODIC_PING, &b);
|
|
}
|
|
}
|
|
self.flush_control(now);
|
|
}
|
|
|
|
/// When the next timer is due.
|
|
fn next_due(&self, deadline: StdInstant) -> StdInstant {
|
|
let mut due = deadline.min(self.next_ping);
|
|
if let Some(p) = self.next_periodic {
|
|
due = due.min(p);
|
|
}
|
|
for t in [
|
|
self.enet.poll_timeout(),
|
|
self.video.poll_timeout(),
|
|
self.audio_decrypting.poll_timeout(),
|
|
self.audio_plain.poll_timeout(),
|
|
]
|
|
.into_iter()
|
|
.flatten()
|
|
{
|
|
due = due.min(std_at(self.epoch, t));
|
|
}
|
|
due
|
|
}
|
|
|
|
fn dispatch(&mut self, m: Msg) {
|
|
match m {
|
|
Msg::SocketError { src, error } => {
|
|
let key = format!("{src:?}: {error}");
|
|
let n = self.socket_errors.entry(key.clone()).or_default();
|
|
*n += 1;
|
|
if *n == 1 {
|
|
self.log.note(
|
|
"socket",
|
|
&["U8"],
|
|
format!("receive error on the {key} (Windows reports an ICMP port unreachable this way)"),
|
|
);
|
|
}
|
|
}
|
|
Msg::Datagram { src, at, from, bytes: d } => {
|
|
if from.ip() != self.host {
|
|
self.foreign += 1;
|
|
if self.foreign <= 3 {
|
|
self.log.note("socket", &[], format!("dropped a {src:?} datagram from {from}: not the host"));
|
|
}
|
|
return;
|
|
}
|
|
match src {
|
|
Src::Control => self.on_control(at, &d),
|
|
Src::Video => self.on_video(at, from, &d),
|
|
Src::Audio => self.on_audio(at, from, &d),
|
|
}
|
|
self.flush_control(ds(self.epoch, at));
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
/// The run's summary: what the sitting reads first.
|
|
fn summary(s: &Session<'_>, seconds: f64) -> J {
|
|
let map_u8 =
|
|
|m: &BTreeMap<u8, u64>| J::A(m.iter().map(|(k, v)| J::A(vec![J::s(format!("{k:#04x}")), J::U(*v)])).collect());
|
|
let v = &s.v;
|
|
// U29: RTP ticks per frame from consecutive delivered frames.
|
|
let mut deltas: Vec<u64> = v
|
|
.timestamps
|
|
.windows(2)
|
|
.filter_map(|w| {
|
|
let (f0, t0) = w[0];
|
|
let (f1, t1) = w[1];
|
|
let df = f1.wrapping_sub(f0);
|
|
(df > 0 && df < 8).then(|| u64::from(t1.wrapping_sub(t0)) / u64::from(df))
|
|
})
|
|
.collect();
|
|
deltas.sort_unstable();
|
|
let ticks_per_frame = deltas.get(deltas.len() / 2).copied();
|
|
let vs = s.video.stats();
|
|
let (ad, ap) = (s.audio_decrypting.stats(), s.audio_plain.stats());
|
|
J::O(vec![
|
|
("seconds", J::F(seconds)),
|
|
(
|
|
"negotiated",
|
|
J::O(vec![
|
|
("ports", J::dbg(&s.stream.ports)),
|
|
("encryption", J::U(u64::from(s.stream.encryption.0))),
|
|
("host", J::dbg(&s.stream.host)),
|
|
("opus", J::dbg(&s.stream.opus)),
|
|
("session_id", J::dbg(&s.stream.session_id)),
|
|
]),
|
|
),
|
|
(
|
|
"video",
|
|
J::O(vec![
|
|
("datagrams", J::U(v.datagrams)),
|
|
("bytes", J::U(v.bytes)),
|
|
("first_packet_ms", v.first_at_ms.map_or(J::Null, J::F)),
|
|
("first_from", v.first_from.map_or(J::Null, |a| J::s(a.to_string()))),
|
|
("decrypt_failures", J::U(v.decrypt_failures)),
|
|
("parse_errors", J::U(v.parse_errors)),
|
|
("frames", J::U(v.frames)),
|
|
("decode_ready_frames", J::U(v.decode_ready)),
|
|
("frames_lost", J::U(v.frames_lost)),
|
|
("loss_events", J::U(v.loss_events)),
|
|
("fec_recovered_shards", J::U(v.recovered_shards)),
|
|
("depacketizer", J::dbg(&vs)),
|
|
(
|
|
"frame_types",
|
|
J::A(v.frame_types.iter().map(|(k, n)| J::A(vec![J::s(k.clone()), J::U(*n)])).collect()),
|
|
),
|
|
("frame_header_types_u13", map_u8(&v.header_types)),
|
|
("multi_fec_flags_u15", map_u8(&v.multi_fec_flags)),
|
|
("fec_percentages", map_u8(&v.fec_percentages)),
|
|
(
|
|
"data_shards_per_block",
|
|
J::A(v.data_shards.iter().map(|(k, n)| J::A(vec![J::U(u64::from(*k)), J::U(*n)])).collect()),
|
|
),
|
|
("u14_blocks_checked", J::U(s.fec_check.checked)),
|
|
("u14_whole_packets_match", J::U(s.fec_check.whole)),
|
|
("u14_payload_only_match", J::U(s.fec_check.payload_only)),
|
|
("u14_no_match", J::U(s.fec_check.neither)),
|
|
("u14_skipped", J::U(s.fec_check.skipped)),
|
|
("u29_rtp_ticks_per_frame", ticks_per_frame.map_or(J::Null, J::U)),
|
|
("u29_clock_hz_estimate", ticks_per_frame.map_or(J::Null, |t| J::U(t * u64::from(s.opts.fps)))),
|
|
("assembly_ms_mean", if v.frames > 0 { J::F(v.assembly_ms_sum / v.frames as f64) } else { J::Null }),
|
|
("assembly_ms_max", J::F(v.assembly_ms_max)),
|
|
("recovery_requests", J::U(v.recovery_requests)),
|
|
("elementary_stream_frames", J::U(u64::from(v.es_frames))),
|
|
("elementary_stream_bytes", J::U(v.es_bytes)),
|
|
("dumped_packets", J::U(u64::from(s.video_dump.written))),
|
|
]),
|
|
),
|
|
(
|
|
"audio",
|
|
J::O(vec![
|
|
("datagrams", J::U(s.a.datagrams)),
|
|
("bytes", J::U(s.a.bytes)),
|
|
("first_packet_ms", s.a.first_at_ms.map_or(J::Null, J::F)),
|
|
("first_from", s.a.first_from.map_or(J::Null, |a| J::s(a.to_string()))),
|
|
("data_packets", J::U(s.a.data)),
|
|
("parity_packets", J::U(s.a.parity)),
|
|
("parse_errors", J::U(s.a.parse_errors)),
|
|
(
|
|
"payload_lengths",
|
|
J::A(s.a.payload_lens.iter().map(|(k, n)| J::A(vec![J::U(*k as u64), J::U(*n)])).collect()),
|
|
),
|
|
("u17_decrypting", J::dbg(&ad)),
|
|
("u17_plain", J::dbg(&ap)),
|
|
("lost_decrypting", J::U(s.a.lost_decrypting)),
|
|
("lost_plain", J::U(s.a.lost_plain)),
|
|
("fec_recovered", J::U(ad.recovered)),
|
|
(
|
|
"fec_note",
|
|
J::s("audio FEC recovery is off until U16 is solved (solve-audio-fec on audio-packets.bin)"),
|
|
),
|
|
("dumped_packets", J::U(u64::from(s.audio_dump.written))),
|
|
]),
|
|
),
|
|
(
|
|
"control",
|
|
J::O(vec![
|
|
("state", J::dbg(&s.enet.state())),
|
|
("connected_at_ms", s.c.connected_at_ms.map_or(J::Null, J::F)),
|
|
("round_trip", J::dbg(&s.enet.round_trip_time())),
|
|
("datagrams_sent", J::U(u64::from(s.c.sent_datagrams))),
|
|
("datagrams_received", J::U(u64::from(s.c.received_datagrams))),
|
|
("enet_errors", J::U(s.c.enet_errors)),
|
|
(
|
|
"sent",
|
|
J::A(
|
|
s.c.sent
|
|
.iter()
|
|
.take(32)
|
|
.map(|(n, q)| J::A(vec![J::s(n.clone()), J::U(u64::from(*q))]))
|
|
.collect(),
|
|
),
|
|
),
|
|
(
|
|
"host_messages",
|
|
J::A(
|
|
s.c.host_messages
|
|
.iter()
|
|
.map(|(t, n)| J::A(vec![J::s(format!("{t:#06x}")), J::U(*n)]))
|
|
.collect(),
|
|
),
|
|
),
|
|
("host_frames_failed", J::U(s.c.host_frames_failed)),
|
|
("host_sequence_first_u11", s.c.first_host_sequence.map_or(J::Null, |q| J::U(u64::from(q)))),
|
|
("host_sequence_last", s.c.last_host_sequence.map_or(J::Null, |q| J::U(u64::from(q)))),
|
|
("host_sequence_not_increasing", J::U(s.c.host_replays)),
|
|
("ended", s.c.ended.as_ref().map_or(J::Null, |e| J::s(e.clone()))),
|
|
]),
|
|
),
|
|
("pings", J::U(s.pings)),
|
|
("foreign_datagrams", J::U(s.foreign)),
|
|
("socket_errors", J::A(s.socket_errors.iter().map(|(k, n)| J::A(vec![J::s(k.clone()), J::U(*n)])).collect())),
|
|
])
|
|
}
|
|
|
|
fn stream_config(o: &Options) -> StreamConfig {
|
|
StreamConfig {
|
|
width: o.width,
|
|
height: o.height,
|
|
fps: o.fps,
|
|
bitrate_kbps: o.bitrate_kbps,
|
|
packet_size: o.packet_size,
|
|
codec: o.codec,
|
|
hdr: o.hdr,
|
|
audio: o.audio,
|
|
audio_packet_duration_ms: o.audio_ms,
|
|
min_fec_packets: o.min_fec,
|
|
reference_frame_invalidation: o.rfi,
|
|
encryption: EncryptionFlags(o.encryption),
|
|
}
|
|
}
|
|
|
|
/// `probe launch <app-id>`.
|
|
pub fn launch(ctx: &mut Ctx, app_id: u32) -> Result<(), String> {
|
|
let opts = ctx.opts.clone();
|
|
let keys = SessionKeys::generate(&mut ctx.rng).map_err(|e| e.to_string())?;
|
|
ctx.log.register_secret(&keys.rikey);
|
|
ctx.log.note("launch.keys", &["U4"], format!("fresh session keys: {keys:?} (rikey never logged)"));
|
|
let params = LaunchParams {
|
|
app_id,
|
|
width: opts.width,
|
|
height: opts.height,
|
|
fps: opts.fps,
|
|
keys: keys.clone(),
|
|
hdr: opts.hdr,
|
|
audio: opts.audio,
|
|
};
|
|
let req = launch_request(¶ms, &ctx.id.unique_id).map_err(|e| e.to_string())?;
|
|
let x = ctx.http("launch", &["U4", "U24", "U27"], &req, None)?;
|
|
let launched = match parse_launch_response(&x.response.body) {
|
|
Ok(l) => l,
|
|
Err(e) => {
|
|
ctx.log.parse_error("launch", &["U4", "U27"], &e, crate::body_j(&x.response.body));
|
|
ctx.log.stop("launch", &["U4"], format!("launch answer refused: {e}"), J::Null);
|
|
return Err(format!("launch answer refused: {e}"));
|
|
}
|
|
};
|
|
ctx.log.record("launch", Kind::Note, &["U4"], J::dbg(&launched));
|
|
println!("launch: gamesession={} sessionUrl0={:?}", launched.game_session, launched.session_url);
|
|
if !launched.game_session {
|
|
ctx.log.stop("launch", &["U4"], "the host did not start a game session (gamesession != 1)", J::Null);
|
|
return Err("no game session".into());
|
|
}
|
|
let target = rtsp::target(launched.session_url.as_deref(), ctx.host, ctx.connect)
|
|
.inspect_err(|e| ctx.log.stop("launch", &["U4"], e.clone(), J::Null))?;
|
|
if target.assumed_port {
|
|
ctx.log.note("rtsp.target", &["U4"], "no sessionUrl0: assuming port 48010 of the host");
|
|
}
|
|
if let Some(f) = &target.foreign_host {
|
|
ctx.log.note(
|
|
"rtsp.target",
|
|
&["U4"],
|
|
format!("sessionUrl0 names {f}; the probe still connects only to {}", target.addr),
|
|
);
|
|
}
|
|
let stream = rtsp::negotiate(&mut ctx.log, &target, stream_config(&opts))?;
|
|
ctx.log.record("rtsp.ready", Kind::Recv, &["U5", "U6", "U7", "U26"], J::dbg(&stream));
|
|
println!(
|
|
"rtsp: ports video {} audio {} control {}, encryption {:#x}",
|
|
stream.ports.video, stream.ports.audio, stream.ports.control, stream.encryption.0
|
|
);
|
|
run_streams(ctx, &opts, &keys, stream)
|
|
}
|
|
|
|
fn run_streams(ctx: &mut Ctx, opts: &Options, keys: &SessionKeys, stream: NegotiatedStream) -> Result<(), String> {
|
|
let host = ctx.connect;
|
|
let socks = (|| -> io::Result<_> { Ok((bind(opts, host)?, bind(opts, host)?, bind(opts, host)?)) })()
|
|
.map_err(|e| format!("UDP sockets: {e}"))?;
|
|
let (video_sock, audio_sock, control_sock) = socks;
|
|
for (name, s) in [("video", &video_sock), ("audio", &audio_sock), ("control", &control_sock)] {
|
|
ctx.log.note(
|
|
"socket",
|
|
&["U8"],
|
|
format!("{name} socket on {}", s.local_addr().map_or_else(|e| e.to_string(), |a| a.to_string())),
|
|
);
|
|
}
|
|
let stop = Arc::new(AtomicBool::new(false));
|
|
let (tx, rx) = mpsc::channel();
|
|
let mut threads = Vec::new();
|
|
for (src, s) in [(Src::Video, &video_sock), (Src::Audio, &audio_sock), (Src::Control, &control_sock)] {
|
|
let s = s.try_clone().map_err(|e| format!("UDP socket clone: {e}"))?;
|
|
let (tx, stop) = (tx.clone(), Arc::clone(&stop));
|
|
threads.push(thread::spawn(move || reader(src, s, tx, stop)));
|
|
}
|
|
drop(tx);
|
|
let epoch = ctx.epoch;
|
|
let enc = stream.encryption;
|
|
let video_cipher = enc.contains(EncryptionFlags::VIDEO).then(|| VideoCipher::new(keys.rikey));
|
|
let video = VideoDepacketizer::new(VideoConfig {
|
|
packet_size: opts.packet_size,
|
|
cipher: video_cipher.clone(),
|
|
frame_timeout: Duration::from_millis(150),
|
|
})
|
|
.map_err(|e| format!("video receiver: {e}"))?;
|
|
let audio = |cipher| {
|
|
AudioDepacketizer::new(AudioConfig {
|
|
cipher,
|
|
packet_duration_ms: opts.audio_ms,
|
|
fec: AudioFec::Disabled,
|
|
loss_timeout: Duration::from_millis(60),
|
|
})
|
|
.map_err(|e| format!("audio receiver: {e}"))
|
|
};
|
|
let enet = EnetClient::connect(
|
|
EnetConfig {
|
|
channel_count: opts.enet_channels,
|
|
mtu: opts.enet_mtu,
|
|
connect_data: opts.enet_connect_data,
|
|
ping_interval: Duration::from_millis(500),
|
|
timeout: Duration::from_secs(10),
|
|
},
|
|
ds(epoch, StdInstant::now()),
|
|
&mut ctx.rng,
|
|
)
|
|
.map_err(|e| format!("ENet: {e}"))?;
|
|
let es = if opts.dump_frames > 0 {
|
|
let p = ctx.run_dir.join(format!("video.{}", codec_ext(opts.codec)));
|
|
Some(BufWriter::new(
|
|
File::options().write(true).create_new(true).open(&p).map_err(|e| format!("{}: {e}", p.display()))?,
|
|
))
|
|
} else {
|
|
None
|
|
};
|
|
let video_dump =
|
|
PacketDump::create(&ctx.run_dir.join("video-packets.bin"), opts.dump_packets).map_err(|e| e.to_string())?;
|
|
let audio_dump =
|
|
PacketDump::create(&ctx.run_dir.join("audio-packets.bin"), opts.dump_packets).map_err(|e| e.to_string())?;
|
|
let mut s = Session {
|
|
log: &mut ctx.log,
|
|
epoch,
|
|
host,
|
|
control_addr: SocketAddr::new(host, stream.ports.control),
|
|
stream,
|
|
opts: opts.clone(),
|
|
video_sock,
|
|
audio_sock,
|
|
control_sock,
|
|
enet,
|
|
cipher: ControlCipher::new(keys.rikey),
|
|
next_sequence: opts.first_control_seq,
|
|
video,
|
|
video_cipher,
|
|
audio_decrypting: audio(Some(AudioCipher::new(keys)))?,
|
|
audio_plain: audio(None)?,
|
|
v: VideoCounters::default(),
|
|
a: AudioCounters::default(),
|
|
c: ControlCounters::default(),
|
|
es,
|
|
video_dump,
|
|
audio_dump,
|
|
fec_check: VideoFecCheck::new(CHECKED_BLOCKS),
|
|
pings: 0,
|
|
next_ping: StdInstant::now(),
|
|
next_periodic: None,
|
|
last_recovery: None,
|
|
nudged: false,
|
|
foreign: 0,
|
|
socket_errors: BTreeMap::new(),
|
|
};
|
|
println!("streams: receiving for {} s ...", opts.seconds);
|
|
let started = StdInstant::now();
|
|
let deadline = started + Duration::from_secs(u64::from(opts.seconds));
|
|
s.tick();
|
|
loop {
|
|
let now = StdInstant::now();
|
|
if now >= deadline || s.c.ended.is_some() {
|
|
break;
|
|
}
|
|
let wait = s.next_due(deadline).saturating_duration_since(now).min(Duration::from_millis(50));
|
|
match rx.recv_timeout(wait) {
|
|
Ok(m) => {
|
|
s.dispatch(m);
|
|
// Take what is queued before the timers run again.
|
|
while let Ok(m) = rx.try_recv() {
|
|
s.dispatch(m);
|
|
}
|
|
}
|
|
Err(mpsc::RecvTimeoutError::Timeout) => {}
|
|
Err(mpsc::RecvTimeoutError::Disconnected) => break,
|
|
}
|
|
s.tick();
|
|
}
|
|
// Graceful end of the control stream; then a short drain for its acknowledgement.
|
|
if s.enet.state() == EnetState::Connected {
|
|
let now = s.now();
|
|
if s.enet.disconnect(now, 0).is_ok() {
|
|
s.flush_control(now);
|
|
let until = StdInstant::now() + Duration::from_millis(500);
|
|
while StdInstant::now() < until && s.enet.state() != EnetState::Disconnected {
|
|
if let Ok(Msg::Datagram { src: Src::Control, at, bytes: d, .. }) =
|
|
rx.recv_timeout(Duration::from_millis(50))
|
|
{
|
|
s.on_control(at, &d);
|
|
s.flush_control(ds(epoch, at));
|
|
}
|
|
}
|
|
}
|
|
}
|
|
stop.store(true, Ordering::Relaxed);
|
|
if let Some(w) = &mut s.es {
|
|
let _ = w.flush();
|
|
}
|
|
let _ = s.video_dump.finish();
|
|
let _ = s.audio_dump.finish();
|
|
let seconds = started.elapsed().as_secs_f64();
|
|
let sum = summary(&s, seconds);
|
|
let ended = s.c.ended.clone();
|
|
let (frames, ready, lost, rec) = (s.v.frames, s.v.decode_ready, s.v.frames_lost, s.v.recovered_shards);
|
|
let (apk, alost_dec, alost_plain) = (s.a.data, s.a.lost_decrypting, s.a.lost_plain);
|
|
let (ad, ap) = (s.audio_decrypting.stats(), s.audio_plain.stats());
|
|
let host_msgs: u64 = s.c.host_messages.values().sum();
|
|
let (u14, u14_whole) = (s.fec_check.checked, s.fec_check.whole);
|
|
let audio_dump_written = s.audio_dump.written;
|
|
drop(s);
|
|
for t in threads {
|
|
let _ = t.join();
|
|
}
|
|
ctx.log.record(
|
|
"launch.summary",
|
|
Kind::Summary,
|
|
&["U8", "U9", "U10", "U11", "U13", "U14", "U15", "U17", "U19", "U29"],
|
|
sum,
|
|
);
|
|
println!("video: {frames} frames ({ready} decode-ready), {lost} lost, {rec} shards recovered by FEC");
|
|
println!(
|
|
"audio: {apk} data packets; decrypting receiver {} ok / {} refused, plain receiver {} ok / {} refused; lost {alost_dec} / {alost_plain}",
|
|
ad.packets, ad.packets_dropped, ap.packets, ap.packets_dropped
|
|
);
|
|
println!("control: {host_msgs} host messages; U14 blocks checked {u14}, whole-packet parity matched {u14_whole}");
|
|
if let Some(e) = &ended {
|
|
println!("control ended early: {e}");
|
|
}
|
|
if audio_dump_written > 0 {
|
|
match crate::solve_audio_file(&ctx.run_dir.join("audio-packets.bin")) {
|
|
Ok(r) => ctx.log.record("audio.u16", Kind::Summary, &["U16"], r),
|
|
Err(e) => ctx.log.note("audio.u16", &["U16"], format!("not solved: {e}")),
|
|
}
|
|
}
|
|
if frames == 0 {
|
|
ctx.log.stop("launch.summary", &["U8", "U10"], "no video frame arrived", J::Null);
|
|
} else if apk == 0 {
|
|
ctx.log.stop("launch.summary", &["U8", "U17"], "no audio packet arrived", J::Null);
|
|
} else if ended.is_some() {
|
|
ctx.log.stop(
|
|
"launch.summary",
|
|
&["U9", "U10"],
|
|
format!("the control stream ended early: {}", ended.unwrap_or_default()),
|
|
J::Null,
|
|
);
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
#[test]
|
|
fn raw_messages_have_type_and_length() {
|
|
assert_eq!(raw_message(START_B, &[]).unwrap(), vec![0x07, 0x03, 0x00, 0x00]);
|
|
assert_eq!(raw_message(PERIODIC_PING, &[0xAA, 0xBB]).unwrap(), vec![0x00, 0x02, 0x02, 0x00, 0xAA, 0xBB]);
|
|
assert!(raw_message(IDR_REQUEST, &vec![0; 70_000]).is_none());
|
|
}
|
|
|
|
/// The U10 candidates the probe sends by default, as plaintext messages: a bare 4-byte header each, which is
|
|
/// what Moonshine's parser accepts (length field = bytes after the header).
|
|
#[test]
|
|
fn default_candidates_are_bare_headers() {
|
|
let o = Options::default();
|
|
let cases = [
|
|
(START_A, &o.start_a, [0x05, 0x03, 0x00, 0x00]),
|
|
(START_B, &o.start_b, [0x07, 0x03, 0x00, 0x00]),
|
|
(PERIODIC_PING, &o.periodic_ping, [0x00, 0x02, 0x00, 0x00]),
|
|
(IDR_REQUEST, &o.idr, [0x02, 0x03, 0x00, 0x00]),
|
|
];
|
|
for (t, body, want) in cases {
|
|
let m = raw_message(t, body_of(body).unwrap()).unwrap();
|
|
assert_eq!(m, want);
|
|
let parsed = parse_message(&m).unwrap();
|
|
assert_eq!((parsed.message_type, parsed.body.len()), (t, 0));
|
|
}
|
|
}
|
|
|
|
/// Sealed with a test key, each candidate is the documented encrypted frame (PROTOCOL.md 3.2): type 0x0001,
|
|
/// length 4 + 16 + 4, the sequence LE, tag, 4 bytes of ciphertext; the nonce is Moonshine's client-to-host IV
|
|
/// (sequence LE, six zeros, 'C', 'C').
|
|
#[test]
|
|
fn sealed_candidates_follow_the_frame_layout() {
|
|
use domistream::control::frame::nonce;
|
|
let cipher = ControlCipher::new([0x11; 16]);
|
|
for (seq, t) in [(0u32, START_A), (1, START_B), (2, PERIODIC_PING), (0x0102_0304, IDR_REQUEST)] {
|
|
let plain = raw_message(t, &[]).unwrap();
|
|
let frame = cipher.seal(seq, Direction::ClientToHost, &plain).unwrap();
|
|
assert_eq!(frame.len(), 28);
|
|
assert_eq!(frame[..4], [0x01, 0x00, 24, 0x00]);
|
|
assert_eq!(frame[4..8], seq.to_le_bytes());
|
|
assert_eq!(cipher.open(Direction::ClientToHost, &frame).unwrap(), (seq, plain));
|
|
let mut iv = [0u8; 12];
|
|
iv[..4].copy_from_slice(&seq.to_le_bytes());
|
|
iv[10] = b'C';
|
|
iv[11] = b'C';
|
|
assert_eq!(nonce(seq, Direction::ClientToHost).unwrap(), iv);
|
|
}
|
|
}
|
|
|
|
/// The crate's INVALIDATE_REF_FRAMES (sent with --rfi) puts `first` and `last` where Moonshine reads them:
|
|
/// message bytes 4..8 and 12..16, little-endian.
|
|
#[test]
|
|
fn invalidate_ref_frames_layout() {
|
|
let m = encode_client_message(&ClientMessage::InvalidateRefFrames { first: 7, last: 0x0A0B_0C0D }).unwrap();
|
|
assert_eq!(m[..2], [0x01, 0x03]);
|
|
assert_eq!(m[4..8], 7u32.to_le_bytes());
|
|
assert_eq!(m[12..16], 0x0A0B_0C0Du32.to_le_bytes());
|
|
}
|
|
|
|
#[test]
|
|
fn clock_conversions_round_trip() {
|
|
let epoch = StdInstant::now();
|
|
let at = epoch + Duration::from_micros(1_234_567);
|
|
let d = ds(epoch, at);
|
|
assert_eq!(d.as_micros(), 1_234_567);
|
|
assert_eq!(std_at(epoch, d), at);
|
|
assert_eq!(ds(at, epoch).as_micros(), 0);
|
|
}
|
|
|
|
#[test]
|
|
fn stream_config_follows_the_options() {
|
|
let o = Options { encryption: 3, rfi: true, ..Options::default() };
|
|
let c = stream_config(&o);
|
|
assert_eq!((c.width, c.fps, c.packet_size, c.encryption.0), (1920, 60, 1024, 3));
|
|
assert!(c.reference_frame_invalidation);
|
|
}
|
|
}
|