//! The command line. Strict: an unknown option, a missing value or a value out of range is refused, never guessed. use std::net::IpAddr; use std::path::PathBuf; use domistream::http::launch::AudioLayout; use domistream::rtsp::client::VideoCodec; pub const USAGE: &str = "\ usage: probe --host --out [options] commands: serverinfo GET /serverinfo over HTTP (and HTTPS once paired) pair pair this probe: prints a 4-digit PIN for the operator to submit through Sunshine's API apps GET /applist (HTTPS) launch launch, RTSP, ENet control, then receive video + audio for --seconds quit GET /cancel (HTTPS): quits the running app unpair GET /unpair (HTTPS): the host forgets this probe solve-audio-fec offline: solve the audio parity matrix (U16) from a launch run's audio-packets.bin common options: --host the ONE host address; every socket goes there (or to --relay) --out identity (test-only key and cert), runs/-/log.jsonl and dumps --http-port 47989 --https-port 47984 --relay connect to tools/lab-relay on this loopback address instead (same ports) --bind local address for the UDP sockets (default: unspecified) --name device name sent while pairing and certificate CN (default: DomiStream probe) pair: --wrong-pin print one PIN but use another (U28: what the host does after a failed pairing) launch: --mode 1920x1080x60 --bitrate 20000 --packet-size 1024 --codec h264|hevc|av1 h264 --hdr --audio stereo|5.1|7.1 --audio-ms 5 --min-fec 2 --rfi (ask for reference frame invalidation) --encryption <0-7> 7 (bits: 1 control V2, 2 video, 4 audio) --seconds 20 (1-600) --dump-frames 120 --dump-packets 3000 --ping-ms 500 (UDP ping to the video and audio ports) --enet-channels 1 --enet-mtu 1392 --enet-connect-data 0 --control-channel 0 --first-control-seq 0 Control message bodies (U10; defaults from Moonshine, which reads no body from any of them, PROTOCOL.md 3.3): --start-a empty --start-b empty --periodic-ping empty --periodic-ping-ms 500 --idr empty (IDR request on frame loss, unless --rfi and the host offers invalidation) --nudge-mouse send one relative mouse move +1/-1 after the first decodable frame "; /// What to do. #[derive(Clone, Debug, PartialEq, Eq)] pub enum Command { ServerInfo, Pair, Apps, Launch { app_id: u32 }, Quit, Unpair, SolveAudioFec { dump: PathBuf }, } impl Command { /// The short name used in run folder names and the log. pub const fn name(&self) -> &'static str { match self { Self::ServerInfo => "serverinfo", Self::Pair => "pair", Self::Apps => "apps", Self::Launch { .. } => "launch", Self::Quit => "quit", Self::Unpair => "unpair", Self::SolveAudioFec { .. } => "solve-audio-fec", } } /// Whether the command talks to the host (and so needs `--host` and `--out`). pub const fn is_network(&self) -> bool { !matches!(self, Self::SolveAudioFec { .. }) } } /// A control message body from the command line: skip the message, send it empty, or send these bytes. #[derive(Clone, Debug, PartialEq, Eq)] pub enum Body { None, Bytes(Vec), } /// Every option, with its default. #[derive(Clone, Debug, PartialEq, Eq)] pub struct Options { pub host: Option, pub out: Option, pub http_port: u16, pub https_port: u16, pub relay: Option, pub bind: Option, pub name: String, pub wrong_pin: bool, pub width: u32, pub height: u32, pub fps: u32, pub bitrate_kbps: u32, pub packet_size: u16, pub codec: VideoCodec, pub hdr: bool, pub audio: AudioLayout, pub audio_ms: u8, pub min_fec: u8, pub rfi: bool, pub encryption: u8, pub seconds: u32, pub dump_frames: u32, pub dump_packets: u32, pub ping_ms: u32, pub enet_channels: u8, pub enet_mtu: u16, pub enet_connect_data: u32, pub control_channel: u8, pub first_control_seq: u32, pub start_a: Body, pub start_b: Body, pub periodic_ping: Body, pub periodic_ping_ms: u32, pub idr: Body, pub nudge_mouse: bool, } impl Default for Options { fn default() -> Self { Self { host: None, out: None, http_port: domistream::http::DEFAULT_HTTP_PORT, https_port: domistream::http::DEFAULT_HTTPS_PORT, relay: None, bind: None, name: "DomiStream probe".to_owned(), wrong_pin: false, width: 1920, height: 1080, fps: 60, bitrate_kbps: 20_000, packet_size: 1024, codec: VideoCodec::H264, hdr: false, audio: AudioLayout::Stereo, audio_ms: 5, min_fec: 2, rfi: false, encryption: 7, seconds: 20, dump_frames: 120, dump_packets: 3000, ping_ms: 500, enet_channels: 1, enet_mtu: 1392, enet_connect_data: 0, control_channel: 0, first_control_seq: 0, start_a: Body::Bytes(Vec::new()), start_b: Body::Bytes(Vec::new()), periodic_ping: Body::Bytes(Vec::new()), periodic_ping_ms: 500, idr: Body::Bytes(Vec::new()), nudge_mouse: false, } } } impl Options { /// The address every socket connects to: the relay when one is given, else the host. pub fn connect_ip(&self) -> Option { self.relay.or(self.host) } } /// A parsed command line. #[derive(Clone, Debug, PartialEq, Eq)] pub struct Invocation { pub command: Command, pub options: Options, } /// Largest control message body accepted from the command line. pub const MAX_BODY_BYTES: usize = 1024; fn number(name: &str, v: &str) -> Result { v.parse().map_err(|_| format!("{name}: '{v}' is not a valid number")) } fn ranged( name: &str, v: &str, min: T, max: T, ) -> Result { let n: T = number(name, v)?; if n < min || n > max { return Err(format!("{name}: {n} is outside {min}..={max}")); } Ok(n) } /// `hex`, `empty` or `none` (when `allow_none`). pub fn parse_body(name: &str, v: &str, allow_none: bool) -> Result { match v { "none" if allow_none => Ok(Body::None), "empty" => Ok(Body::Bytes(Vec::new())), _ => parse_hex(v).map(Body::Bytes).map_err(|e| format!("{name}: {e}")), } } /// Hex digits, upper or lower case, optionally separated by spaces, colons or dashes; at most [`MAX_BODY_BYTES`]. pub fn parse_hex(v: &str) -> Result, String> { let digits: Vec = v.bytes().filter(|b| !matches!(b, b' ' | b':' | b'-')).collect(); if digits.is_empty() || !digits.len().is_multiple_of(2) { return Err(format!("'{v}' is not an even number of hex digits")); } if digits.len() / 2 > MAX_BODY_BYTES { return Err(format!("more than {MAX_BODY_BYTES} bytes")); } let nibble = |b: u8| match b { b'0'..=b'9' => Ok(b - b'0'), b'a'..=b'f' => Ok(b - b'a' + 10), b'A'..=b'F' => Ok(b - b'A' + 10), _ => Err(format!("'{v}' holds a non-hex character")), }; digits.chunks(2).map(|p| Ok((nibble(p[0])? << 4) | nibble(p[1])?)).collect() } /// `WxHxFPS`, each part non-zero. pub fn parse_mode(v: &str) -> Result<(u32, u32, u32), String> { let parts: Vec<&str> = v.split('x').collect(); let [w, h, f] = parts.as_slice() else { return Err(format!("--mode: '{v}' is not WxHxFPS")) }; Ok((ranged("--mode width", w, 1, 8192)?, ranged("--mode height", h, 1, 8192)?, ranged("--mode fps", f, 1, 480)?)) } fn ip(name: &str, v: &str) -> Result { v.parse().map_err(|_| format!("{name}: '{v}' is not an IP address (names are not resolved)")) } /// Parses the arguments after the program name. pub fn parse(args: &[String]) -> Result { let mut it = args.iter(); let command = match it.next().map(String::as_str) { Some("serverinfo") => Command::ServerInfo, Some("pair") => Command::Pair, Some("apps") => Command::Apps, Some("launch") => { let id = it.next().ok_or("launch: needs an app id")?; Command::Launch { app_id: number("launch ", id)? } } Some("quit") => Command::Quit, Some("unpair") => Command::Unpair, Some("solve-audio-fec") => { let file = it.next().ok_or("solve-audio-fec: needs a file")?; Command::SolveAudioFec { dump: PathBuf::from(file) } } Some(other) => return Err(format!("unknown command '{other}'")), None => return Err("no command".into()), }; let mut o = Options::default(); while let Some(flag) = it.next() { let mut value = || it.next().map(String::as_str).ok_or(format!("{flag}: needs a value")); match flag.as_str() { "--host" => o.host = Some(ip(flag, value()?)?), "--out" => o.out = Some(PathBuf::from(value()?)), "--http-port" => o.http_port = ranged(flag, value()?, 1, 65535)?, "--https-port" => o.https_port = ranged(flag, value()?, 1, 65535)?, "--relay" => { let r = ip(flag, value()?)?; if !r.is_loopback() { return Err(format!( "--relay: {r} is not a loopback address (tools/lab-relay runs on loopback only)" )); } o.relay = Some(r); } "--bind" => o.bind = Some(ip(flag, value()?)?), "--name" => { let n = value()?; if n.is_empty() || n.len() > 64 || n.chars().any(char::is_control) { return Err("--name: 1-64 characters, no control characters".into()); } o.name = n.to_owned(); } "--wrong-pin" => o.wrong_pin = true, "--mode" => (o.width, o.height, o.fps) = parse_mode(value()?)?, "--bitrate" => o.bitrate_kbps = ranged(flag, value()?, 500, 500_000)?, "--packet-size" => o.packet_size = ranged(flag, value()?, 64, 4000)?, "--codec" => { o.codec = match value()? { "h264" => VideoCodec::H264, "hevc" => VideoCodec::Hevc, "av1" => VideoCodec::Av1, v => return Err(format!("--codec: '{v}' is not h264, hevc or av1")), } } "--hdr" => o.hdr = true, "--audio" => { o.audio = match value()? { "stereo" => AudioLayout::Stereo, "5.1" => AudioLayout::Surround51, "7.1" => AudioLayout::Surround71, v => return Err(format!("--audio: '{v}' is not stereo, 5.1 or 7.1")), } } "--audio-ms" => o.audio_ms = ranged(flag, value()?, 1, 100)?, "--min-fec" => o.min_fec = ranged(flag, value()?, 0, 64)?, "--rfi" => o.rfi = true, "--encryption" => o.encryption = ranged(flag, value()?, 0, 7)?, "--seconds" => o.seconds = ranged(flag, value()?, 1, 600)?, "--dump-frames" => o.dump_frames = ranged(flag, value()?, 0, 100_000)?, "--dump-packets" => o.dump_packets = ranged(flag, value()?, 0, 1_000_000)?, "--ping-ms" => o.ping_ms = ranged(flag, value()?, 10, 10_000)?, "--enet-channels" => o.enet_channels = ranged(flag, value()?, 1, 255)?, "--enet-mtu" => o.enet_mtu = ranged(flag, value()?, 576, 4096)?, "--enet-connect-data" => o.enet_connect_data = number(flag, value()?)?, "--control-channel" => o.control_channel = number(flag, value()?)?, "--first-control-seq" => o.first_control_seq = number(flag, value()?)?, "--start-a" => o.start_a = parse_body(flag, value()?, true)?, "--start-b" => o.start_b = parse_body(flag, value()?, true)?, "--periodic-ping" => o.periodic_ping = parse_body(flag, value()?, true)?, "--periodic-ping-ms" => o.periodic_ping_ms = ranged(flag, value()?, 10, 10_000)?, "--idr" => o.idr = parse_body(flag, value()?, true)?, "--nudge-mouse" => o.nudge_mouse = true, other => return Err(format!("unknown option '{other}'")), } } if o.control_channel >= o.enet_channels { return Err(format!( "--control-channel {} needs --enet-channels above it (now {})", o.control_channel, o.enet_channels )); } if command.is_network() { if o.host.is_none() { return Err(format!("{}: --host is required", command.name())); } if o.out.is_none() { return Err(format!("{}: --out is required", command.name())); } } Ok(Invocation { command, options: o }) } #[cfg(test)] mod tests { use super::*; fn args(s: &str) -> Vec { s.split_whitespace().map(str::to_owned).collect() } fn ok(s: &str) -> Invocation { parse(&args(s)).unwrap() } fn err(s: &str) -> String { parse(&args(s)).unwrap_err() } #[test] fn network_commands_need_host_and_out() { assert!(err("serverinfo --out x").contains("--host")); assert!(err("serverinfo --host 192.168.100.140").contains("--out")); let i = ok("serverinfo --host 192.168.100.140 --out F:/x"); assert_eq!(i.command, Command::ServerInfo); assert_eq!(i.options.host, Some("192.168.100.140".parse().unwrap())); assert_eq!(i.options.connect_ip(), i.options.host); } #[test] fn defaults_are_the_documented_ones() { let o = ok("pair --host 127.0.0.1 --out o").options; assert_eq!((o.http_port, o.https_port), (47989, 47984)); assert_eq!((o.width, o.height, o.fps, o.bitrate_kbps, o.packet_size), (1920, 1080, 60, 20_000, 1024)); assert_eq!((o.encryption, o.seconds, o.enet_channels, o.enet_mtu), (7, 20, 1, 1392)); assert_eq!(o.start_a, Body::Bytes(vec![])); // U10 candidates (PROTOCOL.md 3.3): every body empty, a ping every 500 ms. assert_eq!( (o.start_b, o.periodic_ping, o.idr), (Body::Bytes(vec![]), Body::Bytes(vec![]), Body::Bytes(vec![])) ); assert_eq!(o.periodic_ping_ms, 500); assert!(!o.wrong_pin && !o.nudge_mouse && !o.rfi); } #[test] fn launch_needs_a_numeric_app_id() { assert!(err("launch").contains("app id")); assert!(err("launch --host 1.2.3.4 --out o").contains("not a valid number")); assert!(err("launch abc --host 1.2.3.4 --out o").contains("not a valid number")); assert_eq!(ok("launch 881448767 --host 1.2.3.4 --out o").command, Command::Launch { app_id: 881_448_767 }); } #[test] fn host_names_and_unknown_options_are_refused() { assert!(err("apps --host my-pc --out o").contains("not an IP address")); assert!(err("apps --host 1.2.3.4 --out o --verbose").contains("unknown option")); assert!(err("apps --host 1.2.3.4 --out").contains("needs a value")); assert!(err("dance").contains("unknown command")); assert!(err("").contains("no command")); } #[test] fn relay_must_be_loopback() { assert!(err("apps --host 192.168.100.140 --out o --relay 192.168.100.2").contains("loopback")); let o = ok("apps --host 192.168.100.140 --out o --relay 127.0.0.1").options; assert_eq!(o.connect_ip(), Some("127.0.0.1".parse().unwrap())); } #[test] fn launch_options_parse_and_are_ranged() { let o = ok("launch 1 --host ::1 --out o --mode 1280x720x30 --codec hevc --audio 5.1 --seconds 600 \ --start-b 0a0B --start-a none --idr none --enet-channels 48 --control-channel 47 --hdr --rfi") .options; assert_eq!((o.width, o.height, o.fps), (1280, 720, 30)); assert_eq!((o.codec, o.audio), (VideoCodec::Hevc, AudioLayout::Surround51)); assert_eq!((o.start_a, o.start_b, o.idr), (Body::None, Body::Bytes(vec![0x0a, 0x0b]), Body::None)); assert!(o.hdr && o.rfi); assert!(err("launch 1 --host ::1 --out o --seconds 601").contains("outside")); assert!(err("launch 1 --host ::1 --out o --encryption 8").contains("outside")); assert!(err("launch 1 --host ::1 --out o --mode 1920x1080").contains("WxHxFPS")); assert!(err("launch 1 --host ::1 --out o --mode 0x1080x60").contains("outside")); assert!(err("launch 1 --host ::1 --out o --control-channel 1").contains("--enet-channels")); assert!(err("launch 1 --host ::1 --out o --codec vp9").contains("h264")); } #[test] fn hex_bodies() { assert_eq!(parse_hex("00 ff:A0-0b").unwrap(), vec![0x00, 0xff, 0xa0, 0x0b]); assert!(parse_hex("abc").is_err()); assert!(parse_hex("zz").is_err()); assert!(parse_hex("").is_err()); assert!(parse_hex(&"00".repeat(MAX_BODY_BYTES + 1)).is_err()); assert_eq!(parse_body("x", "none", true).unwrap(), Body::None); assert!(parse_body("x", "none", false).is_err()); } #[test] fn solve_audio_fec_is_offline() { let i = ok("solve-audio-fec F:/runs/a/audio-packets.bin"); assert_eq!(i.command, Command::SolveAudioFec { dump: PathBuf::from("F:/runs/a/audio-packets.bin") }); assert!(!i.command.is_network()); } #[test] fn device_name_is_checked() { assert!(err("pair --host 1.2.3.4 --out o --name").contains("needs a value")); let long = format!("pair --host 1.2.3.4 --out o --name {}", "n".repeat(65)); assert!(err(&long).contains("1-64")); } }