use std::fmt;
use std::path::PathBuf;
use std::time::Duration;
use clap::builder::BoolishValueParser;
use clap::{ArgAction, Args, ValueEnum};
use moqros::ros::{QosProfile, StampSource};
use crate::spec::{RepublishOptions, parse_encoding};
use crate::url::{insecurity, redact_url};
#[derive(Debug, Clone, Args)]
pub struct RelayArgs {
#[arg(long, env = "MOQROS_URL", default_value = "http://localhost:4443/anon")]
pub url: moqros::Url,
#[arg(long, env = "MOQROS_INSECURE", action = ArgAction::Set, value_parser = BoolishValueParser::new(),
num_args = 0..=1, require_equals = true, default_value_t = false, default_missing_value = "true")]
pub insecure: bool,
#[arg(long, env = "MOQROS_TLS_CERT", requires = "tls_key")]
pub tls_cert: Option<PathBuf>,
#[arg(long, env = "MOQROS_TLS_KEY", requires = "tls_cert")]
pub tls_key: Option<PathBuf>,
}
impl RelayArgs {
pub fn config(&self) -> moqros::ClientConfig {
let mut config = moqros::ClientConfig::new(self.url.clone()).with_insecure(self.insecure);
config.tls_cert = self.tls_cert.clone();
config.tls_key = self.tls_key.clone();
config
}
pub fn redacted_url(&self) -> moqros::Url {
redact_url(&self.url)
}
pub fn warn_if_insecure(&self) {
if let Some(reason) = insecurity(&self.url, self.insecure) {
tracing::warn!("{reason}; anyone on the network path can read or alter the stream");
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
pub enum Format {
Video,
Json,
Cdr,
}
impl fmt::Display for Format {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.to_possible_value().expect("no variant is skipped").get_name())
}
}
impl Format {
pub fn data(self) -> Option<moqros::DataFormat> {
match self {
Self::Video => None,
Self::Json => Some(moqros::DataFormat::Json),
Self::Cdr => Some(moqros::DataFormat::Cdr),
}
}
}
#[derive(Debug, Clone, Args)]
pub struct QosArgs {
#[arg(long, action = ArgAction::Set, value_parser = BoolishValueParser::new(),
num_args = 0..=1, require_equals = true, default_value_t = false, default_missing_value = "true")]
pub reliable: bool,
}
impl QosArgs {
pub fn profile(&self) -> QosProfile {
if self.reliable {
QosProfile::default().keep_last(5)
} else {
QosProfile::sensor_data()
}
}
}
#[derive(Debug, Clone, Args)]
pub struct EncoderArgs {
#[arg(long, default_value_t = moqros::Codec::default())]
pub codec: moqros::Codec,
#[arg(long, default_value_t = moqros::Hardware::default())]
pub hw: moqros::Hardware,
#[arg(long, default_value_t = moqros::EncoderSettings::default().bitrate)]
pub bitrate: u32,
#[arg(long, default_value_t = moqros::EncoderSettings::default().max_fps)]
pub fps: f32,
#[arg(long, default_value_t = default_keyframe_interval_ms())]
pub keyframe_interval_ms: u64,
#[arg(id = "rendition", long = "rendition", value_parser = parse_rendition)]
pub renditions: Vec<moqros::RenditionSettings>,
}
fn default_keyframe_interval_ms() -> u64 {
u64::try_from(moqros::EncoderSettings::default().keyframe_interval.as_millis()).unwrap_or(u64::MAX)
}
fn parse_rendition(spec: &str) -> Result<moqros::RenditionSettings, String> {
let invalid = || format!("expected HEIGHTp@BITRATE (e.g. 360p@500000), got {spec:?}");
let (height, bitrate) = spec.split_once('@').ok_or_else(invalid)?;
let height: u32 = height.trim().trim_end_matches('p').parse().map_err(|_| invalid())?;
let bitrate: u32 = bitrate.trim().parse().map_err(|_| invalid())?;
if height < 2 || bitrate == 0 {
return Err(invalid());
}
Ok(moqros::RenditionSettings::new(height, bitrate))
}
impl EncoderArgs {
pub fn settings(&self) -> moqros::EncoderSettings {
moqros::EncoderSettings::default()
.with_codec(self.codec)
.with_bitrate(self.bitrate)
.with_max_fps(self.fps)
.with_keyframe_interval(Duration::from_millis(self.keyframe_interval_ms))
.with_hardware(self.hw)
}
pub fn broadcast_settings(&self) -> moqros::ImageBroadcastSettings {
moqros::ImageBroadcastSettings::new(self.settings()).with_renditions(self.renditions.iter().copied())
}
}
#[derive(Debug, Clone, Args)]
pub struct RepublishArgs {
#[arg(long)]
pub frame_id: Option<String>,
#[arg(long, default_value_t = StampSource::default())]
pub stamp: StampSource,
#[arg(long)]
pub max_height: Option<u32>,
#[arg(long, default_value = "rgb8", value_parser = parse_encoding)]
pub encoding: moqros::PixelFormat,
}
impl RepublishArgs {
pub fn options(&self) -> RepublishOptions {
RepublishOptions {
frame_id: self.frame_id.clone(),
stamp: self.stamp,
max_height: self.max_height,
encoding: self.encoding,
}
}
}
#[derive(Debug, Clone, Args)]
pub struct DiagnosticsArgs {
#[arg(long, default_value_t = 1000)]
pub diagnostics_period_ms: u64,
}
impl DiagnosticsArgs {
pub fn period(&self) -> Option<Duration> {
(self.diagnostics_period_ms > 0).then(|| Duration::from_millis(self.diagnostics_period_ms))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parses_renditions() {
let rendition = moqros::RenditionSettings::new;
assert_eq!(parse_rendition("360p@500000"), Ok(rendition(360, 500_000)));
assert_eq!(parse_rendition("720@2000000"), Ok(rendition(720, 2_000_000)));
for bad in [
"360p",
"@500000",
"360p@",
"p@1",
"1p@100",
"360p@0",
"360p@1.5M",
"-360p@1",
] {
assert!(parse_rendition(bad).is_err(), "{bad}");
}
}
#[test]
fn formats_display_their_flag_values() {
for format in Format::value_variants() {
assert_eq!(Format::from_str(&format.to_string(), false), Ok(*format));
}
}
#[test]
fn encoder_flags_default_to_the_library_defaults() {
#[derive(clap::Parser)]
struct Cli {
#[command(flatten)]
encoder: EncoderArgs,
}
let settings = <Cli as clap::Parser>::parse_from(["test"]).encoder.settings();
let defaults = moqros::EncoderSettings::default();
assert_eq!(settings.bitrate, defaults.bitrate);
assert_eq!(settings.max_fps, defaults.max_fps);
assert_eq!(settings.keyframe_interval, defaults.keyframe_interval);
assert_eq!(settings.codec, defaults.codec);
assert_eq!(settings.hardware, defaults.hardware);
}
}