Skip to main content

moqros_cli/
args.rs

1//! Flags shared by the bridge binaries.
2
3use std::path::PathBuf;
4use std::time::Duration;
5
6use clap::builder::BoolishValueParser;
7use clap::{ArgAction, Args, ValueEnum};
8use moqros::ros::QosProfile;
9
10use crate::url::{insecurity, redact_url};
11
12/// Relay connection flags.
13#[derive(Debug, Clone, Args)]
14pub struct RelayArgs {
15	/// Relay URL; its path scopes broadcast names.
16	#[arg(long, env = "MOQROS_URL", default_value = "http://localhost:4443/anon")]
17	pub url: moqros::Url,
18
19	/// Disable TLS certificate verification (development only).
20	#[arg(long, env = "MOQROS_INSECURE", action = ArgAction::Set, value_parser = BoolishValueParser::new(),
21		num_args = 0..=1, require_equals = true, default_value_t = false, default_missing_value = "true")]
22	pub insecure: bool,
23
24	/// PEM client certificate chain to present to the relay (mTLS).
25	#[arg(long, env = "MOQROS_TLS_CERT", requires = "tls_key")]
26	pub tls_cert: Option<PathBuf>,
27
28	/// PEM private key of `--tls-cert`.
29	#[arg(long, env = "MOQROS_TLS_KEY", requires = "tls_cert")]
30	pub tls_key: Option<PathBuf>,
31}
32
33impl RelayArgs {
34	pub fn config(&self) -> moqros::ClientConfig {
35		moqros::ClientConfig {
36			url: self.url.clone(),
37			insecure: self.insecure,
38			tls_cert: self.tls_cert.clone(),
39			tls_key: self.tls_key.clone(),
40		}
41	}
42
43	/// The relay URL with its tokens and password hidden, for logging.
44	pub fn redacted_url(&self) -> moqros::Url {
45		redact_url(&self.url)
46	}
47
48	/// Log a warning if these settings let anyone on the network path read or alter the stream.
49	pub fn warn_if_insecure(&self) {
50		if let Some(reason) = insecurity(&self.url, self.insecure) {
51			tracing::warn!("{reason}; anyone on the network path can read or alter the stream");
52		}
53	}
54}
55
56/// What `moqros-pub` sends.
57#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
58pub enum Format {
59	/// Encode `sensor_msgs/msg/Image` or `sensor_msgs/msg/CompressedImage` messages as video.
60	Video,
61	/// Any message type, as one JSON document per message.
62	Json,
63	/// Any message type, in its ROS serialization (CDR).
64	Cdr,
65}
66
67impl Format {
68	pub fn name(self) -> &'static str {
69		match self {
70			Self::Video => "video",
71			Self::Json => "json",
72			Self::Cdr => "cdr",
73		}
74	}
75
76	/// The data track format, or `None` for video.
77	pub fn data(self) -> Option<moqros::DataFormat> {
78		match self {
79			Self::Video => None,
80			Self::Json => Some(moqros::DataFormat::Json),
81			Self::Cdr => Some(moqros::DataFormat::Cdr),
82		}
83	}
84}
85
86/// ROS QoS flags.
87#[derive(Debug, Clone, Args)]
88pub struct QosArgs {
89	/// Use reliable QoS instead of the best-effort sensor-data profile.
90	#[arg(long, action = ArgAction::Set, value_parser = BoolishValueParser::new(),
91		num_args = 0..=1, require_equals = true, default_value_t = false, default_missing_value = "true")]
92	pub reliable: bool,
93}
94
95impl QosArgs {
96	pub fn profile(&self) -> QosProfile {
97		if self.reliable {
98			QosProfile::default().keep_last(5)
99		} else {
100			QosProfile::sensor_data()
101		}
102	}
103}
104
105/// Video encoder flags.
106#[derive(Debug, Clone, Args)]
107pub struct EncoderArgs {
108	/// Video codec: `vp8`, `av1` (built with the `av1` feature), or `h264` (built with the
109	/// `h264` feature, with OPENH264_LIBRARY pointing at Cisco's OpenH264 binary).
110	#[arg(long, default_value_t = moqros::Codec::default())]
111	pub codec: moqros::Codec,
112
113	/// Hardware video encoding (built with the `hw` feature): `auto` uses a VA-API or NVENC
114	/// encoder through GStreamer when one works and falls back to software, `off` always
115	/// encodes in software, and `require` fails without a hardware encoder.
116	#[arg(long, default_value_t = moqros::Hardware::default())]
117	pub hw: moqros::Hardware,
118
119	/// Target video bitrate in bits per second.
120	#[arg(long, default_value_t = 2_000_000)]
121	pub bitrate: u32,
122
123	/// Expected maximum input frame rate of the video.
124	#[arg(long, default_value_t = 30.0)]
125	pub fps: f32,
126
127	/// Maximum keyframe (MoQ group) interval of the video in milliseconds.
128	#[arg(long, default_value_t = 2000)]
129	pub keyframe_interval_ms: u64,
130
131	/// A smaller rendition of each video, as `HEIGHTp@BITRATE` (e.g. `360p@500000`); repeat for
132	/// several. Viewers pick the one that suits them.
133	#[arg(id = "rendition", long = "rendition", value_parser = parse_rendition)]
134	pub renditions: Vec<moqros::RenditionSettings>,
135}
136
137/// Parse `HEIGHT[p]@BITRATE`, e.g. `360p@500000`.
138fn parse_rendition(spec: &str) -> Result<moqros::RenditionSettings, String> {
139	let invalid = || format!("expected HEIGHTp@BITRATE (e.g. 360p@500000), got {spec:?}");
140	let (height, bitrate) = spec.split_once('@').ok_or_else(invalid)?;
141	let height: u32 = height.trim().trim_end_matches('p').parse().map_err(|_| invalid())?;
142	let bitrate: u32 = bitrate.trim().parse().map_err(|_| invalid())?;
143	if height < 2 || bitrate == 0 {
144		return Err(invalid());
145	}
146	Ok(moqros::RenditionSettings { height, bitrate })
147}
148
149impl EncoderArgs {
150	pub fn settings(&self) -> moqros::EncoderSettings {
151		moqros::EncoderSettings {
152			codec: self.codec,
153			bitrate: self.bitrate,
154			max_fps: self.fps,
155			keyframe_interval: Duration::from_millis(self.keyframe_interval_ms),
156			hardware: self.hw,
157			..Default::default()
158		}
159	}
160
161	/// The settings of every rendition.
162	pub fn broadcast_settings(&self) -> moqros::ImageBroadcastSettings {
163		moqros::ImageBroadcastSettings {
164			encoder: self.settings(),
165			renditions: self.renditions.clone(),
166		}
167	}
168}
169
170/// Diagnostics flags.
171#[derive(Debug, Clone, Args)]
172pub struct DiagnosticsArgs {
173	/// Period in milliseconds of the bridge statistics published on `/diagnostics`
174	/// (`diagnostic_msgs/msg/DiagnosticArray`); 0 turns them off.
175	#[arg(long, default_value_t = 1000)]
176	pub diagnostics_period_ms: u64,
177}
178
179impl DiagnosticsArgs {
180	pub fn period(&self) -> Option<Duration> {
181		(self.diagnostics_period_ms > 0).then(|| Duration::from_millis(self.diagnostics_period_ms))
182	}
183}
184
185#[cfg(test)]
186mod tests {
187	use super::*;
188
189	#[test]
190	fn parses_renditions() {
191		let rendition = |height, bitrate| moqros::RenditionSettings { height, bitrate };
192		assert_eq!(parse_rendition("360p@500000"), Ok(rendition(360, 500_000)));
193		assert_eq!(parse_rendition("720@2000000"), Ok(rendition(720, 2_000_000)));
194		for bad in [
195			"360p",
196			"@500000",
197			"360p@",
198			"p@1",
199			"1p@100",
200			"360p@0",
201			"360p@1.5M",
202			"-360p@1",
203		] {
204			assert!(parse_rendition(bad).is_err(), "{bad}");
205		}
206	}
207}