1use 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#[derive(Debug, Clone, Args)]
16pub struct RelayArgs {
17 #[arg(long, env = "MOQROS_URL", default_value = "http://localhost:4443/anon")]
19 pub url: moqros::Url,
20
21 #[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 #[arg(long, env = "MOQROS_TLS_CERT", requires = "tls_key")]
28 pub tls_cert: Option<PathBuf>,
29
30 #[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 pub fn redacted_url(&self) -> moqros::Url {
45 redact_url(&self.url)
46 }
47
48 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#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
58pub enum Format {
59 Video,
61 Json,
63 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 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#[derive(Debug, Clone, Args)]
86pub struct QosArgs {
87 #[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#[derive(Debug, Clone, Args)]
105pub struct EncoderArgs {
106 #[arg(long, default_value_t = moqros::Codec::default())]
109 pub codec: moqros::Codec,
110
111 #[arg(long, default_value_t = moqros::Hardware::default())]
115 pub hw: moqros::Hardware,
116
117 #[arg(long, default_value_t = moqros::EncoderSettings::default().bitrate)]
119 pub bitrate: u32,
120
121 #[arg(long, default_value_t = moqros::EncoderSettings::default().max_fps)]
123 pub fps: f32,
124
125 #[arg(long, default_value_t = default_keyframe_interval_ms())]
127 pub keyframe_interval_ms: u64,
128
129 #[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
139fn 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 pub fn broadcast_settings(&self) -> moqros::ImageBroadcastSettings {
163 moqros::ImageBroadcastSettings::new(self.settings()).with_renditions(self.renditions.iter().copied())
164 }
165}
166
167#[derive(Debug, Clone, Args)]
169pub struct RepublishArgs {
170 #[arg(long)]
172 pub frame_id: Option<String>,
173
174 #[arg(long, default_value_t = StampSource::default())]
177 pub stamp: StampSource,
178
179 #[arg(long)]
182 pub max_height: Option<u32>,
183
184 #[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#[derive(Debug, Clone, Args)]
202pub struct DiagnosticsArgs {
203 #[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}