use std::path::PathBuf;
use std::time::{Duration, Instant};
use fluxframe_core::{FluxConfig, FluxError, InputDevice};
use tracing::{info, warn};
use crate::cli::RunArgs;
use crate::config_merge::{CliOverrides, apply, load, resolve_load_path, resolve_writable_path};
use crate::preset;
use crate::runtime::{
InputSpec, OutputSpec, classify_input, classify_output, ensure_ctrlc_handler,
is_shutdown_requested, run_testsrc_chain, run_v4l2_chain, wait_for_shutdown,
};
pub fn run(args: RunArgs) -> Result<(), FluxError> {
let overrides = CliOverrides {
input: args.common.input,
output: args.common.output,
width: args.width,
height: args.height,
fps: args.fps,
};
let load_path = resolve_load_path(args.common.config.as_deref(), args.common.no_default_config);
let writable_path =
resolve_writable_path(args.common.config.as_deref(), args.common.no_default_config);
let cfg = load(load_path.as_deref())?;
let cfg = apply(cfg, &overrides);
cfg.validate()?;
crate::logging::apply_config_level(&cfg.logging.level);
crate::cap_rayon_pool(cfg.realtime.processing_threads);
let (resolved_name, _preset) = preset::resolve(&cfg, args.preset.as_deref())?;
let preset_name = resolved_name.to_string();
info!(
input = %cfg.input.device,
output = %cfg.output.device,
width = cfg.input.width,
height = cfg.input.height,
fps = cfg.input.fps,
preset = %preset_name,
config = ?writable_path,
"merged configuration"
);
match &cfg.input.device {
InputDevice::Auto => run_auto(&cfg, &preset_name, writable_path.as_deref()),
_ => run_once(&cfg, &preset_name, writable_path.as_deref()),
}
}
fn run_auto(
cfg: &FluxConfig,
preset_name: &str,
config_path: Option<&std::path::Path>,
) -> Result<(), FluxError> {
ensure_ctrlc_handler();
let interval = Duration::from_secs(u64::from(cfg.input.auto.poll_interval_secs.max(1)));
let exclude = compute_excludes(cfg);
info!(
poll_interval_secs = interval.as_secs(),
exclude = ?exclude,
"entering auto-input wait loop"
);
let mut last_failure_kind: Option<String> = None;
let mut last_no_devices_logged = false;
let backoff_base = Duration::from_millis(u64::from(cfg.input.acquire_backoff_base_ms.max(1)));
let backoff_max = Duration::from_millis(u64::from(cfg.input.acquire_backoff_max_ms.max(1)));
let mut failure_backoff: Option<Duration> = None;
loop {
if is_shutdown_requested() {
info!("auto-input loop: shutdown requested before any device was found");
return Ok(());
}
let candidates = fluxframe_gst::v4l2_caps::enumerate_capture_devices();
if let Some(path) = fluxframe_gst::v4l2_caps::pick_input_device(&candidates, &exclude) {
last_no_devices_logged = false;
info!(device = %path.display(), "auto-input picked");
let mut resolved = cfg.clone();
resolved.input.device = InputDevice::Path(path.clone());
let run_started = Instant::now();
match run_once(&resolved, preset_name, config_path) {
Ok(()) => return Ok(()),
Err(e) => {
if !e.is_transient() {
warn!(error = %e, "auto-input: permanent error, surfacing");
return Err(e);
}
let kind = format!("{:?}", std::mem::discriminant(&e));
if last_failure_kind.as_deref() != Some(kind.as_str()) {
warn!(
error = %e,
"auto-input transient error (new); returning to wait"
);
last_failure_kind = Some(kind);
}
failure_backoff = Some(next_failure_backoff(
failure_backoff,
run_started.elapsed(),
backoff_base,
backoff_max,
));
}
}
} else {
last_failure_kind = None;
failure_backoff = None;
if !last_no_devices_logged {
info!(
candidates = ?candidates,
"auto-input: no openable capture devices, will retry silently",
);
last_no_devices_logged = true;
}
}
let wait = failure_backoff.unwrap_or(interval);
if wait_for_shutdown(wait) {
info!("auto-input loop: shutdown during wait");
return Ok(());
}
}
}
const BACKOFF_RESET_FACTOR: u32 = 4;
fn next_failure_backoff(
current: Option<Duration>,
run_uptime: Duration,
base: Duration,
max: Duration,
) -> Duration {
if run_uptime >= max * BACKOFF_RESET_FACTOR {
return base.min(max);
}
match current {
None => base.min(max),
Some(prev) => (prev * 2).min(max),
}
}
fn run_once(
cfg: &FluxConfig,
preset_name: &str,
config_path: Option<&std::path::Path>,
) -> Result<(), FluxError> {
let (name, preset) = preset::resolve(cfg, Some(preset_name))?;
let chain = preset::build_chain(name, preset)?;
match classify_input(cfg) {
InputSpec::Testsrc => run_testsrc_chain(cfg, name, config_path, chain),
InputSpec::V4l2(_) => run_v4l2_chain(cfg, name, config_path, chain),
InputSpec::Unsupported(d) => Err(FluxError::Config {
reason: format!("input '{d}' is not supported"),
hint: Some("supported inputs: testsrc, /dev/video* (V4L2)".into()),
}),
}
}
fn compute_excludes(cfg: &FluxConfig) -> Vec<PathBuf> {
let mut excludes = cfg.input.auto.exclude_devices.clone();
if let OutputSpec::V4l2(p) = classify_output(cfg) {
if !excludes.contains(&p) {
excludes.push(p);
}
}
excludes
}
#[cfg(test)]
mod tests {
use super::*;
const BASE: Duration = Duration::from_millis(500);
const MAX: Duration = Duration::from_secs(5);
#[test]
fn first_failure_waits_the_base_delay() {
assert_eq!(
next_failure_backoff(None, Duration::from_millis(10), BASE, MAX),
BASE
);
}
#[test]
fn repeated_fast_failures_double_up_to_the_ceiling() {
let mut d = next_failure_backoff(None, Duration::ZERO, BASE, MAX);
assert_eq!(d, Duration::from_millis(500));
d = next_failure_backoff(Some(d), Duration::ZERO, BASE, MAX);
assert_eq!(d, Duration::from_secs(1));
d = next_failure_backoff(Some(d), Duration::ZERO, BASE, MAX);
assert_eq!(d, Duration::from_secs(2));
d = next_failure_backoff(Some(d), Duration::ZERO, BASE, MAX);
assert_eq!(d, Duration::from_secs(4));
d = next_failure_backoff(Some(d), Duration::ZERO, BASE, MAX);
assert_eq!(d, MAX);
d = next_failure_backoff(Some(d), Duration::ZERO, BASE, MAX);
assert_eq!(d, MAX);
}
#[test]
fn a_long_lived_run_resets_the_backoff() {
let long_enough = MAX * BACKOFF_RESET_FACTOR;
assert_eq!(
next_failure_backoff(Some(MAX), long_enough, BASE, MAX),
BASE
);
assert_eq!(
next_failure_backoff(
Some(BASE),
long_enough - Duration::from_millis(1),
BASE,
MAX
),
BASE * 2
);
}
#[test]
fn backoff_never_exceeds_max_even_when_base_is_larger() {
let base = Duration::from_secs(30);
let max = Duration::from_secs(5);
assert_eq!(next_failure_backoff(None, Duration::ZERO, base, max), max);
}
#[test]
fn compute_excludes_includes_output_dev_path() {
let mut cfg = FluxConfig::default();
cfg.output.device = "/dev/video10".into();
let ex = compute_excludes(&cfg);
assert!(ex.contains(&PathBuf::from("/dev/video10")));
}
#[test]
fn compute_excludes_skips_non_dev_output() {
let mut cfg = FluxConfig::default();
cfg.output.device = "fakesink".into();
assert!(compute_excludes(&cfg).is_empty());
}
#[test]
fn compute_excludes_merges_operator_excludes_with_output() {
let mut cfg = FluxConfig::default();
cfg.output.device = "/dev/video10".into();
cfg.input.auto.exclude_devices = vec![PathBuf::from("/dev/video20")];
let ex = compute_excludes(&cfg);
assert!(ex.contains(&PathBuf::from("/dev/video10")));
assert!(ex.contains(&PathBuf::from("/dev/video20")));
assert_eq!(ex.len(), 2);
}
#[test]
fn compute_excludes_no_duplicate_when_output_already_listed() {
let mut cfg = FluxConfig::default();
cfg.output.device = "/dev/video10".into();
cfg.input.auto.exclude_devices = vec![PathBuf::from("/dev/video10")];
let ex = compute_excludes(&cfg);
assert_eq!(ex.len(), 1);
}
}