fluxframe-cli 0.8.0

fluxframe CLI binary: list, check, run, benchmark.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
//! `fluxframe check` — verify GStreamer init, devices and the selected
//! preset's pipeline before `fluxframe run` so users see structured §27
//! Error/Hint diagnostics instead of opaque GStreamer failures.

use std::path::Path;

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};
use crate::preset;
use crate::runtime::{InputSpec, OutputSpec, classify_input, classify_output};

/// Entry point for `fluxframe check`.
///
/// # Errors
///
/// Returns the first failed check as a [`FluxError`].  All checks run
/// (subsequent failures are also printed) before returning.
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 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()) {
        failures.push(e);
    }

    if failures.is_empty() {
        info!("all checks passed");
        Ok(())
    } else {
        // Print every failure here, in §27 Error/Hint form, so the
        // operator sees the full picture (not just the first failure).
        for failure in &failures {
            use fluxframe_core::Diagnostic;
            eprintln!("Error: {}", failure.reason());
            if let Some(hint) = failure.hint() {
                eprintln!("Hint: {hint}");
            }
        }
        // Surface an `Aggregated` error so `main.rs` recognises that we
        // already rendered each underlying failure and skips its own
        // §27 print.  Preserving `primary` keeps `matches!()` consumers
        // (tests in particular) working unchanged.
        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> {
    // Auto-pick mode: nothing to verify ahead of time. Just enumerate
    // and report what would be picked right now so the operator can
    // sanity-check the candidate list. An empty list is a warning,
    // not an error — runtime will wait for a device to appear.
    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(());
    }
    // Triage lives in [`classify_input`] (shared with `commands::run`)
    // so both code paths cannot drift apart on which device strings are
    // valid.  Delegate the actual canonicalisation + open-probe +
    // hint-rendering to `fluxframe_gst::check_v4l2_input_access` so the
    // §27 Error/Hint text is rendered in exactly one place.
    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> {
    // Same rationale as `check_input_device`: route through
    // [`classify_output`] so `commands::check` and `commands::run` agree
    // on which output strings are valid.
    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) => {
            // No pre-flight to run: PipeWire availability and the
            // `pipewiresink` element are validated at pipeline build
            // time, which surfaces a structured MissingElement error
            // when `gst-plugin-pipewire` is not installed.
            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 {
        // Device passed the open-probe but isn't in the sysfs enumeration
        // (e.g. the user pointed at a path outside `/dev/video*`).  We
        // intentionally do not warn the operator here — they already
        // know they are writing to a non-standard path — but record a
        // debug breadcrumb for support.
        tracing::debug!(
            device = %canonical.display(),
            "loopback classification skipped (device not in enumeration)",
        );
        return;
    };
    match d.kind {
        V4l2DeviceKind::Virtual => {} // expected
        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",
            );
        }
    }
}

/// Warn when the v4l2loopback device backing the output is NOT exposing
/// `exclusive_caps=1`.
///
/// Chrome / WebRTC (and other capability-filtering consumers) only list a
/// loopback device when it advertises CAPTURE caps, which requires the
/// module to be loaded with `exclusive_caps=1`. Without it the virtual
/// camera silently never appears in the browser's device picker — the
/// single most common "FluxFrame isn't showing up" cause. This is a
/// best-effort, non-fatal diagnostic: missing sysfs files (module not
/// loaded, non-Linux) are skipped quietly.
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\"",
            );
        }
    }
}

/// Parse the trailing video number from a `/dev/videoN` path
/// (`/dev/video10` → `10`). Returns `None` if the file name does not
/// match the `videoN` shape.
fn video_number(path: &Path) -> Option<i32> {
    let name = path.file_name()?.to_str()?;
    name.strip_prefix("video")?.parse::<i32>().ok()
}

