Skip to main content

moqros_cli/
args.rs

1//! Flags shared by the bridge binaries.
2
3use std::fmt;
4use std::path::PathBuf;
5use std::time::Duration;
6
7use clap::builder::BoolishValueParser;
8use clap::{ArgAction, Args, ValueEnum};
9use moqros::ros::{QosProfile, StampSource};
10
11use crate::spec::{RepublishOptions, parse_encoding};
12use crate::url::{insecurity, redact_url};
13
14/// Relay connection flags.
15#[derive(Debug, Clone, Args)]
16pub struct RelayArgs {
17	/// Relay URL; its path scopes broadcast names.
18	#[arg(long, env = "MOQROS_URL", default_value = "http://localhost:4443/anon")]
19	pub url: moqros::Url,
20
21	/// Disable TLS certificate verification (development only).
22	#[arg(long, env = "MOQROS_INSECURE", action = ArgAction::Set, value_parser = BoolishValueParser::new(),
23		num_args = 0..=1, require_equals = true, default_value_t = false, default_missing_value = "true")]
24	pub insecure: bool,
25
26	/// PEM client certificate chain to present to the relay (mTLS).
27	#[arg(long, env = "MOQROS_TLS_CERT", requires = "tls_key")]
28	pub tls_cert: Option<PathBuf>,
29
30	/// PEM private key of `--tls-cert`.
31	#[arg(long, env = "MOQROS_TLS_KEY", requires = "tls_cert")]
32	pub tls_key: Option<PathBuf>,
33}
34
35impl RelayArgs {
36	pub fn config(&self) -> moqros::ClientConfig {
37		let mut config = moqros::ClientConfig::new(self.url.clone()).with_insecure(self.insecure);
38		config.tls_cert = self.tls_cert.clone();
39		config.tls_key = self.tls_key.clone();
40		config
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 fmt::Display for Format {
68	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
69		f.write_str(self.to_possible_value().expect("no variant is skipped").get_name())
70	}
71}
72
73impl Format {
74	/// The data track format, or `None` for video.
75	pub fn data(self) -> Option<moqros::DataFormat> {
76		match self {
77			Self::Video => None,
78			Self::Json => Some(moqros::DataFormat::Json),
79			Self::Cdr => Some(moqros::DataFormat::Cdr),
80		}
81	}
82}
83
84/// ROS QoS flags.
85#[derive(Debug, Clone, Args)]
86pub struct QosArgs {
87	/// Use reliable QoS instead of the best-effort sensor-data profile.
88	#[arg(long, action = ArgAction::Set, value_parser = BoolishValueParser::new(),
89		num_args = 0..=1, require_equals = true, default_value_t = false, default_missing_value = "true")]
90	pub reliable: bool,
91}
92
93impl QosArgs {
94	pub fn profile(&self) -> QosProfile {
95		if self.reliable {
96			QosProfile::default().keep_last(5)
97		} else {
98			QosProfile::sensor_data()
99		}
100	}
101}
102
103/// Video encoder flags.
104#[derive(Debug, Clone, Args)]
105pub struct EncoderArgs {
106	/// Video codec: `vp8`, `av1` (built with the `av1` feature), or `h264` (built with the
107	/// `h264` feature, with OPENH264_LIBRARY pointing at Cisco's OpenH264 binary).
108	#[arg(long, default_value_t = moqros::Codec::default())]
109	pub codec: moqros::Codec,
110
111	/// Hardware video encoding (built with the `hw` feature): `auto` uses a VA-API or NVENC
112	/// encoder through GStreamer when one works and falls back to software, `off` always
113	/// encodes in software, and `require` fails without a hardware encoder.
114	#[arg(long, default_value_t = moqros::Hardware::default())]
115	pub hw: moqros::Hardware,
116
117	/// Target video bitrate in bits per second.
118	#[arg(long, default_value_t = moqros::EncoderSettings::default().bitrate)]
119	pub bitrate: u32,
120
121	/// Expected maximum input frame rate of the video.
122	#[arg(long, default_value_t = moqros::EncoderSettings::default().max_fps)]
123	pub fps: f32,
124
125	/// Maximum keyframe (MoQ group) interval of the video in milliseconds.
126	#[arg(long, default_value_t = default_keyframe_interval_ms())]
127	pub keyframe_interval_ms: u64,
128
129	/// A smaller rendition of each video, as `HEIGHTp@BITRATE` (e.g. `360p@500000`); repeat for
130	/// several. Viewers pick the one that suits them.
131	#[arg(id = "rendition", long = "rendition", value_parser = parse_rendition)]
132	pub renditions: Vec<moqros::RenditionSettings>,
133}
134
135fn default_keyframe_interval_ms() -> u64 {
136	u64::try_from(moqros::EncoderSettings::default().keyframe_interval.as_millis()).unwrap_or(u64::MAX)
137}
138
139/// Parse `HEIGHT[p]@BITRATE`, e.g. `360p@500000`.
140fn parse_rendition(spec: &str) -> Result<moqros::RenditionSettings, String> {
141	let invalid = || format!("expected HEIGHTp@BITRATE (e.g. 360p@500000), got {spec:?}");
142	let (height, bitrate) = spec.split_once('@').ok_or_else(invalid)?;
143	let height: u32 = height.trim().trim_end_matches('p').parse().map_err(|_| invalid())?;
144	let bitrate: u32 = bitrate.trim().parse().map_err(|_| invalid())?;
145	if height < 2 || bitrate == 0 {
146		return Err(invalid());
147	}
148	Ok(moqros::RenditionSettings::new(height, bitrate))
149}
150
151impl EncoderArgs {
152	pub fn settings(&self) -> moqros::EncoderSettings {
153		moqros::EncoderSettings::default()
154			.with_codec(self.codec)
155			.with_bitrate(self.bitrate)
156			.with_max_fps(self.fps)
157			.with_keyframe_interval(Duration::from_millis(self.keyframe_interval_ms))
158			.with_hardware(self.hw)
159	}
160
161	/// The settings of every rendition.
162	pub fn broadcast_settings(&self) -> moqros::ImageBroadcastSettings {
163		moqros::ImageBroadcastSettings::new(self.settings()).with_renditions(self.renditions.iter().copied())
164	}
165}
166
167/// How MoQ -> ROS bridges republish video.
168#[derive(Debug, Clone, Args)]
169pub struct RepublishArgs {
170	/// `header.frame_id` of the republished images; defaults to the one the publisher announces.
171	#[arg(long)]
172	pub frame_id: Option<String>,
173
174	/// `header.stamp` of the republished images: `source` uses the capture time the publisher
175	/// announces (falling back to the receive time), `receive` the local receive time.
176	#[arg(long, default_value_t = StampSource::default())]
177	pub stamp: StampSource,
178
179	/// Pick the largest video rendition at most this tall (the smallest if none is), instead of
180	/// the largest.
181	#[arg(long)]
182	pub max_height: Option<u32>,
183
184	/// Pixel encoding of the republished images: `rgb8`, `bgr8`, `rgba8`, `bgra8` or `mono8`.
185	#[arg(long, default_value = "rgb8", value_parser = parse_encoding)]
186	pub encoding: moqros::PixelFormat,
187}
188
189impl RepublishArgs {
190	pub fn options(&self) -> RepublishOptions {
191		RepublishOptions {
192			frame_id: self.frame_id.clone(),
193			stamp: self.stamp,
194			max_height: self.max_height,
195			encoding: self.encoding,
196		}
197	}
198}
199
200/// Diagnostics flags.
201#[derive(Debug, Clone, Args)]
202pub struct DiagnosticsArgs {
203	/// Period in milliseconds of the bridge statistics published on `/diagnostics`
204	/// (`diagnostic_msgs/msg/DiagnosticArray`); 0 turns them off.
205	#[arg(long, default_value_t = 1000)]
206	pub diagnostics_period_ms: u64,
207}
208
209impl DiagnosticsArgs {
210	pub fn period(&self) -> Option<Duration> {
211		(self.diagnostics_period_ms > 0).then(|| Duration::from_millis(self.diagnostics_period_ms))
212	}
213}
214
215#[cfg(test)]
216mod tests {
217	use super::*;
218
219	#[test]
220	fn parses_renditions() {
221		let rendition = moqros::RenditionSettings::new;
222		assert_eq!(parse_rendition("360p@500000"), Ok(rendition(360, 500_000)));
223		assert_eq!(parse_rendition("720@2000000"), Ok(rendition(720, 2_000_000)));
224		for bad in [
225			"360p",
226			"@500000",
227			"360p@",
228			"p@1",
229			"1p@100",
230			"360p@0",
231			"360p@1.5M",
232			"-360p@1",
233		] {
234			assert!(parse_rendition(bad).is_err(), "{bad}");
235		}
236	}
237
238	#[test]
239	fn formats_display_their_flag_values() {
240		for format in Format::value_variants() {
241			assert_eq!(Format::from_str(&format.to_string(), false), Ok(*format));
242		}
243	}
244
245	#[test]
246	fn encoder_flags_default_to_the_library_defaults() {
247		#[derive(clap::Parser)]
248		struct Cli {
249			#[command(flatten)]
250			encoder: EncoderArgs,
251		}
252		let settings = <Cli as clap::Parser>::parse_from(["test"]).encoder.settings();
253		let defaults = moqros::EncoderSettings::default();
254		assert_eq!(settings.bitrate, defaults.bitrate);
255		assert_eq!(settings.max_fps, defaults.max_fps);
256		assert_eq!(settings.keyframe_interval, defaults.keyframe_interval);
257		assert_eq!(settings.codec, defaults.codec);
258		assert_eq!(settings.hardware, defaults.hardware);
259	}
260}