use std::path::Path;
use fluxframe_core::paths::ConfigBase;
use fluxframe_core::{FluxConfig, FluxError, InputDevice, PipelineSection, Preset};
#[cfg(feature = "ml")]
use fluxframe_effects::ml::OnnxEngine;
#[cfg(feature = "ml")]
use fluxframe_effects::post_effects;
use fluxframe_effects::{mask_effects, plane_effects};
use fluxframe_gst::{V4l2DeviceKind, enumerate_devices};
use tracing::{info, warn};
use crate::cli::CheckArgs;
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};
pub fn run(args: CheckArgs) -> Result<(), FluxError> {
let overrides = CliOverrides {
input: args.common.input,
output: args.common.output,
width: None,
height: None,
fps: None,
};
let load_path = resolve_load_path(args.common.config.as_deref(), args.common.no_default_config);
let config_base = ConfigBase::for_config(
resolve_writable_path(args.common.config.as_deref(), args.common.no_default_config)
.as_deref(),
);
let cfg = load(load_path.as_deref())?;
let cfg = apply(cfg, &overrides);
cfg.validate()?;
let mut failures: Vec<FluxError> = Vec::new();
if let Err(e) = check_gstreamer_init() {
failures.push(e);
}
if let Err(e) = check_input_device(&cfg) {
failures.push(e);
}
if let Err(e) = check_output_device(&cfg) {
failures.push(e);
}
if let Err(e) = check_preset(&cfg, args.preset.as_deref(), &config_base) {
failures.push(e);
}
if failures.is_empty() {
info!("all checks passed");
Ok(())
} else {
for failure in &failures {
use fluxframe_core::Diagnostic;
eprintln!("Error: {}", failure.reason());
if let Some(hint) = failure.hint() {
eprintln!("Hint: {hint}");
}
}
let count = failures.len();
let primary = failures.into_iter().next().expect("non-empty");
Err(FluxError::Aggregated {
primary: Box::new(primary),
count,
})
}
}
fn check_gstreamer_init() -> Result<(), FluxError> {
fluxframe_gst::init()?;
info!("gstreamer init: ok");
Ok(())
}
fn check_input_device(cfg: &FluxConfig) -> Result<(), FluxError> {
if matches!(cfg.input.device, InputDevice::Auto) {
let candidates = fluxframe_gst::v4l2_caps::enumerate_capture_devices();
if candidates.is_empty() {
tracing::warn!(
"input: auto — no capture devices available right now \
(runtime will keep polling at `[input.auto].poll_interval_secs`)"
);
} else {
info!(
devices = ?candidates,
"input: auto — first available will be picked at startup",
);
}
return Ok(());
}
match classify_input(cfg) {
InputSpec::Testsrc => {
info!(device = %cfg.input.device, "input: synthetic source (no device check needed)");
Ok(())
}
InputSpec::V4l2(path) => {
let canon = fluxframe_gst::check_v4l2_input_access(&path)?;
info!(
device = %path.display(),
canonical = %canon.display(),
"input device: readable",
);
Ok(())
}
InputSpec::Unsupported(d) => Err(FluxError::Config {
reason: format!("input '{d}' is not supported"),
hint: Some("use --input testsrc or --input /dev/video<N>".into()),
}),
}
}
fn check_output_device(cfg: &FluxConfig) -> Result<(), FluxError> {
match classify_output(cfg) {
OutputSpec::Auto => {
info!("output: autovideosink (no device check needed)");
Ok(())
}
OutputSpec::Fake => {
info!("output: fakesink (no device check needed)");
Ok(())
}
OutputSpec::V4l2(path) => {
let canon = fluxframe_gst::check_v4l2_output_access(&path)?;
warn_if_not_loopback(&canon);
warn_if_no_exclusive_caps(&canon);
info!(
device = %path.display(),
canonical = %canon.display(),
"output device: writable",
);
Ok(())
}
OutputSpec::Pipewire(node_name) => {
info!(node = ?node_name, "output: pipewire (validated at pipeline build)");
Ok(())
}
OutputSpec::Unsupported(d) => Err(FluxError::Config {
reason: format!("output '{d}' is not supported"),
hint: Some("supported outputs: auto, fakesink, /dev/video<N>, pipewire[:name]".into()),
}),
}
}
fn warn_if_not_loopback(canonical: &Path) {
let devices = enumerate_devices();
let Some(d) = devices.iter().find(|d| d.path == canonical) else {
tracing::debug!(
device = %canonical.display(),
"loopback classification skipped (device not in enumeration)",
);
return;
};
match d.kind {
V4l2DeviceKind::Virtual => {} V4l2DeviceKind::Unknown => {
warn!(
device = %canonical.display(),
"device kind unknown; could not verify loopback. If this is a real camera, output may be wasted.",
);
}
_ => {
warn!(
device = %canonical.display(),
kind = ?d.kind,
"output device does not look like a v4l2loopback; you may be writing to a real camera",
);
}
}
}
fn warn_if_no_exclusive_caps(device: &Path) {
if !cfg!(target_os = "linux") {
return;
}
let Some(video_nr) = video_number(device) else {
tracing::debug!(
device = %device.display(),
"exclusive_caps check skipped (could not parse a video number from the path)",
);
return;
};
let video_nr_csv = std::fs::read_to_string("/sys/module/v4l2loopback/parameters/video_nr");
let exclusive_csv =
std::fs::read_to_string("/sys/module/v4l2loopback/parameters/exclusive_caps");
let (Ok(video_nr_csv), Ok(exclusive_csv)) = (video_nr_csv, exclusive_csv) else {
tracing::debug!(
device = %device.display(),
"exclusive_caps check skipped (v4l2loopback sysfs parameters unreadable)",
);
return;
};
match exclusive_caps_for_device(&video_nr_csv, &exclusive_csv, video_nr) {
Some(true) => {
info!(
device = %device.display(),
"v4l2loopback exclusive_caps=1 — visible to Chrome/WebRTC",
);
}
Some(false) | None => {
warn!(
device = %device.display(),
"v4l2loopback is NOT exposing exclusive_caps=1 for this device; Chrome and other \
capability-filtering consumers will not list it. Reload the module with: \
sudo modprobe -r v4l2loopback && sudo modprobe v4l2loopback exclusive_caps=1 \
card_label=\"FluxFrame Camera\"",
);
}
}
}
fn video_number(path: &Path) -> Option<i32> {
let name = path.file_name()?.to_str()?;
name.strip_prefix("video")?.parse::<i32>().ok()
}
fn exclusive_caps_for_device(
video_nr_csv: &str,
exclusive_caps_csv: &str,
video_nr_target: i32,
) -> Option<bool> {
let idx = video_nr_csv
.trim()
.split(',')
.position(|entry| entry.trim().parse::<i32>().ok() == Some(video_nr_target))?;
let entry = exclusive_caps_csv.trim().split(',').nth(idx)?.trim();
match entry {
"Y" | "y" | "1" => Some(true),
"N" | "n" | "0" => Some(false),
_ => None,
}
}
fn check_preset(
cfg: &FluxConfig,
requested: Option<&str>,
config_base: &ConfigBase,
) -> Result<(), FluxError> {
let (name, preset) = preset::resolve(cfg, requested)?;
check_preset_sections(name, preset)?;
let _ = preset::build_chain(name, preset, config_base)?;
#[cfg(feature = "ml")]
if let Some(mask) = preset.mask.as_ref() {
if let Some(model) = mask.model.as_deref() {
check_model_file(&config_base.resolve(model))?;
}
}
info!(preset = %name, "preset: ok");
Ok(())
}
fn check_preset_sections(preset_name: &str, preset: &Preset) -> Result<(), FluxError> {
let mask_registry = mask_effects::default_registry();
let plane_registry = plane_effects::default_registry();
if let Some(mask) = preset.mask.as_ref() {
check_mask_chain(preset_name, mask, &mask_registry)?;
}
if let Some(bg) = preset.background.as_ref() {
check_plane_chain(preset_name, "background", bg, &plane_registry)?;
}
if let Some(fg) = preset.foreground.as_ref() {
check_plane_chain(preset_name, "foreground", fg, &plane_registry)?;
}
if let Some(post) = preset.post.as_ref() {
if preset.mask.is_none() {
return Err(FluxError::Config {
reason: format!("preset '{preset_name}' has a [post] chain but no [mask] section"),
hint: Some(
"post-effects require a mask; either add a [mask] section or \
remove the [post] chain"
.into(),
),
});
}
#[cfg(feature = "ml")]
{
let post_registry = post_effects::default_registry();
check_post_chain(preset_name, post, &post_registry)?;
}
#[cfg(not(feature = "ml"))]
let _ = post;
}
Ok(())
}
fn check_mask_chain(
preset_name: &str,
mask: &PipelineSection,
registry: &mask_effects::MaskEffectRegistry,
) -> Result<(), FluxError> {
for name in &mask.chain {
if !registry.contains(name) {
return Err(FluxError::Config {
reason: format!(
"preset '{preset_name}': mask chain references unknown effect '{name}'"
),
hint: Some(format!(
"available mask effects: {}",
registry.names().join(", "),
)),
});
}
}
Ok(())
}
fn check_plane_chain(
preset_name: &str,
section: &str,
plane: &PipelineSection,
registry: &plane_effects::PlaneEffectRegistry,
) -> Result<(), FluxError> {
for name in &plane.chain {
if !registry.contains(name) {
return Err(FluxError::Config {
reason: format!(
"preset '{preset_name}': {section} chain references unknown effect '{name}'"
),
hint: Some(format!(
"available plane effects: {}",
registry.names().join(", "),
)),
});
}
}
Ok(())
}
#[cfg(feature = "ml")]
fn check_post_chain(
preset_name: &str,
post: &PipelineSection,
registry: &post_effects::PostEffectRegistry,
) -> Result<(), FluxError> {
for name in &post.chain {
if !registry.contains(name) {
return Err(FluxError::Config {
reason: format!(
"preset '{preset_name}': post chain references unknown effect '{name}'"
),
hint: Some(format!(
"available post effects: {}",
registry.names().join(", "),
)),
});
}
}
Ok(())
}
#[cfg(feature = "ml")]
fn check_model_file(path: &Path) -> Result<(), FluxError> {
if !path.exists() {
return Err(FluxError::Config {
reason: format!("model file not found: {}", path.display()),
hint: Some(
"set the `model = \"...\"` field in the preset's [mask] section \
to a valid ONNX path"
.into(),
),
});
}
let config = fluxframe_effects::ml::load_sidecar_or_placeholder(path)?;
let engine = OnnxEngine::load(path, config)?;
info!(
inputs = engine.input_count(),
outputs = engine.output_count(),
"model file: loads OK",
);
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use fluxframe_core::Preset;
fn cfg_with(toml: &str) -> FluxConfig {
FluxConfig::from_toml_str(toml).expect("toml parses")
}
#[test]
fn video_number_parses_dev_path() {
assert_eq!(video_number(Path::new("/dev/video10")), Some(10));
assert_eq!(video_number(Path::new("/dev/video0")), Some(0));
assert_eq!(video_number(Path::new("/dev/videoX")), None);
assert_eq!(video_number(Path::new("/dev/null")), None);
}
#[test]
fn exclusive_caps_maps_index_zero() {
assert_eq!(
exclusive_caps_for_device("10,-1,-1", "Y,N,N", 10),
Some(true)
);
}
#[test]
fn exclusive_caps_maps_nonzero_index() {
assert_eq!(
exclusive_caps_for_device("4,10,-1", "Y,N,N", 10),
Some(false)
);
}
#[test]
fn exclusive_caps_accepts_numeric_one_as_enabled() {
assert_eq!(exclusive_caps_for_device("10", "1", 10), Some(true));
assert_eq!(exclusive_caps_for_device("10", "0", 10), Some(false));
}
#[test]
fn exclusive_caps_none_when_target_missing() {
assert_eq!(exclusive_caps_for_device("4,5,6", "Y,Y,Y", 10), None);
}
#[test]
fn exclusive_caps_none_when_index_out_of_range() {
assert_eq!(exclusive_caps_for_device("4,5,10", "Y,N", 10), None);
}
#[test]
fn exclusive_caps_tolerates_whitespace_and_newlines() {
assert_eq!(
exclusive_caps_for_device(" 10, -1 \n", " Y , N \n", 10),
Some(true)
);
}
#[test]
fn check_preset_fails_when_no_default_and_no_flag() {
let cfg = cfg_with("[presets.custom]\n");
let err =
check_preset(&cfg, None, &ConfigBase::default()).expect_err("missing default → error");
let msg = format!("{err}");
assert!(msg.contains("default"), "got: {msg}");
}
#[test]
fn check_preset_fails_when_named_missing() {
let cfg = cfg_with("[presets.default]\n");
let err = check_preset(&cfg, Some("nope"), &ConfigBase::default())
.expect_err("missing requested → error");
let msg = format!("{err}");
assert!(msg.contains("'nope'"), "got: {msg}");
}
#[test]
fn check_preset_default_with_empty_sections_passes() {
let cfg = cfg_with("[presets.default]\n");
check_preset(&cfg, None, &ConfigBase::default()).expect("empty default preset is valid");
}
#[test]
fn check_preset_rejects_unknown_mask_effect() {
let cfg = cfg_with(
r#"
[presets.default]
[presets.default.mask]
model = "/tmp/nonexistent.onnx"
chain = ["nonexistent_mask_effect"]
"#,
);
let err = check_preset_sections(
"default",
cfg.presets.get("default").expect("preset present"),
)
.expect_err("unknown mask effect must fail");
let msg = format!("{err}");
assert!(msg.contains("nonexistent_mask_effect"), "got: {msg}");
}
#[test]
fn check_preset_rejects_unknown_plane_effect() {
let cfg = cfg_with(
r#"
[presets.default]
[presets.default.background]
chain = ["nonexistent_plane_effect"]
"#,
);
let err = check_preset_sections(
"default",
cfg.presets.get("default").expect("preset present"),
)
.expect_err("unknown plane effect must fail");
let msg = format!("{err}");
assert!(msg.contains("nonexistent_plane_effect"), "got: {msg}");
}
#[test]
fn check_preset_accepts_known_effects() {
let cfg = cfg_with(
r#"
[presets.default]
[presets.default.background]
chain = ["blur"]
[presets.default.foreground]
chain = ["passthrough"]
"#,
);
check_preset_sections(
"default",
cfg.presets.get("default").expect("preset present"),
)
.expect("blur+passthrough are registered");
}
#[test]
fn check_input_device_accepts_testsrc() {
let mut cfg = FluxConfig::default();
cfg.input.device = InputDevice::Testsrc;
check_input_device(&cfg).expect("testsrc always passes");
}
#[test]
fn check_input_device_reports_auto_without_devices_as_warning_not_error() {
let mut cfg = FluxConfig::default();
cfg.input.device = InputDevice::Auto;
check_input_device(&cfg).expect("auto mode never errors at check time");
}
#[test]
fn check_preset_sections_with_default_preset_is_noop() {
let preset = Preset::default();
check_preset_sections("empty", &preset).expect("empty preset has no chains to validate");
}
}