/// Resolve whether a given v4l2loopback device has `exclusive_caps=1`,
/// from the module's `video_nr` and `exclusive_caps` CSV parameters.
///
/// Both parameters are comma-separated and positionally aligned: the
/// device created at `video_nr[i]` has the cap setting `exclusive_caps[i]`.
/// We find `video_nr_target` in the `video_nr` CSV, then read the same
/// index of the `exclusive_caps` CSV. `Y`/`1` → `Some(true)`, `N`/`0` →
/// `Some(false)`, and any malformed / missing / out-of-range input →
/// `None` (treated as "could not confirm", which the caller warns on).
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,
    }
}

/// Validate the preset selected on the command line (or the implicit
/// [`preset::DEFAULT_PRESET_NAME`] preset).
///
/// Checks performed:
///   1. The named preset exists ([`preset::resolve`]).
///   2. Every effect name in `mask.chain` is registered in the mask
///      registry.
///   3. Every effect name in `background.chain` / `foreground.chain`
///      is registered in the plane registry.
///   4. The preset can be turned into an [`EffectChain`]
///      ([`preset::build_chain`]) — this surfaces the same
///      feature-gated and bg-without-mask errors that `run` would
///      raise, so `check` and `run` cannot disagree.
///   5. (`ml` feature only) The model path referenced by the mask
///      section exists on disk and loads as an ONNX model.
///
/// [`EffectChain`]: fluxframe_effects::EffectChain
fn check_preset(cfg: &FluxConfig, requested: Option<&str>) -> Result<(), FluxError> {
    let (name, preset) = preset::resolve(cfg, requested)?;

    // Registry-level effect-name validation lives here (and only here)
    // because `preset::build_chain` already surfaces these as
    // `EffectError::UnknownEffect` via the composite builder when a
    // `[mask]` section is present — but `check` should also reject
    // unknown names in `[background]`/`[foreground]` chains when no
    // mask is configured (in which case those sections are config
    // bugs that `build_chain` rejects, but the operator deserves the
    // sharper "unknown effect" message first).
    check_preset_sections(name, preset)?;

    // Surface the same Ok/Err that `run` would see when constructing
    // its chain.  Catches: mask-without-ml, bg/fg-without-mask, and
    // composite-builder failures (per-effect TOML, model missing).
    let _ = preset::build_chain(name, preset)?;

    #[cfg(feature = "ml")]
    if let Some(mask) = preset.mask.as_ref() {
        if let Some(model) = mask.model.as_deref() {
            check_model_file(model)?;
        }
    }

    info!(preset = %name, "preset: ok");
    Ok(())
}

/// Validate each effect name appearing in the preset's sub-chains is
/// known to the corresponding registry.
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() {
        // Post-effects are mask-aware — a preset that declares a
        // `[post]` chain without a `[mask]` section is a config bug
        // that the runtime would surface later with a less specific
        // message. Catch it here.
        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() {
        // video10 is the first loopback → index 0 → "Y" → enabled.
        assert_eq!(
            exclusive_caps_for_device("10,-1,-1", "Y,N,N", 10),
            Some(true)
        );
    }

    #[test]
    fn exclusive_caps_maps_nonzero_index() {
        // The target sits at index 1; its cap entry is "N" → disabled.
        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() {
        // video_nr has the target at index 2 but exclusive_caps is shorter.
        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).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")).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).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"]
"#,
        );
        // We intentionally do not test the model-file branch here —
        // the chain validation runs before the model existence check,
        // so the unknown-effect error is what surfaces first.
        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() {
        // `Auto` enters the polling branch, which logs a warning and
        // returns `Ok(())` when nothing is plugged in. The unit harness
        // is unlikely to have a real V4L2 camera available; either
        // outcome counts as "no error surfaced", because absence of a
        // device is not a check-time failure.
        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() {
        // An empty Preset (no mask/bg/fg) trivially passes — there are
        // no chains to validate.
        let preset = Preset::default();
        check_preset_sections("empty", &preset).expect("empty preset has no chains to validate");
    }
}