use std::path::PathBuf;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Arc, Mutex, OnceLock, Weak};
use std::time::{Duration, Instant};
use fluxframe_core::Region;
use fluxframe_core::context::{FrameContext, Framing, FramingSource, ProcessingContext};
use fluxframe_core::error::PipelineError;
use fluxframe_core::metrics::StageKey;
use fluxframe_core::{FluxConfig, FluxError, InputDevice, Preset, SubchainKind};
use fluxframe_effects::EffectChain;
use fluxframe_effects::processing::framer::Framer;
use fluxframe_gst::input::{InputParams, InputPipeline};
use fluxframe_gst::output::{OutputParams, OutputPipeline, OutputSink};
use fluxframe_gst::{BusEvent, BusListener, BusSource, LatestFrameSlot, WatchedPipeline};
use tracing::{debug, error, info, warn};
use crate::control::{
self, Command as ControlCommand, ListenerHandle, Response as ControlResponse,
};
use crate::metrics_reporter::MetricsReporter;
use crate::preset;
use crate::runtime_metrics::RuntimeMetrics;
use crate::session::ControlSession;
use fluxframe_core::paths::ConfigBase;
const WORKER_RESPONSE_TIMEOUT: Duration = Duration::from_secs(5);
const CONTROL_CHANNEL_DEPTH: usize = 16;
const REPLY_CHANNEL_DEPTH: usize = 1;
pub(crate) struct ControlEnvelope {
pub cmd: ControlCommand,
pub reply_tx: crossbeam_channel::Sender<ControlResponse>,
}
struct ChannelHandler {
tx: crossbeam_channel::Sender<ControlEnvelope>,
}
impl control::CommandHandler for ChannelHandler {
fn handle(&self, cmd: ControlCommand) -> ControlResponse {
let (reply_tx, reply_rx) =
crossbeam_channel::bounded::<ControlResponse>(REPLY_CHANNEL_DEPTH);
if self.tx.send(ControlEnvelope { cmd, reply_tx }).is_err() {
return ControlResponse::err("worker channel closed", None);
}
match reply_rx.recv_timeout(WORKER_RESPONSE_TIMEOUT) {
Ok(r) => r,
Err(_) => ControlResponse::err(
"worker did not respond within timeout",
Some("the pipeline may be wedged; check the supervisor log".into()),
),
}
}
}
pub(crate) struct ControlPlane {
_listener: Option<ListenerHandle>,
rx: Option<crossbeam_channel::Receiver<ControlEnvelope>>,
}
impl ControlPlane {
pub(crate) fn spawn(cfg: &FluxConfig) -> Self {
let disabled = Self {
_listener: None,
rx: None,
};
if !cfg.control.enabled {
return disabled;
}
let socket_path = cfg
.control
.socket_path
.clone()
.unwrap_or_else(control::default_socket_path);
let (tx, rx) = crossbeam_channel::bounded::<ControlEnvelope>(CONTROL_CHANNEL_DEPTH);
let handler = ChannelHandler { tx };
match control::spawn(socket_path, handler) {
Ok(handle) => Self {
_listener: Some(handle),
rx: Some(rx),
},
Err(e) => {
warn!(error = %e, "control socket failed to bind; live-reconfig disabled");
disabled
}
}
}
pub(crate) fn rx(&self) -> Option<&crossbeam_channel::Receiver<ControlEnvelope>> {
self.rx.as_ref()
}
}
fn command_label(cmd: &ControlCommand) -> &'static str {
match cmd {
ControlCommand::ListPresets => "list_presets",
ControlCommand::CurrentPreset => "current_preset",
ControlCommand::ListEffects => "list_effects",
ControlCommand::GetConfig { .. } => "get_config",
ControlCommand::SetPreset { .. } => "set_preset",
ControlCommand::Set { .. } => "set",
ControlCommand::SetChain { .. } => "set_chain",
ControlCommand::SetEnabled { .. } => "set_enabled",
ControlCommand::Reload => "reload",
ControlCommand::SavePreset => "save_preset",
ControlCommand::SavePresetAs { .. } => "save_preset_as",
ControlCommand::ConfigPath => "config_path",
ControlCommand::DaemonInfo => "daemon_info",
_ => "unknown",
}
}
fn apply_read_only_command(
session: &ControlSession,
cmd: &ControlCommand,
) -> Option<ControlResponse> {
let response = match cmd {
ControlCommand::ListPresets => {
let names: Vec<&str> = session.cfg.presets.keys().map(String::as_str).collect();
ControlResponse::ok_with(serde_json::json!(names))
}
ControlCommand::CurrentPreset => {
ControlResponse::ok_with(serde_json::json!(session.active_preset_name))
}
ControlCommand::GetConfig { path } => {
apply_get_config_command(&session.active_preset, path.as_deref())
}
ControlCommand::ListEffects => apply_list_effects_command(),
ControlCommand::ConfigPath => apply_config_path_command(session.config_path.as_deref()),
ControlCommand::DaemonInfo => apply_daemon_info_command(&session.cfg),
_ => return None,
};
Some(response)
}
fn apply_offline_command(session: &ControlSession, cmd: &ControlCommand) -> ControlResponse {
apply_read_only_command(session, cmd).unwrap_or_else(|| {
ControlResponse::err(
"pipeline is not running (waiting for the camera)",
Some("read-only commands keep working; retry once the camera is back".into()),
)
})
}
fn apply_control_command(
session: &mut ControlSession,
processing_ctx: &ProcessingContext,
chain: &mut EffectChain,
telemetry: &fluxframe_core::EffectTelemetry,
cmd: ControlCommand,
) -> ControlResponse {
if let Some(response) = apply_read_only_command(session, &cmd) {
return response;
}
let ControlSession {
cfg,
config_path,
config_base,
active_preset_name,
active_preset,
} = session;
let config_path = config_path.as_deref();
match cmd {
ControlCommand::SetPreset { name } => {
let Some(new_preset) = cfg.presets.get(&name) else {
let available: Vec<&str> = cfg.presets.keys().map(String::as_str).collect();
return ControlResponse::err(
format!("preset '{name}' not defined"),
Some(format!("available: {}", available.join(", "))),
);
};
let mut new_chain = match preset::build_chain(&name, new_preset, config_base) {
Ok(c) => c,
Err(e) => return ControlResponse::err(format!("build chain failed: {e}"), None),
};
if let Err(e) = new_chain.prepare_all(processing_ctx) {
return ControlResponse::err(
format!("prepare failed: {e}"),
Some(format!(
"preset '{name}' parsed but did not initialise at runtime"
)),
);
}
std::mem::swap(chain, &mut new_chain);
if let Err(e) = new_chain.shutdown_all() {
warn!(error = %e, "old chain shutdown reported an error");
}
active_preset_name.clone_from(&name);
*active_preset = new_preset.clone();
info!(preset = %name, "control: swapped active preset");
ControlResponse::ok()
}
ControlCommand::Set { path, value } => {
apply_set_command(chain, active_preset, config_base, &path, value)
}
ControlCommand::SetChain {
section,
chain: new_names,
} => apply_set_chain_command(
chain,
active_preset,
telemetry,
section,
&new_names,
config_base,
),
ControlCommand::SetEnabled {
section,
effect,
enabled,
} => apply_set_enabled_command(chain, active_preset, telemetry, section, &effect, enabled),
ControlCommand::Reload => apply_reload_command(
cfg,
config_path,
processing_ctx,
chain,
active_preset_name,
active_preset,
),
ControlCommand::SavePreset => {
apply_save_preset_command(cfg, config_path, active_preset_name, active_preset)
}
ControlCommand::SavePresetAs { name } => {
apply_save_preset_as_command(cfg, config_path, active_preset, &name)
}
_ => ControlResponse::err(
"unknown command — daemon was built without support for this wire variant",
Some("update the daemon, or check the client is not ahead of the daemon".into()),
),
}
}
fn apply_save_preset_command(
cfg: &mut FluxConfig,
config_path: Option<&std::path::Path>,
active_preset_name: &str,
active_preset: &Preset,
) -> ControlResponse {
let Some(path) = config_path else {
return ControlResponse::err(
"daemon has no writable config path",
Some(
"restart the daemon with --config <PATH> or without --no-default-config to enable Save"
.into(),
),
);
};
if let Err(e) = crate::persist::save_preset(path, active_preset_name, active_preset) {
return ControlResponse::err(
format!("save failed: {e}"),
Some(format!("path: {}", path.display())),
);
}
cfg.presets
.insert(active_preset_name.to_string(), active_preset.clone());
info!(
path = %path.display(),
preset = %active_preset_name,
"control: saved active preset to disk",
);
ControlResponse::ok()
}
fn apply_save_preset_as_command(
cfg: &mut FluxConfig,
config_path: Option<&std::path::Path>,
active_preset: &Preset,
new_name: &str,
) -> ControlResponse {
let Some(path) = config_path else {
return ControlResponse::err(
"daemon has no writable config path",
Some(
"restart the daemon with --config <PATH> or without --no-default-config to enable Save"
.into(),
),
);
};
if cfg.presets.contains_key(new_name) {
return ControlResponse::err(
format!("preset '{new_name}' already exists"),
Some("pick a different name or use Save to overwrite the active preset".into()),
);
}
if let Err(e) = crate::persist::save_preset_as(path, new_name, active_preset) {
return ControlResponse::err(
format!("save-as failed: {e}"),
Some(format!("path: {}", path.display())),
);
}
cfg.presets
.insert(new_name.to_string(), active_preset.clone());
info!(
path = %path.display(),
preset = %new_name,
"control: saved active preset under new name",
);
ControlResponse::ok()
}
fn apply_config_path_command(config_path: Option<&std::path::Path>) -> ControlResponse {
match config_path {
Some(p) => ControlResponse::ok_with(serde_json::json!({ "path": p })),
None => ControlResponse::ok_with(serde_json::Value::Null),
}
}
fn apply_daemon_info_command(cfg: &FluxConfig) -> ControlResponse {
use fluxframe_core::{DaemonInfo, OutputInfo};
let output = match classify_output(cfg) {
OutputSpec::V4l2(device) => OutputInfo::V4l2 { device },
OutputSpec::Pipewire(node) => OutputInfo::Pipewire { node },
OutputSpec::Auto => OutputInfo::Auto,
OutputSpec::Fake => OutputInfo::Fakesink,
OutputSpec::Unsupported(device) => {
return ControlResponse::err(format!("output '{device}' is not supported"), None);
}
};
match serde_json::to_value(DaemonInfo { output }) {
Ok(data) => ControlResponse::ok_with(data),
Err(e) => ControlResponse::err(format!("serialise failed: {e}"), None),
}
}
fn apply_list_effects_command() -> ControlResponse {
static CACHE: OnceLock<serde_json::Value> = OnceLock::new();
let payload = CACHE.get_or_init(|| {
use fluxframe_effects::{mask_effects, plane_effects};
let mask: Vec<_> = mask_effects::default_registry().iter_metadata().collect();
let background: Vec<_> = plane_effects::default_registry().iter_metadata().collect();
let foreground = background.clone();
#[cfg(feature = "ml")]
let post: Vec<_> = fluxframe_effects::post_effects::default_registry()
.iter_metadata()
.collect();
#[cfg(not(feature = "ml"))]
let post: Vec<&'static fluxframe_core::EffectMetadata> = Vec::new();
#[allow(
unused_mut,
reason = "slim build leaves `features` empty; mut is needed when any feature is enabled"
)]
let mut features: Vec<&'static str> = Vec::new();
#[cfg(feature = "ml")]
features.push("ml");
#[cfg(feature = "image-fill")]
features.push("image-fill");
serde_json::json!({
"mask": mask,
"background": background,
"foreground": foreground,
"post": post,
"build_features": features,
})
});
ControlResponse::ok_with(payload.clone())
}
fn apply_reload_command(
cfg: &mut FluxConfig,
config_path: Option<&std::path::Path>,
processing_ctx: &ProcessingContext,
chain: &mut EffectChain,
active_preset_name: &mut String,
active_preset: &mut Preset,
) -> ControlResponse {
let Some(path) = config_path else {
return ControlResponse::err(
"no config path provided at startup",
Some("pass --config <PATH> on the command line to enable reload".into()),
);
};
let new_cfg = match crate::config_merge::load(Some(path)) {
Ok(c) => c,
Err(e) => {
return ControlResponse::err(
format!("re-read failed: {e}"),
Some(format!("path: {}", path.display())),
);
}
};
if let Err(e) = new_cfg.validate() {
return ControlResponse::err(format!("validation failed: {e}"), None);
}
let Some(new_preset) = new_cfg.presets.get(active_preset_name) else {
let available: Vec<&str> = new_cfg.presets.keys().map(String::as_str).collect();
return ControlResponse::err(
format!("active preset '{active_preset_name}' is gone from the reloaded config"),
Some(format!(
"available presets after reload: {}",
available.join(", ")
)),
);
};
let config_base = ConfigBase::for_config(Some(path));
let mut new_chain = match preset::build_chain(active_preset_name, new_preset, &config_base) {
Ok(c) => c,
Err(e) => return ControlResponse::err(format!("build chain failed: {e}"), None),
};
if let Err(e) = new_chain.prepare_all(processing_ctx) {
return ControlResponse::err(
format!("prepare on reloaded chain failed: {e}"),
Some("the live chain is unchanged".into()),
);
}
std::mem::swap(chain, &mut new_chain);
if let Err(e) = new_chain.shutdown_all() {
warn!(error = %e, "old chain shutdown reported an error during reload");
}
*active_preset = new_preset.clone();
*cfg = new_cfg;
info!(path = %path.display(), preset = %active_preset_name, "control: reloaded config from disk");
ControlResponse::ok()
}
fn apply_get_config_command(active_preset: &Preset, path: Option<&str>) -> ControlResponse {
let full = match serde_json::to_value(active_preset) {
Ok(v) => v,
Err(e) => return ControlResponse::err(format!("serialise failed: {e}"), None),
};
let Some(path) = path else {
return ControlResponse::ok_with(full);
};
let mut current = &full;
for component in path.split('.') {
if component.is_empty() {
return ControlResponse::err(format!("empty component in path '{path}'"), None);
}
match current.get(component) {
Some(v) => current = v,
None => {
return ControlResponse::err(
format!("path '{path}' has no value at '{component}'"),
None,
);
}
}
}
ControlResponse::ok_with(current.clone())
}
fn apply_set_command(
chain: &mut EffectChain,
active_preset: &mut Preset,
config_base: &ConfigBase,
path: &str,
value: serde_json::Value,
) -> ControlResponse {
let set_path = match crate::control::commands::parse_set_path(path) {
Ok(p) => p,
Err(e) => return ControlResponse::err(e, None),
};
if set_path.field == fluxframe_core::EFFECT_ENABLED_KEY {
return ControlResponse::err(
format!(
"`{}` is not an effect parameter",
fluxframe_core::EFFECT_ENABLED_KEY
),
Some("use set_enabled to switch an effect on or off".into()),
);
}
let toml_value = match crate::control::commands::json_to_toml(value) {
Ok(v) => v,
Err(e) => return ControlResponse::err(e, None),
};
let (section_mut, was_absent) = match set_target_section(active_preset, set_path.section) {
Ok(target) => target,
Err(response) => return response,
};
let original_entry = section_mut.per_effect.get(&set_path.effect).cloned();
let mut effect_table = match original_entry.clone() {
Some(toml::Value::Table(t)) => t,
_ => toml::Table::new(),
};
effect_table.insert(set_path.field.clone(), toml_value);
let merged_entry = toml::Value::Table(effect_table);
let metadata = effect_metadata(set_path.section, &set_path.effect);
let result = live_effect_params(&set_path.effect, Some(&merged_entry), metadata, config_base)
.and_then(|params| {
chain.reconfigure_named_effect(set_path.section, &set_path.effect, params)
});
section_mut
.per_effect
.insert(set_path.effect.clone(), merged_entry);
match result {
Ok(()) => {
info!(
section = %set_path.section,
effect = %set_path.effect,
field = %set_path.field,
"control: live-reconfigured effect"
);
ControlResponse::ok()
}
Err(e) => {
tracing::debug!(
section = %set_path.section,
effect = %set_path.effect,
field = %set_path.field,
error = %e,
"control: set rejected",
);
match &original_entry {
Some(v) => {
section_mut
.per_effect
.insert(set_path.effect.clone(), v.clone());
}
None => {
section_mut.per_effect.remove(&set_path.effect);
}
}
let revert = live_effect_params(
&set_path.effect,
original_entry.as_ref(),
metadata,
config_base,
)
.and_then(|params| {
chain.reconfigure_named_effect(set_path.section, &set_path.effect, params)
});
if let Err(revert_err) = revert {
warn!(
section = %set_path.section,
effect = %set_path.effect,
error = %revert_err,
"control: revert reconfigure also failed; live effect may be in an inconsistent state",
);
}
revert_absent_section_if_empty(active_preset, set_path.section, was_absent);
effect_error_response(&e)
}
}
}
fn set_target_section(
preset: &mut Preset,
section: SubchainKind,
) -> Result<(&mut fluxframe_core::PipelineSection, bool), ControlResponse> {
let was_absent = section_is_absent(preset, section);
if section != SubchainKind::Mask {
return Ok((
ensure_plane_or_post_section_mut(preset, section),
was_absent,
));
}
mask_section_mut(preset)
.map(|mask| (mask, was_absent))
.ok_or_else(|| {
ControlResponse::err(
"preset does not have a [mask] sub-section",
Some(
"this preset has no segmentation; switch to a preset with [mask] to add post-process effects"
.into(),
),
)
})
}
fn live_effect_params(
effect: &str,
table: Option<&toml::Value>,
metadata: Option<&fluxframe_core::EffectMetadata>,
config_base: &ConfigBase,
) -> Result<fluxframe_core::traits::RawEffectParams, fluxframe_core::EffectError> {
let (_, mut params) = fluxframe_core::split_effect_table(effect, table)?;
if let Some(metadata) = metadata {
fluxframe_core::resolve_path_params(&mut params, metadata, config_base);
}
Ok(toml::Value::Table(params))
}
fn effect_metadata(
section: SubchainKind,
name: &str,
) -> Option<&'static fluxframe_core::EffectMetadata> {
match section {
SubchainKind::Mask => fluxframe_effects::mask_effects::default_registry().metadata(name),
SubchainKind::Background | SubchainKind::Foreground => {
fluxframe_effects::plane_effects::default_registry().metadata(name)
}
#[cfg(feature = "ml")]
SubchainKind::Post => fluxframe_effects::post_effects::default_registry().metadata(name),
#[cfg(not(feature = "ml"))]
SubchainKind::Post => None,
}
}
fn mask_section_mut(preset: &mut Preset) -> Option<&mut fluxframe_core::PipelineSection> {
preset.mask.as_mut()
}
fn ensure_plane_or_post_section_mut(
preset: &mut Preset,
section: SubchainKind,
) -> &mut fluxframe_core::PipelineSection {
let slot: &mut Option<fluxframe_core::PipelineSection> = match section {
SubchainKind::Background => &mut preset.background,
SubchainKind::Foreground => &mut preset.foreground,
SubchainKind::Post => &mut preset.post,
SubchainKind::Mask => {
debug_assert!(
false,
"ensure_plane_or_post_section_mut called with Mask — use mask_section_mut"
);
return preset.mask.get_or_insert_with(|| {
tracing::info!(
section = "mask",
"materialised absent mask section on demand (fallback)"
);
fluxframe_core::PipelineSection::default()
});
}
};
if slot.is_none() {
tracing::info!(section = %section, "materialised absent sub-section on demand");
}
slot.get_or_insert_with(Default::default)
}
#[cfg(feature = "ml")]
fn apply_set_chain_command(
chain: &mut EffectChain,
active_preset: &mut Preset,
telemetry: &fluxframe_core::EffectTelemetry,
section: SubchainKind,
new_names: &[String],
config_base: &ConfigBase,
) -> ControlResponse {
let Some(composite) = chain.composite_mut() else {
return ControlResponse::err(
"active chain has no composite (preset has no [mask] section)",
Some(
"this preset has no segmentation; switch to a preset with [mask] to add post-process effects"
.into(),
),
);
};
let was_absent = section_is_absent(active_preset, section);
let section_data = if section == SubchainKind::Mask {
let Some(s) = mask_section_mut(active_preset) else {
debug_assert!(
false,
"internal: composite present but active preset has no [mask] section"
);
return ControlResponse::err(
"internal: composite present but mask section missing",
Some("this is a bug; please report".into()),
);
};
s
} else {
ensure_plane_or_post_section_mut(active_preset, section)
};
let old_names = section_data.chain.clone();
let result =
build_and_configure_subchain(section, new_names, §ion_data.per_effect, config_base);
let payload = match result {
Ok(o) => o,
Err(e) => {
revert_absent_section_if_empty(active_preset, section, was_absent);
return ControlResponse::err(e.reason, e.hint);
}
};
match composite.replace_subchain(payload) {
Ok(()) => {
let section_data = match section {
SubchainKind::Mask => mask_section_mut(active_preset)
.expect("mask presence checked above and not removed since"),
SubchainKind::Background | SubchainKind::Foreground | SubchainKind::Post => {
ensure_plane_or_post_section_mut(active_preset, section)
}
};
section_data.chain = new_names.to_vec();
section_data.per_effect.retain(|key, _| {
new_names.iter().any(|n| n == key)
|| fluxframe_core::PipelineSection::is_reserved_key(key)
});
for gone in old_names.iter().filter(|n| !new_names.contains(n)) {
telemetry.forget_stage(section.as_str(), gone);
}
info!(
section = %section,
chain = ?new_names,
disabled = ?composite.disabled_effects(section),
"control: replaced sub-chain"
);
ControlResponse::ok()
}
Err(e) => {
revert_absent_section_if_empty(active_preset, section, was_absent);
ControlResponse::err(
format!("prepare on new chain failed: {e}"),
Some("the previous chain is still active".into()),
)
}
}
}
fn section_is_absent(preset: &Preset, section: SubchainKind) -> bool {
match section {
SubchainKind::Mask => preset.mask.is_none(),
SubchainKind::Background => preset.background.is_none(),
SubchainKind::Foreground => preset.foreground.is_none(),
SubchainKind::Post => preset.post.is_none(),
}
}
fn revert_absent_section_if_empty(
active_preset: &mut Preset,
section: SubchainKind,
was_absent: bool,
) {
if !was_absent {
return;
}
let now_empty = match section {
SubchainKind::Mask => active_preset
.mask
.as_ref()
.is_some_and(|s| s.chain.is_empty() && s.per_effect.is_empty()),
SubchainKind::Background => active_preset
.background
.as_ref()
.is_some_and(|s| s.chain.is_empty() && s.per_effect.is_empty()),
SubchainKind::Foreground => active_preset
.foreground
.as_ref()
.is_some_and(|s| s.chain.is_empty() && s.per_effect.is_empty()),
SubchainKind::Post => active_preset
.post
.as_ref()
.is_some_and(|s| s.chain.is_empty() && s.per_effect.is_empty()),
};
if now_empty {
match section {
SubchainKind::Mask => active_preset.mask = None,
SubchainKind::Background => active_preset.background = None,
SubchainKind::Foreground => active_preset.foreground = None,
SubchainKind::Post => active_preset.post = None,
}
}
}
#[cfg(not(feature = "ml"))]
fn apply_set_chain_command(
_chain: &mut EffectChain,
_active_preset: &mut Preset,
_telemetry: &fluxframe_core::EffectTelemetry,
_section: SubchainKind,
_new_names: &[String],
_config_base: &ConfigBase,
) -> ControlResponse {
ControlResponse::err(
"set_chain unavailable: built without ml feature",
Some("rebuild with `--features fluxframe-cli/ml` to enable composite live-reconfig".into()),
)
}
#[cfg(feature = "ml")]
fn apply_set_enabled_command(
chain: &mut EffectChain,
active_preset: &mut Preset,
telemetry: &fluxframe_core::EffectTelemetry,
section: SubchainKind,
effect: &str,
enabled: bool,
) -> ControlResponse {
use fluxframe_core::EFFECT_ENABLED_KEY;
let section_data = match section {
SubchainKind::Mask => active_preset.mask.as_mut(),
SubchainKind::Background => active_preset.background.as_mut(),
SubchainKind::Foreground => active_preset.foreground.as_mut(),
SubchainKind::Post => active_preset.post.as_mut(),
};
let Some(section_data) = section_data else {
return ControlResponse::err(
format!("preset does not have a [{section}] sub-section"),
Some(format!("add effects to [{section}] before toggling them")),
);
};
if !section_data.chain.iter().any(|name| name == effect) {
return ControlResponse::err(
format!("no effect named '{effect}' in the '{section}' chain"),
Some(format!("chain: {}", section_data.chain.join(", "))),
);
}
if section_data
.per_effect
.get(effect)
.is_some_and(|entry| !entry.is_table())
{
return ControlResponse::err(
format!("[{section}.{effect}] is not a table"),
Some("fix the preset in fluxframe.toml and reload".into()),
);
}
let changed = match chain.set_effect_enabled(section, effect, enabled) {
Ok(changed) => changed,
Err(e) => {
tracing::debug!(
section = %section,
effect,
enabled,
error = %e,
"control: set_enabled rejected",
);
return effect_error_response(&e);
}
};
if enabled {
if let Some(toml::Value::Table(table)) = section_data.per_effect.get_mut(effect) {
table.remove(EFFECT_ENABLED_KEY);
if table.is_empty() {
section_data.per_effect.remove(effect);
}
}
} else {
let entry = section_data
.per_effect
.entry(effect.to_string())
.or_insert_with(|| toml::Value::Table(toml::Table::new()));
if let toml::Value::Table(table) = entry {
table.insert(EFFECT_ENABLED_KEY.into(), toml::Value::Boolean(false));
}
telemetry.forget_stage(section.as_str(), effect);
}
info!(section = %section, effect, enabled, changed, "control: toggled effect");
ControlResponse::ok()
}
#[cfg(not(feature = "ml"))]
fn apply_set_enabled_command(
_chain: &mut EffectChain,
_active_preset: &mut Preset,
_telemetry: &fluxframe_core::EffectTelemetry,
_section: SubchainKind,
_effect: &str,
_enabled: bool,
) -> ControlResponse {
ControlResponse::err(
"set_enabled unavailable: built without ml feature",
Some("rebuild with `--features fluxframe-cli/ml` to enable composite live-reconfig".into()),
)
}
fn effect_error_response(e: &fluxframe_core::EffectError) -> ControlResponse {
match e {
fluxframe_core::EffectError::InvalidConfig { reason, hint, .. } => {
ControlResponse::err(reason.clone(), hint.clone())
}
other => ControlResponse::err(format!("{other}"), None),
}
}
#[cfg(feature = "ml")]
struct SubChainError {
reason: String,
hint: Option<String>,
}
#[cfg(feature = "ml")]
#[allow(
clippy::too_many_lines,
reason = "four enum arms × build+configure pattern; trait-object types differ so each arm is its own monomorphisation"
)]
fn build_and_configure_subchain(
section: SubchainKind,
names: &[String],
per_effect: &std::collections::BTreeMap<String, toml::Value>,
config_base: &ConfigBase,
) -> Result<fluxframe_effects::composite::SubChainPayload, SubChainError> {
use fluxframe_effects::composite::{Slot, SubChainPayload};
use fluxframe_effects::{mask_effects, plane_effects, post_effects};
trait Configure {
fn configure_mut(
&mut self,
params: fluxframe_core::traits::RawEffectParams,
) -> Result<(), fluxframe_core::EffectError>;
}
impl Configure for dyn fluxframe_core::MaskEffect {
fn configure_mut(
&mut self,
params: fluxframe_core::traits::RawEffectParams,
) -> Result<(), fluxframe_core::EffectError> {
self.configure(params)
}
}
impl Configure for dyn fluxframe_core::PlaneEffect {
fn configure_mut(
&mut self,
params: fluxframe_core::traits::RawEffectParams,
) -> Result<(), fluxframe_core::EffectError> {
self.configure(params)
}
}
impl Configure for dyn fluxframe_core::PostEffect {
fn configure_mut(
&mut self,
params: fluxframe_core::traits::RawEffectParams,
) -> Result<(), fluxframe_core::EffectError> {
self.configure(params)
}
}
fn configure_each<E>(
chain: Vec<Box<E>>,
names: &[String],
per_effect: &std::collections::BTreeMap<String, toml::Value>,
lookup_metadata: impl Fn(&str) -> Option<&'static fluxframe_core::EffectMetadata>,
config_base: &ConfigBase,
) -> Result<Vec<Slot<E>>, SubChainError>
where
E: ?Sized + Configure,
{
chain
.into_iter()
.zip(names.iter())
.map(|(mut effect, name)| {
let resolved = fluxframe_core::resolve_effect_params(
name,
per_effect.get(name),
lookup_metadata(name),
config_base,
)
.map_err(configure_error)?;
effect
.configure_mut(resolved.params)
.map_err(configure_error)?;
Ok(Slot::new(effect, resolved.enabled))
})
.collect()
}
fn configure_error(e: fluxframe_core::EffectError) -> SubChainError {
match e {
fluxframe_core::EffectError::InvalidConfig { reason, hint, .. } => {
SubChainError { reason, hint }
}
other => SubChainError {
reason: format!("configure failed: {other}"),
hint: None,
},
}
}
fn build_error(section: SubchainKind, e: &fluxframe_core::EffectError) -> SubChainError {
SubChainError {
reason: format!("{section} chain build failed: {e}"),
hint: None,
}
}
match section {
SubchainKind::Mask => {
let registry = mask_effects::default_registry();
let built = registry
.build_chain(names)
.map_err(|e| build_error(section, &e))?;
let slots = configure_each::<dyn fluxframe_core::MaskEffect>(
built,
names,
per_effect,
|n| registry.metadata(n),
config_base,
)?;
Ok(SubChainPayload::Mask(slots))
}
SubchainKind::Background | SubchainKind::Foreground => {
let registry = plane_effects::default_registry();
let built = registry
.build_chain(names)
.map_err(|e| build_error(section, &e))?;
let slots = configure_each::<dyn fluxframe_core::PlaneEffect>(
built,
names,
per_effect,
|n| registry.metadata(n),
config_base,
)?;
Ok(if section == SubchainKind::Background {
SubChainPayload::Background(slots)
} else {
SubChainPayload::Foreground(slots)
})
}
SubchainKind::Post => {
let registry = post_effects::default_registry();
let built = registry
.build_chain(names)
.map_err(|e| build_error(section, &e))?;
let slots = configure_each::<dyn fluxframe_core::PostEffect>(
built,
names,
per_effect,
|n| registry.metadata(n),
config_base,
)?;
Ok(SubChainPayload::Post(slots))
}
}
}
const WORKER_POLL_TIMEOUT: Duration = Duration::from_millis(50);
const DROPPED_SYNC_INTERVAL: u64 = 30;
static REGISTERED_TOKENS: OnceLock<Mutex<Vec<Weak<RunToken>>>> = OnceLock::new();
static SHUTDOWN_REQUESTED: AtomicBool = AtomicBool::new(false);
fn tokens_registry() -> &'static Mutex<Vec<Weak<RunToken>>> {
REGISTERED_TOKENS.get_or_init(|| Mutex::new(Vec::new()))
}
static OUTPUT_INVISIBLE_MS_TOTAL: AtomicU64 = AtomicU64::new(0);
static OUTPUT_REBUILDS_TOTAL: AtomicU64 = AtomicU64::new(0);
static OUTPUT_DOWN_SINCE_MS: AtomicU64 = AtomicU64::new(0);
fn process_epoch() -> Instant {
static EPOCH: OnceLock<Instant> = OnceLock::new();
*EPOCH.get_or_init(Instant::now)
}
fn elapsed_ms_since_epoch() -> u64 {
u64::try_from(process_epoch().elapsed().as_millis()).unwrap_or(u64::MAX)
}
pub(crate) fn mark_output_live() {
let since = OUTPUT_DOWN_SINCE_MS.swap(0, Ordering::Relaxed);
if since == 0 {
return;
}
OUTPUT_REBUILDS_TOTAL.fetch_add(1, Ordering::Relaxed);
let down_ms = elapsed_ms_since_epoch().saturating_sub(since);
OUTPUT_INVISIBLE_MS_TOTAL.fetch_add(down_ms, Ordering::Relaxed);
info!(
down_ms,
invisible_ms_total = OUTPUT_INVISIBLE_MS_TOTAL.load(Ordering::Relaxed),
rebuilds_total = OUTPUT_REBUILDS_TOTAL.load(Ordering::Relaxed),
"loopback output back up — clients can enumerate the camera again"
);
}
pub(crate) fn mark_output_down(reason: Option<&FluxError>) {
let now = elapsed_ms_since_epoch().max(1);
let _ = OUTPUT_DOWN_SINCE_MS.compare_exchange(0, now, Ordering::Relaxed, Ordering::Relaxed);
if let Some(e) = reason {
warn!(error = %e, "loopback output torn down — camera unavailable to clients");
} else {
info!("loopback output torn down (clean exit)");
}
}
#[must_use]
pub(crate) fn is_shutdown_requested() -> bool {
SHUTDOWN_REQUESTED.load(Ordering::Relaxed)
}
pub(crate) fn wait_for_shutdown(total: Duration) -> bool {
let deadline = Instant::now() + total;
while Instant::now() < deadline {
if is_shutdown_requested() {
return true;
}
let remaining = deadline.saturating_duration_since(Instant::now());
std::thread::sleep(remaining.min(Duration::from_millis(100)));
}
is_shutdown_requested()
}
pub(crate) fn wait_serving_control(
total: Duration,
control_rx: Option<&crossbeam_channel::Receiver<ControlEnvelope>>,
session: &ControlSession,
) -> bool {
let Some(rx) = control_rx else {
return wait_for_shutdown(total);
};
let deadline = Instant::now() + total;
loop {
let step = deadline
.saturating_duration_since(Instant::now())
.min(Duration::from_millis(100));
match rx.recv_timeout(step) {
Ok(envelope) => {
let _ = envelope
.reply_tx
.send(apply_offline_command(session, &envelope.cmd));
}
Err(crossbeam_channel::RecvTimeoutError::Timeout) => {}
Err(crossbeam_channel::RecvTimeoutError::Disconnected) => std::thread::sleep(step),
}
if is_shutdown_requested() {
return true;
}
if Instant::now() >= deadline {
return false;
}
}
}
pub(crate) fn ensure_ctrlc_handler() {
install_ctrlc_once();
}
struct RunToken {
flag: Arc<AtomicBool>,
slot: LatestFrameSlot,
}
fn install_ctrlc_once() {
static INSTALLED: OnceLock<()> = OnceLock::new();
INSTALLED.get_or_init(|| {
let result = ctrlc::set_handler(|| {
info!("Ctrl-C received - broadcasting shutdown");
SHUTDOWN_REQUESTED.store(true, Ordering::Relaxed);
let mut reg = tokens_registry()
.lock()
.expect("tokens registry poisoned");
reg.retain(|w| w.upgrade().is_some());
for token in reg.iter().filter_map(Weak::upgrade) {
token.flag.store(false, Ordering::Release);
token.slot.close();
}
});
if let Err(e) = result {
warn!(
error = %e,
"could not install Ctrl-C handler (another one is already set); continuing without one",
);
}
});
}
struct TokenGuard {
token: Arc<RunToken>,
}
impl Drop for TokenGuard {
fn drop(&mut self) {
let reg = tokens_registry();
let mut tokens = reg.lock().expect("tokens registry poisoned");
tokens.retain(|w| {
w.upgrade()
.is_some_and(|other| !Arc::ptr_eq(&other, &self.token))
});
}
}
fn register_token(slot: LatestFrameSlot) -> (TokenGuard, Arc<AtomicBool>) {
install_ctrlc_once();
let token = Arc::new(RunToken {
flag: Arc::new(AtomicBool::new(true)),
slot,
});
let flag = Arc::clone(&token.flag);
let weak = Arc::downgrade(&token);
tokens_registry()
.lock()
.expect("tokens registry poisoned")
.push(weak);
(TokenGuard { token }, flag)
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum InputSpec {
Testsrc,
V4l2(PathBuf),
Unsupported(String),
}
#[must_use]
pub(crate) fn classify_input(cfg: &FluxConfig) -> InputSpec {
match &cfg.input.device {
InputDevice::Testsrc => InputSpec::Testsrc,
InputDevice::Path(p) => InputSpec::V4l2(p.clone()),
InputDevice::Auto => InputSpec::Unsupported(
"auto (should have been handled in commands::run before classify_input)".into(),
),
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum OutputSpec {
Auto,
Fake,
V4l2(PathBuf),
Pipewire(Option<String>),
Unsupported(String),
}
#[must_use]
pub(crate) fn classify_output(cfg: &FluxConfig) -> OutputSpec {
let device = cfg.output.device.as_str();
if let Some(suffix) = device.strip_prefix("pipewire") {
if suffix.is_empty() {
return OutputSpec::Pipewire(None);
}
if let Some(rest) = suffix.strip_prefix(':') {
let trimmed = rest.trim();
return OutputSpec::Pipewire(if trimmed.is_empty() {
None
} else {
Some(trimmed.to_string())
});
}
}
match device {
"auto" => OutputSpec::Auto,
"fakesink" => OutputSpec::Fake,
other if other.starts_with("/dev/") => OutputSpec::V4l2(PathBuf::from(other)),
other => OutputSpec::Unsupported(other.to_string()),
}
}
#[tracing::instrument(skip_all, fields(sink = ?cfg.output.device, preset = %session.active_preset_name))]
pub(crate) fn run_testsrc_chain(
cfg: &FluxConfig,
session: &mut ControlSession,
control_rx: Option<&crossbeam_channel::Receiver<ControlEnvelope>>,
chain: EffectChain,
) -> Result<(), FluxError> {
run_chain(
cfg,
session,
control_rx,
chain,
"testsrc",
InputPipeline::build_testsrc,
)
}
#[tracing::instrument(skip_all, fields(device = %cfg.input.device, sink = ?cfg.output.device, preset = %session.active_preset_name))]
pub(crate) fn run_v4l2_chain(
cfg: &FluxConfig,
session: &mut ControlSession,
control_rx: Option<&crossbeam_channel::Receiver<ControlEnvelope>>,
chain: EffectChain,
) -> Result<(), FluxError> {
let device_path = match &cfg.input.device {
InputDevice::Path(p) => p.clone(),
other => {
return Err(FluxError::Config {
reason: format!(
"run_v4l2_chain invoked with non-path input device '{other}' (this is a CLI \
dispatch bug)",
),
hint: None,
});
}
};
let device_path_for_builder = device_path.clone();
run_chain(cfg, session, control_rx, chain, "v4l2src", move |params| {
let mode = fluxframe_gst::v4l2_caps::detect_native_mode(
&device_path_for_builder,
params.width,
params.height,
params.fps,
)?;
info!(
device = %device_path_for_builder.display(),
width = mode.width,
height = mode.height,
fps = mode.fps,
encoding = %mode.encoding,
"camera mode selected",
);
let resolved = InputParams::new(params.width, params.height, mode.fps, params.format);
InputPipeline::build_v4l2(&device_path_for_builder, &mode, resolved)
})
}
fn run_chain<F>(
cfg: &FluxConfig,
session: &mut ControlSession,
control_rx: Option<&crossbeam_channel::Receiver<ControlEnvelope>>,
mut chain: EffectChain,
source_label: &'static str,
input_builder: F,
) -> Result<(), FluxError>
where
F: Fn(InputParams) -> Result<InputPipeline, PipelineError>,
{
fluxframe_gst::init()?;
let metrics = RuntimeMetrics::new();
metrics
.counters
.set_processing_threads(rayon::current_num_threads() as u64);
let (output, mut processing_ctx, sink_label) = build_output(cfg)?;
processing_ctx.counters = Some(Arc::clone(&metrics.counters));
chain
.prepare_all(&processing_ctx)
.map_err(FluxError::from)?;
let (effective_out_w, effective_out_h) = cfg
.output
.effective_dimensions(cfg.input.width, cfg.input.height);
info!(
source = source_label,
sink = sink_label,
effects = ?chain.names(),
input_w = cfg.input.width,
input_h = cfg.input.height,
input_fps = cfg.input.fps,
output_w = effective_out_w,
output_h = effective_out_h,
output_scale = cfg.output.scale.value(),
input_format = ?cfg.input.format,
output_format = ?cfg.output.format,
"starting pipeline ({source_label} -> {sink_label})",
);
output.start()?;
mark_output_live();
let input = match prepare_input(
cfg,
&input_builder,
&output,
&metrics,
&mut chain,
control_rx,
session,
) {
Ok(Some(input)) => input,
Ok(None) => {
mark_output_down(None);
return Ok(());
}
Err(e) => {
mark_output_down(Some(&e));
return Err(e);
}
};
let slot = input.slot();
let (_token_guard, running) = register_token(slot.clone());
let bus_error: Arc<Mutex<Option<FluxError>>> = Arc::new(Mutex::new(None));
let input_failure = Arc::new(InputFailureSignal::new());
let _bus_listener = build_bus_listener(
&input,
&output,
Arc::clone(&running),
Arc::clone(&bus_error),
slot.clone(),
Arc::clone(&input_failure),
);
let _reporter = spawn_metrics_reporter(cfg, &metrics, &running);
let base = &session.config_base;
let mut idle_runtime = build_idle_runtime(cfg, base, &input, &output, &running, &metrics);
if supervised_acquire(cfg) && idle_runtime.is_some() {
input_failure.arm();
}
let process_result = run_supervised_loop(
WorkerDeps {
cfg,
processing_ctx: &processing_ctx,
metrics: &metrics,
control_rx,
},
session,
&running,
&slot,
&mut chain,
&output,
&mut idle_runtime,
SupervisedInput {
pipeline: &input,
failure: &input_failure,
},
);
running.store(false, Ordering::Release);
slot.close();
teardown(&input, &output, &mut chain);
metrics.sync_dropped(slot.dropped_count());
let snap = metrics.snapshot();
fluxframe_core::emit_metrics_line(&snap, None);
let bus_err = bus_error.lock().expect("bus_error mutex poisoned").take();
let outcome = match (process_result, bus_err) {
(Ok(()), Some(e)) | (Err(e), _) => Err(e),
(Ok(()), None) => Ok(()),
};
mark_output_down(outcome.as_ref().err());
outcome
}
fn teardown_partial(output: &OutputPipeline, chain: &mut EffectChain) {
if let Err(e) = output.stop() {
warn!(error = %e, "output.stop failed during acquire teardown");
}
if let Err(e) = chain.shutdown_all() {
warn!(error = %e, "chain shutdown reported an error during acquire teardown");
}
}
fn prepare_input<F>(
cfg: &FluxConfig,
input_builder: &F,
output: &OutputPipeline,
metrics: &RuntimeMetrics,
chain: &mut EffectChain,
control_rx: Option<&crossbeam_channel::Receiver<ControlEnvelope>>,
session: &ControlSession,
) -> Result<Option<Arc<InputPipeline>>, FluxError>
where
F: Fn(InputParams) -> Result<InputPipeline, PipelineError>,
{
let (out_w, out_h) = cfg
.output
.effective_dimensions(cfg.input.width, cfg.input.height);
let placeholder: Option<Box<dyn crate::idle::Placeholder>> = if supervised_acquire(cfg) {
match crate::idle::build_placeholder(
&cfg.idle.resolve_paths(&session.config_base),
out_w,
out_h,
) {
Ok(p) => Some(p),
Err(e) => {
warn!(error = %e, "failed to build acquire placeholder — falling back to single-attempt input acquisition");
None
}
}
} else {
None
};
match acquire_input(
cfg,
input_builder,
output,
metrics,
placeholder.as_deref(),
control_rx,
session,
) {
Ok(Some(input)) => Ok(Some(Arc::new(input))),
Ok(None) => {
teardown_partial(output, chain);
Ok(None)
}
Err(e) => {
teardown_partial(output, chain);
Err(e)
}
}
}
fn build_output(
cfg: &FluxConfig,
) -> Result<(OutputPipeline, ProcessingContext, &'static str), FluxError> {
let sink = resolve_output_sink(cfg)?;
let sink_label = output_sink_label(&sink);
let (sink_w, sink_h) = cfg
.output
.effective_dimensions(cfg.input.width, cfg.input.height);
let output_params = OutputParams::new(sink_w, sink_h, cfg.input.fps, cfg.input.format, sink)
.with_sink_format(cfg.output.format);
let output = OutputPipeline::build(output_params)?;
let processing_ctx = ProcessingContext {
width: cfg.input.width,
height: cfg.input.height,
format: cfg.input.format,
fps: cfg.input.fps,
counters: None,
};
Ok((output, processing_ctx, sink_label))
}
fn supervised_acquire(cfg: &FluxConfig) -> bool {
cfg.idle.enabled
&& matches!(classify_output(cfg), OutputSpec::V4l2(_))
&& matches!(classify_input(cfg), InputSpec::V4l2(_))
}
fn is_input_contention(e: &FluxError) -> bool {
matches!(
e,
FluxError::Pipeline(fluxframe_core::PipelineError::InputDeviceUnavailable { .. })
)
}
fn acquire_input<F>(
cfg: &FluxConfig,
input_builder: &F,
output: &OutputPipeline,
metrics: &RuntimeMetrics,
placeholder: Option<&dyn crate::idle::Placeholder>,
control_rx: Option<&crossbeam_channel::Receiver<ControlEnvelope>>,
session: &ControlSession,
) -> Result<Option<InputPipeline>, FluxError>
where
F: Fn(InputParams) -> Result<InputPipeline, PipelineError>,
{
let (ph_w, ph_h) = cfg
.output
.effective_dimensions(cfg.input.width, cfg.input.height);
let base = Duration::from_millis(u64::from(cfg.input.acquire_backoff_base_ms));
let max = Duration::from_millis(u64::from(cfg.input.acquire_backoff_max_ms));
let mut backoff = base;
let mut logged_kind: Option<String> = None;
loop {
if is_shutdown_requested() {
return Ok(None);
}
metrics.counters.inc_input_acquire_attempts();
let (capture_w, capture_h) = cfg.input.capture_dimensions();
let params = InputParams::new(capture_w, capture_h, cfg.input.fps, cfg.input.format);
let attempt = input_builder(params).and_then(|input| match input.start() {
Ok(()) => Ok(input),
Err(e) => {
let _ = input.set_state_null();
Err(e)
}
});
match attempt {
Ok(input) => return Ok(Some(input)),
Err(e) => {
let fe = FluxError::from(e);
let Some(placeholder) = placeholder.filter(|_| is_input_contention(&fe)) else {
return Err(fe);
};
let cont = backoff_after_contention(
&fe,
&mut logged_kind,
backoff,
placeholder,
ph_w,
ph_h,
cfg.input.format,
output,
metrics,
control_rx,
session,
)?;
if !cont {
return Ok(None);
}
backoff = (backoff * 2).min(max);
}
}
}
}
#[expect(
clippy::too_many_arguments,
reason = "extracted from acquire_input's loop purely to satisfy too-many-lines; \
the arguments are the acquire context and bundling them adds no clarity"
)]
fn backoff_after_contention(
fe: &FluxError,
logged_kind: &mut Option<String>,
backoff: Duration,
placeholder: &dyn crate::idle::Placeholder,
ph_w: u32,
ph_h: u32,
format: fluxframe_core::frame::PixelFormat,
output: &OutputPipeline,
metrics: &RuntimeMetrics,
control_rx: Option<&crossbeam_channel::Receiver<ControlEnvelope>>,
session: &ControlSession,
) -> Result<bool, FluxError> {
metrics.counters.inc_input_acquire_failures();
let kind = fe.to_string();
if logged_kind.as_deref() == Some(kind.as_str()) {
tracing::debug!(
target: "fluxframe::idle",
backoff_ms = backoff.as_millis() as u64,
"input still unavailable — retrying",
);
} else {
warn!(
target: "fluxframe::idle",
error = %kind,
backoff_ms = backoff.as_millis() as u64,
"input device unavailable — streaming placeholder, retrying with backoff",
);
*logged_kind = Some(kind);
}
push_placeholder(placeholder, ph_w, ph_h, format, output, metrics)?;
Ok(!wait_serving_control(backoff, control_rx, session))
}
fn build_bus_listener(
input: &InputPipeline,
output: &OutputPipeline,
running: Arc<AtomicBool>,
bus_error: Arc<Mutex<Option<FluxError>>>,
slot: LatestFrameSlot,
input_failure: Arc<InputFailureSignal>,
) -> BusListener {
let pipelines = vec![
WatchedPipeline {
source: BusSource::Input,
bus: input.bus(),
},
WatchedPipeline {
source: BusSource::Output,
bus: output.bus(),
},
];
BusListener::spawn(pipelines, move |event| {
on_bus_event(&event, &running, &bus_error, &slot, &input_failure);
})
}
const INPUT_RECOVERY_BUDGET: Duration = Duration::from_secs(60);
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum LoopAction {
ReacquireInput,
TeardownAll,
Exit,
}
fn next_action(running: bool, input_failed: bool, worker_failed: bool) -> LoopAction {
if worker_failed {
return LoopAction::TeardownAll;
}
if !running {
return LoopAction::Exit;
}
if input_failed {
LoopAction::ReacquireInput
} else {
LoopAction::Exit
}
}
#[expect(
clippy::too_many_arguments,
reason = "`session` is the one `&mut` collaborator and cannot ride in the `Copy` WorkerDeps"
)]
fn run_supervised_loop(
deps: WorkerDeps<'_>,
session: &mut ControlSession,
running: &AtomicBool,
slot: &LatestFrameSlot,
chain: &mut EffectChain,
output: &OutputPipeline,
idle: &mut Option<IdleRuntime>,
input: SupervisedInput<'_>,
) -> Result<(), FluxError> {
let mut entry_generation = input.failure.generation();
loop {
let watch = InputFailureWatch {
signal: input.failure,
entry_generation,
};
let worker_result = run_process_loop(
WorkerDeps { ..deps },
session,
running,
slot,
chain,
output,
idle.as_mut(),
watch,
);
let worker_failed = worker_result.is_err();
let action = next_action(
running.load(Ordering::Acquire),
watch.tripped(),
worker_failed,
);
match action {
LoopAction::Exit | LoopAction::TeardownAll => return worker_result,
LoopAction::ReacquireInput => {
entry_generation = recover_input(
deps.cfg,
deps.control_rx,
session,
input.pipeline,
output,
idle.as_mut(),
deps.metrics,
slot,
input.failure,
running,
)?;
}
}
}
}
#[allow(
clippy::too_many_arguments,
reason = "recovery context: every argument is a distinct collaborator the retry loop needs"
)]
fn recover_input(
cfg: &FluxConfig,
control_rx: Option<&crossbeam_channel::Receiver<ControlEnvelope>>,
session: &ControlSession,
input: &Arc<InputPipeline>,
output: &OutputPipeline,
idle: Option<&mut IdleRuntime>,
metrics: &RuntimeMetrics,
slot: &LatestFrameSlot,
signal: &InputFailureSignal,
running: &AtomicBool,
) -> Result<u64, FluxError> {
let started = Instant::now();
let placeholder = idle.as_ref().map(|rt| {
(
Arc::clone(&rt.placeholder),
rt.output_w,
rt.output_h,
rt.output_format,
)
});
if let Some(rt) = idle {
if let Some(handle) = rt.reload_handle.take() {
debug!("joining an in-flight reload before recovering the input");
if handle.join().is_err() {
warn!(
target: "fluxframe::idle",
"reload thread panicked; continuing with input recovery"
);
}
}
}
let push_fill = |metrics: &RuntimeMetrics| {
if let Some((ph, w, h, fmt)) = placeholder.as_ref() {
if let Err(e) = push_placeholder(ph.as_ref(), *w, *h, *fmt, output, metrics) {
warn!(error = %e, "placeholder push failed during input recovery");
}
}
};
push_fill(metrics);
if let Err(e) = input.set_state_null() {
warn!(error = %e, "set_state_null failed while recovering the input");
}
slot.clear();
let policy = RecoveryPolicy {
budget: INPUT_RECOVERY_BUDGET,
backoff_base: Duration::from_millis(u64::from(cfg.input.acquire_backoff_base_ms)),
backoff_max: Duration::from_millis(u64::from(cfg.input.acquire_backoff_max_ms)),
};
let generation = retry_reacquire(
&**input,
signal,
running,
&metrics.counters,
policy,
started,
|backoff| {
push_fill(metrics);
wait_serving_control(backoff, control_rx, session)
},
)?;
slot.clear();
Ok(generation)
}
trait Reacquire {
fn reacquire(&self) -> Result<(), FluxError>;
}
impl Reacquire for InputPipeline {
fn reacquire(&self) -> Result<(), FluxError> {
InputPipeline::reacquire(self).map_err(FluxError::from)
}
}
#[derive(Debug, Clone, Copy)]
struct RecoveryPolicy {
budget: Duration,
backoff_base: Duration,
backoff_max: Duration,
}
fn retry_reacquire(
target: &dyn Reacquire,
signal: &InputFailureSignal,
running: &AtomicBool,
counters: &fluxframe_core::metrics::Counters,
policy: RecoveryPolicy,
started: Instant,
mut pause: impl FnMut(Duration) -> bool,
) -> Result<u64, FluxError> {
let mut backoff = policy.backoff_base;
let mut attempt: u32 = 0;
loop {
if is_shutdown_requested() || !running.load(Ordering::Acquire) {
return Ok(signal.generation());
}
attempt += 1;
counters.inc_input_reacquire();
let generation = signal.generation();
match target.reacquire() {
Ok(()) => {
let down = started.elapsed();
counters.add_input_down_ms(u64::try_from(down.as_millis()).unwrap_or(u64::MAX));
info!(
attempt,
down_ms = down.as_millis() as u64,
"camera reacquired — output was never interrupted"
);
return Ok(generation);
}
Err(e) => {
counters.inc_input_reacquire_failures();
if started.elapsed() >= policy.budget {
warn!(
attempt,
elapsed_secs = started.elapsed().as_secs(),
error = %e,
"in-place camera recovery budget exhausted — restarting the run \
so the device can be re-selected"
);
return Err(e);
}
debug!(attempt, error = %e, "reacquire failed; will retry");
if pause(backoff) {
return Ok(signal.generation());
}
backoff = (backoff * 2).min(policy.backoff_max);
}
}
}
}
#[derive(Debug)]
pub(crate) struct InputFailureSignal {
generation: AtomicU64,
enabled: AtomicBool,
}
impl InputFailureSignal {
fn new() -> Self {
Self {
generation: AtomicU64::new(0),
enabled: AtomicBool::new(false),
}
}
fn arm(&self) {
self.enabled.store(true, Ordering::Release);
}
fn handles(&self, source: BusSource) -> bool {
self.enabled.load(Ordering::Acquire) && source == BusSource::Input
}
fn raise(&self) {
self.generation.fetch_add(1, Ordering::Release);
}
fn generation(&self) -> u64 {
self.generation.load(Ordering::Acquire)
}
}
fn on_bus_event(
event: &BusEvent,
running: &AtomicBool,
bus_error: &Mutex<Option<FluxError>>,
slot: &LatestFrameSlot,
input_failure: &InputFailureSignal,
) {
match event {
BusEvent::FatalError {
element,
message,
debug: debug_payload,
source,
} => {
if input_failure.handles(*source) {
warn!(
?source,
%element,
%message,
debug = ?debug_payload,
action = "reacquire",
"input pipeline failed — recovering without tearing the output down",
);
input_failure.raise();
return;
}
error!(
?source,
%element,
%message,
debug = ?debug_payload,
"bus fatal error",
);
if let Some(pipeline_err) = fluxframe_gst::translate_fatal(event) {
let mut guard = bus_error.lock().expect("bus_error mutex poisoned");
if guard.is_none() {
*guard = Some(FluxError::from(pipeline_err));
}
}
running.store(false, Ordering::Release);
slot.close();
}
BusEvent::Warning {
source,
element,
message,
debug: debug_payload,
} => {
warn!(
?source,
%element,
%message,
debug = ?debug_payload,
"bus warning",
);
}
BusEvent::Eos { source } => {
if input_failure.handles(*source) {
warn!(?source, action = "reacquire", "input pipeline reached EOS");
input_failure.raise();
return;
}
info!(?source, "pipeline EOS");
running.store(false, Ordering::Release);
slot.close();
}
_ => {
warn!(?event, "unhandled bus event variant");
}
}
}
fn spawn_metrics_reporter(
cfg: &FluxConfig,
metrics: &RuntimeMetrics,
running: &Arc<AtomicBool>,
) -> Option<MetricsReporter> {
let secs = cfg.realtime.metrics_interval_secs;
if secs == 0 {
tracing::debug!("metrics reporter disabled by config (metrics_interval_secs = 0)");
return None;
}
let interval = Duration::from_secs(u64::from(secs));
match MetricsReporter::spawn(metrics.clone(), interval, Arc::clone(running)) {
Ok(handle) => {
tracing::debug!(secs, "metrics reporter spawned");
Some(handle)
}
Err(e) => {
warn!(error = %e, "could not spawn metrics reporter; teardown summary only");
None
}
}
}
struct WorkerState {
frame_context: FrameContext,
framer: Framer,
framing_region: Region,
prev_fallback: bool,
frames_seen: u64,
}
impl WorkerState {
fn new(metrics: &RuntimeMetrics, cfg: &FluxConfig) -> Self {
let (capture_w, capture_h) = cfg.input.capture_dimensions();
let framer = Framer::new(capture_w, capture_h, cfg.input.width, cfg.input.height);
Self {
frame_context: FrameContext {
telemetry: metrics.effect_telemetry(),
..FrameContext::default()
},
framer,
framing_region: framer.full_view(),
prev_fallback: false,
frames_seen: 0,
}
}
}
fn drain_control_commands(
session: &mut ControlSession,
control_rx: Option<&crossbeam_channel::Receiver<ControlEnvelope>>,
processing_ctx: &ProcessingContext,
chain: &mut EffectChain,
telemetry: &fluxframe_core::EffectTelemetry,
) {
let Some(rx) = control_rx else {
return;
};
while let Ok(envelope) = rx.try_recv() {
let cmd_kind = command_label(&envelope.cmd);
let start = Instant::now();
let response =
apply_control_command(session, processing_ctx, chain, telemetry, envelope.cmd);
tracing::debug!(
command = cmd_kind,
elapsed_us = start.elapsed().as_micros() as u64,
"control command applied",
);
let _ = envelope.reply_tx.send(response);
}
}
const FRAMING_STAGE: StageKey = StageKey::new("framing", "crop_resize");
fn process_one_frame(
state: &mut WorkerState,
mut frame: fluxframe_core::frame::VideoFrame,
chain: &mut EffectChain,
output: &OutputPipeline,
metrics: &RuntimeMetrics,
slot: &LatestFrameSlot,
no_consumer: bool,
) -> Result<(), FluxError> {
let recv_at = Instant::now();
metrics.counters.inc_frames_in();
state.frames_seen += 1;
state.frame_context.frame_sequence = frame.meta.sequence;
state.frame_context.frame_timestamp = frame.meta.timestamp;
state.frame_context.fallback_active = false;
let pre_process = Instant::now();
let region = state.framing_region;
let (capture_w, capture_h) = state.framer.capture_size();
frame = match state.framer.apply(frame, ®ion) {
Ok(framed) => framed,
Err(e) => {
metrics.counters.inc_effect_error();
error!(error = %e, "framing stage failed; stopping");
return Err(FluxError::from(e));
}
};
state
.frame_context
.telemetry
.record_stage(FRAMING_STAGE, pre_process.elapsed());
state.frame_context.framing = Framing {
source: Some(FramingSource {
width: capture_w,
height: capture_h,
region,
}),
request: None,
};
if let Err(e) = chain.process(&mut frame, &mut state.frame_context) {
metrics.counters.inc_effect_error();
error!(error = %e, "effect chain failed; stopping");
return Err(FluxError::from(e));
}
metrics.processing.record_duration(pre_process.elapsed());
if !state.frame_context.fallback_active {
state.framing_region = state
.frame_context
.framing
.request
.unwrap_or_else(|| state.framer.full_view());
}
if state.frame_context.fallback_active != state.prev_fallback {
warn!(
frame_seq = state.frame_context.frame_sequence,
fallback_active = state.frame_context.fallback_active,
"effect-chain fallback state changed (passthrough frame)"
);
if state.frame_context.fallback_active {
metrics.counters.inc_fallback();
}
state.prev_fallback = state.frame_context.fallback_active;
}
let pre_push = Instant::now();
if let Err(e) = output.push_frame(frame) {
error!(error = %e, "output.push_frame failed; stopping");
return Err(e.into());
}
metrics.output.record_duration(pre_push.elapsed());
metrics.end_to_end.record_duration(recv_at.elapsed());
metrics.counters.inc_frames_out();
if no_consumer {
metrics.counters.inc_frames_out_while_no_consumer();
}
if state.frames_seen % DROPPED_SYNC_INTERVAL == 0 {
metrics.sync_dropped(slot.dropped_count());
}
Ok(())
}
fn active_allowed(level: crate::idle::IdleLevel, engine_ready: bool) -> bool {
matches!(level, crate::idle::IdleLevel::Active) && engine_ready
}
fn no_consumer_attached(idle: Option<&IdleRuntime>) -> bool {
idle.is_some_and(|rt| {
crate::idle::ConsumerStatus::from_u8(rt.consumer_status.load(Ordering::Acquire))
== crate::idle::ConsumerStatus::Absent
})
}
fn push_placeholder(
placeholder: &dyn crate::idle::Placeholder,
width: u32,
height: u32,
format: fluxframe_core::frame::PixelFormat,
output: &OutputPipeline,
metrics: &RuntimeMetrics,
) -> Result<(), FluxError> {
let frame = placeholder.render(width, height, format)?;
if let Err(e) = output.push_frame(frame) {
error!(error = %e, "output.push_frame failed during idle placeholder push");
return Err(e.into());
}
metrics.counters.inc_idle_frames_pushed();
Ok(())
}
struct IdleRuntime {
state_machine: crate::idle::IdleStateMachine,
consumer_status: Arc<std::sync::atomic::AtomicU8>,
placeholder: Arc<dyn crate::idle::Placeholder>,
output_w: u32,
output_h: u32,
output_format: fluxframe_core::frame::PixelFormat,
input: Arc<InputPipeline>,
engine_ready: Arc<AtomicBool>,
reload_handle: Option<std::thread::JoinHandle<crate::idle::reload::ResumeOutcome>>,
was_active: bool,
#[cfg(target_os = "linux")]
_detector: crate::idle::ConsumerDetector,
}
fn build_idle_runtime(
cfg: &FluxConfig,
config_base: &ConfigBase,
input: &Arc<InputPipeline>,
output: &OutputPipeline,
running: &Arc<AtomicBool>,
metrics: &RuntimeMetrics,
) -> Option<IdleRuntime> {
if !cfg.idle.enabled {
return None;
}
#[cfg(target_os = "linux")]
{
let sink = resolve_output_sink(cfg).ok()?;
let Some(device_path) = crate::idle::device_path(&sink) else {
warn!(
"idle.enabled = true but sink is not v4l2loopback — idle disabled \
(the consumer-presence detector needs a /dev/videoN device path for the \
inotify watch + /proc/*/fd walk)"
);
return None;
};
let my_pid = std::process::id();
let (sink_w, sink_h) = cfg
.output
.effective_dimensions(cfg.input.width, cfg.input.height);
let placeholder_format = cfg.input.format;
let placeholder: Arc<dyn crate::idle::Placeholder> = match crate::idle::build_placeholder(
&cfg.idle.resolve_paths(config_base),
sink_w,
sink_h,
) {
Ok(p) => p.into(),
Err(e) => {
warn!(error = %e, "failed to build idle placeholder — idle mode disabled");
return None;
}
};
let watch = match output.subscribe_consumer_events() {
Some(Ok(watch)) => Some(watch),
Some(Err(e)) => {
warn!(
error = %e,
"could not subscribe to loopback client-usage events \
(v4l2loopback older than 0.13?)"
);
None
}
None => None,
};
let detector_running = Arc::clone(running);
let detector = crate::idle::ConsumerDetector::spawn(
crate::idle::DetectorParams {
device_path,
my_pid,
poll_interval: std::time::Duration::from_millis(u64::from(
cfg.idle.poll_interval_ms,
)),
mode: cfg.idle.presence_source,
stale_balance_after: std::time::Duration::from_secs(u64::from(
cfg.idle.teardown_secs.max(1),
)),
teardown_grace: std::time::Duration::from_secs(u64::from(
cfg.idle.teardown_secs.max(1),
)),
resync_interval: (cfg.idle.resync_interval_secs > 0).then(|| {
std::time::Duration::from_secs(u64::from(cfg.idle.resync_interval_secs))
}),
},
detector_running,
Arc::clone(&metrics.counters),
watch,
);
let consumer_status = detector.status_handle();
Some(IdleRuntime {
state_machine: crate::idle::IdleStateMachine::new(Instant::now()),
consumer_status,
placeholder,
output_w: sink_w,
output_h: sink_h,
output_format: placeholder_format,
input: Arc::clone(input),
engine_ready: Arc::new(AtomicBool::new(true)),
reload_handle: None,
was_active: true,
_detector: detector,
})
}
#[cfg(not(target_os = "linux"))]
{
let _ = (config_base, input, running, metrics);
warn!(
target: "fluxframe::idle",
"idle mode requested but host is not Linux — idle disabled (the /proc/*/fd consumer detector is Linux-only)"
);
None
}
}
fn reap_reload(
reload_handle: &mut Option<std::thread::JoinHandle<crate::idle::reload::ResumeOutcome>>,
) -> Option<crate::idle::reload::ResumeOutcome> {
let handle = reload_handle.take()?;
if !handle.is_finished() {
*reload_handle = Some(handle);
return None;
}
if let Ok(outcome) = handle.join() {
Some(outcome)
} else {
warn!(target: "fluxframe::idle", "reload thread panicked");
None
}
}
fn handle_idle_edge(
idle: &mut IdleRuntime,
edge: crate::idle::IdleEdge,
slot: &LatestFrameSlot,
output: &OutputPipeline,
metrics: &RuntimeMetrics,
) {
use crate::idle::IdleEdge;
match edge {
IdleEdge::None => {}
IdleEdge::EnterIdle => {
metrics.counters.inc_idle_entered();
info!(target: "fluxframe::idle", "entering idle — tearing down input pipeline");
if let Err(e) = idle.input.set_state_null() {
warn!(error = %e, "set_state_null failed on idle entry");
}
slot.clear();
}
IdleEdge::ResumeActive => {
info!(target: "fluxframe::idle", "consumer reconnected — spawning reload thread");
if let Err(e) = push_placeholder(
idle.placeholder.as_ref(),
idle.output_w,
idle.output_h,
idle.output_format,
output,
metrics,
) {
warn!(error = %e, "resume-edge placeholder push failed");
}
if let Some(handle) = idle.reload_handle.take() {
if !handle.is_finished() {
warn!("a previous reload thread is still in flight; not spawning a second one");
idle.reload_handle = Some(handle);
return;
}
let _ = handle.join();
}
idle.engine_ready.store(false, Ordering::Release);
let input = Arc::clone(&idle.input);
let engine_ready = Arc::clone(&idle.engine_ready);
idle.reload_handle = Some(crate::idle::reload::spawn_reload_thread(
input,
engine_ready,
|| Ok(()),
));
}
}
}
enum IdleTickAction {
Continue,
ProcessFrame,
}
fn tick_idle(
idle: Option<&mut IdleRuntime>,
session: &ControlSession,
slot: &LatestFrameSlot,
output: &OutputPipeline,
metrics: &RuntimeMetrics,
input_failure: &InputFailureSignal,
) -> Result<IdleTickAction, FluxError> {
let Some(idle_rt) = idle else {
return Ok(IdleTickAction::ProcessFrame);
};
if let Some(outcome) = reap_reload(&mut idle_rt.reload_handle) {
use crate::idle::reload::ResumeOutcome;
match outcome {
ResumeOutcome::Completed => {}
ResumeOutcome::EngineFailed(reason) => {
warn!(
target: "fluxframe::idle",
error = %reason,
"reload: engine rebuild failed — staying in placeholder mode"
);
}
ResumeOutcome::InputFailed(e) => {
metrics.counters.inc_resume_failures();
if input_failure.handles(fluxframe_gst::BusSource::Input) {
warn!(
target: "fluxframe::idle",
error = %e,
action = "reacquire",
"reload: camera reacquire failed — recovering without \
tearing the output down"
);
input_failure.raise();
return Ok(IdleTickAction::Continue);
}
warn!(
target: "fluxframe::idle",
error = %e,
"reload: camera reacquire failed — restarting chain to re-select the device"
);
return Err(e);
}
}
}
let status =
crate::idle::ConsumerStatus::from_u8(idle_rt.consumer_status.load(Ordering::Acquire));
let tick = idle_rt
.state_machine
.tick(status, Instant::now(), &session.cfg.idle);
handle_idle_edge(idle_rt, tick.edge, slot, output, metrics);
let active_allowed = active_allowed(tick.level, idle_rt.engine_ready.load(Ordering::Acquire));
if !active_allowed {
if let Err(e) = push_placeholder(
idle_rt.placeholder.as_ref(),
idle_rt.output_w,
idle_rt.output_h,
idle_rt.output_format,
output,
metrics,
) {
error!(error = %e, "placeholder push failed; stopping");
return Err(e);
}
idle_rt.was_active = false;
let _ = slot.recv_timeout(tick.next_tick_in);
return Ok(IdleTickAction::Continue);
}
if !idle_rt.was_active {
info!(target: "fluxframe::idle", "resumed active processing");
idle_rt.was_active = true;
}
Ok(IdleTickAction::ProcessFrame)
}
#[derive(Clone, Copy)]
struct WorkerDeps<'a> {
cfg: &'a FluxConfig,
processing_ctx: &'a ProcessingContext,
metrics: &'a RuntimeMetrics,
control_rx: Option<&'a crossbeam_channel::Receiver<ControlEnvelope>>,
}
#[derive(Clone, Copy)]
struct InputFailureWatch<'a> {
signal: &'a InputFailureSignal,
entry_generation: u64,
}
#[derive(Clone, Copy)]
struct SupervisedInput<'a> {
pipeline: &'a Arc<InputPipeline>,
failure: &'a InputFailureSignal,
}
impl InputFailureWatch<'_> {
fn tripped(&self) -> bool {
self.signal.generation() != self.entry_generation
}
}
#[expect(
clippy::too_many_arguments,
reason = "`session` is the one `&mut` collaborator and cannot ride in the `Copy` WorkerDeps"
)]
fn run_process_loop(
deps: WorkerDeps<'_>,
session: &mut ControlSession,
running: &AtomicBool,
slot: &LatestFrameSlot,
chain: &mut EffectChain,
output: &OutputPipeline,
mut idle: Option<&mut IdleRuntime>,
input_failure: InputFailureWatch<'_>,
) -> Result<(), FluxError> {
let mut state = WorkerState::new(deps.metrics, deps.cfg);
while running.load(Ordering::Acquire) && !input_failure.tripped() {
drain_control_commands(
session,
deps.control_rx,
deps.processing_ctx,
chain,
&state.frame_context.telemetry,
);
match tick_idle(
idle.as_deref_mut(),
session,
slot,
output,
deps.metrics,
input_failure.signal,
)? {
IdleTickAction::Continue => continue,
IdleTickAction::ProcessFrame => {}
}
let Some(frame) = slot.recv_timeout(WORKER_POLL_TIMEOUT) else {
continue;
};
process_one_frame(
&mut state,
frame,
chain,
output,
deps.metrics,
slot,
no_consumer_attached(idle.as_deref()),
)?;
}
if let Some(idle_rt) = idle.as_mut() {
if let Some(handle) = idle_rt.reload_handle.take() {
match handle.join() {
Ok(outcome) => {
tracing::debug!(
target: "fluxframe::idle",
?outcome,
"reload thread reaped at shutdown",
);
}
Err(_) => {
warn!(target: "fluxframe::idle", "reload thread panicked during shutdown");
}
}
}
}
Ok(())
}
fn teardown(input: &InputPipeline, output: &OutputPipeline, chain: &mut EffectChain) {
if let Err(e) = input.stop() {
warn!(error = %e, "input.stop failed");
}
if let Err(e) = output.stop() {
warn!(error = %e, "output.stop failed");
}
if let Err(e) = chain.shutdown_all() {
warn!(error = %e, "effect chain shutdown reported an error");
}
}
fn resolve_output_sink(cfg: &FluxConfig) -> Result<OutputSink, FluxError> {
match classify_output(cfg) {
OutputSpec::Auto => Ok(OutputSink::Auto),
OutputSpec::Fake => Ok(OutputSink::Fake),
OutputSpec::V4l2(device) => Ok(OutputSink::V4l2Loopback { device }),
OutputSpec::Pipewire(node_name) => Ok(OutputSink::Pipewire { node_name }),
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 output_sink_label(sink: &OutputSink) -> &'static str {
match sink {
OutputSink::Fake => "fakesink",
OutputSink::Auto => "autovideosink",
OutputSink::V4l2Loopback { .. } => "v4l2sink",
OutputSink::Pipewire { .. } => "pipewiresink",
}
}
#[cfg(test)]
mod tests {
use super::*;
fn base_cfg() -> FluxConfig {
FluxConfig::default()
}
fn fatal(source: BusSource) -> BusEvent {
BusEvent::FatalError {
source,
element: "input_src".into(),
message: "Device '/dev/video0' is busy".into(),
debug: None,
}
}
fn route(event: &BusEvent, supervised: bool) -> (bool, bool, u64, bool) {
let running = AtomicBool::new(true);
let bus_error = Mutex::new(None);
let slot = LatestFrameSlot::new();
let signal = InputFailureSignal::new();
if supervised {
signal.arm();
}
on_bus_event(event, &running, &bus_error, &slot, &signal);
(
running.load(Ordering::Acquire),
slot.is_closed(),
signal.generation(),
bus_error.lock().expect("poisoned").is_some(),
)
}
#[test]
fn supervised_input_fatal_is_recovered_not_fatal() {
let (running, closed, generation, latched) = route(&fatal(BusSource::Input), true);
assert!(running, "an input failure must not stop the run");
assert!(!closed, "the frame slot must stay open across recovery");
assert_eq!(generation, 1, "the supervisor must be told to recover");
assert!(
!latched,
"a recovered failure must not be returned as the run's error"
);
}
#[test]
fn output_fatal_is_always_fatal() {
let (running, closed, generation, latched) = route(&fatal(BusSource::Output), true);
assert!(!running);
assert!(closed);
assert_eq!(generation, 0);
assert!(latched);
}
#[test]
fn unsupervised_input_fatal_stays_fatal() {
let (running, closed, generation, latched) = route(&fatal(BusSource::Input), false);
assert!(!running);
assert!(closed);
assert_eq!(generation, 0);
assert!(latched);
}
#[test]
fn supervised_input_eos_is_recovered() {
let (running, closed, generation, _) = route(
&BusEvent::Eos {
source: BusSource::Input,
},
true,
);
assert!(running);
assert!(!closed);
assert_eq!(generation, 1);
}
#[test]
fn output_eos_still_ends_the_run() {
let (running, closed, generation, _) = route(
&BusEvent::Eos {
source: BusSource::Output,
},
true,
);
assert!(!running);
assert!(closed);
assert_eq!(generation, 0);
}
#[test]
fn warnings_have_no_side_effects() {
let (running, closed, generation, latched) = route(
&BusEvent::Warning {
source: BusSource::Input,
element: "input_src".into(),
message: "something odd".into(),
debug: None,
},
true,
);
assert!(running);
assert!(!closed);
assert_eq!(generation, 0);
assert!(!latched);
}
#[test]
fn a_burst_of_failures_raises_distinct_generations() {
let signal = InputFailureSignal::new();
signal.arm();
assert_eq!(signal.generation(), 0);
signal.raise();
signal.raise();
assert_eq!(signal.generation(), 2);
}
#[test]
fn an_unarmed_signal_leaves_input_failures_fatal() {
let signal = InputFailureSignal::new();
assert!(!signal.handles(BusSource::Input));
signal.arm();
assert!(signal.handles(BusSource::Input));
assert!(!signal.handles(BusSource::Output));
}
#[test]
fn active_frames_need_both_an_active_level_and_a_ready_engine() {
use crate::idle::IdleLevel;
assert!(active_allowed(IdleLevel::Active, true));
assert!(!active_allowed(IdleLevel::Active, false));
assert!(!active_allowed(IdleLevel::Placeholder, true));
}
#[test]
fn next_action_recovers_only_a_live_run_with_a_failed_input() {
assert_eq!(next_action(true, true, false), LoopAction::ReacquireInput);
assert_eq!(next_action(true, false, false), LoopAction::Exit);
assert_eq!(next_action(false, false, false), LoopAction::Exit);
assert_eq!(next_action(false, true, false), LoopAction::Exit);
assert_eq!(next_action(true, true, true), LoopAction::TeardownAll);
assert_eq!(next_action(true, false, true), LoopAction::TeardownAll);
}
struct ScriptedReacquire<'a> {
failures_before_success: usize,
attempts: std::cell::Cell<usize>,
during_attempt: Option<&'a dyn Fn()>,
}
impl ScriptedReacquire<'_> {
fn new(failures_before_success: usize) -> Self {
Self {
failures_before_success,
attempts: std::cell::Cell::new(0),
during_attempt: None,
}
}
}
impl Reacquire for ScriptedReacquire<'_> {
fn reacquire(&self) -> Result<(), FluxError> {
let n = self.attempts.get() + 1;
self.attempts.set(n);
if let Some(hook) = self.during_attempt {
hook();
}
if n > self.failures_before_success {
Ok(())
} else {
Err(FluxError::Config {
reason: "device busy".into(),
hint: None,
})
}
}
}
fn policy(budget_ms: u64, base_ms: u64, max_ms: u64) -> RecoveryPolicy {
RecoveryPolicy {
budget: Duration::from_millis(budget_ms),
backoff_base: Duration::from_millis(base_ms),
backoff_max: Duration::from_millis(max_ms),
}
}
#[test]
fn retry_reacquire_succeeds_on_the_first_attempt() {
let target = ScriptedReacquire::new(0);
let signal = InputFailureSignal::new();
signal.raise();
signal.raise();
let running = AtomicBool::new(true);
let counters = fluxframe_core::metrics::Counters::new();
let started = Instant::now()
.checked_sub(Duration::from_millis(50))
.expect("monotonic clock is well past 50 ms since boot");
let generation = retry_reacquire(
&target,
&signal,
&running,
&counters,
policy(60_000, 1, 8),
started,
|_| panic!("a first-attempt success must never pause"),
)
.expect("recovery should succeed");
assert_eq!(generation, 2);
assert_eq!(generation, signal.generation());
assert_eq!(target.attempts.get(), 1);
let snap = counters.snapshot();
assert_eq!(snap.input_reacquire_total, 1);
assert_eq!(snap.input_reacquire_failures_total, 0);
assert!(snap.input_down_ms_total >= 50);
}
#[test]
fn retry_reacquire_succeeds_on_the_third_attempt_with_growing_backoff() {
let target = ScriptedReacquire::new(2);
let signal = InputFailureSignal::new();
let running = AtomicBool::new(true);
let counters = fluxframe_core::metrics::Counters::new();
let mut pauses: Vec<Duration> = Vec::new();
let generation = retry_reacquire(
&target,
&signal,
&running,
&counters,
policy(60_000, 1, 8),
Instant::now(),
|backoff| {
pauses.push(backoff);
false
},
)
.expect("third attempt should succeed");
assert_eq!(generation, 0);
assert_eq!(target.attempts.get(), 3);
assert_eq!(
pauses,
vec![Duration::from_millis(1), Duration::from_millis(2)]
);
let snap = counters.snapshot();
assert_eq!(snap.input_reacquire_total, 3);
assert_eq!(snap.input_reacquire_failures_total, 2);
}
#[test]
fn retry_reacquire_backoff_doubles_up_to_the_ceiling() {
let target = ScriptedReacquire::new(usize::MAX);
let signal = InputFailureSignal::new();
let running = AtomicBool::new(true);
let counters = fluxframe_core::metrics::Counters::new();
let mut pauses: Vec<Duration> = Vec::new();
let result = retry_reacquire(
&target,
&signal,
&running,
&counters,
policy(60_000, 1, 8),
Instant::now(),
|backoff| {
pauses.push(backoff);
if pauses.len() >= 6 {
running.store(false, Ordering::Release);
}
false
},
);
assert!(result.is_ok(), "stopping via `running` is not an error");
assert_eq!(
pauses,
vec![
Duration::from_millis(1),
Duration::from_millis(2),
Duration::from_millis(4),
Duration::from_millis(8),
Duration::from_millis(8),
Duration::from_millis(8),
]
);
}
#[test]
fn retry_reacquire_gives_up_when_the_budget_is_spent() {
let target = ScriptedReacquire::new(usize::MAX);
let signal = InputFailureSignal::new();
let running = AtomicBool::new(true);
let counters = fluxframe_core::metrics::Counters::new();
let result = retry_reacquire(
&target,
&signal,
&running,
&counters,
policy(20, 5, 10),
Instant::now(),
|backoff| {
std::thread::sleep(backoff);
false
},
);
assert!(result.is_err(), "an exhausted budget must escalate");
let snap = counters.snapshot();
assert!(snap.input_reacquire_total >= 2);
assert_eq!(
snap.input_reacquire_total,
snap.input_reacquire_failures_total
);
assert_eq!(snap.input_down_ms_total, 0);
}
#[test]
fn retry_reacquire_returns_immediately_when_the_run_is_stopping() {
let target = ScriptedReacquire::new(usize::MAX);
let signal = InputFailureSignal::new();
signal.raise();
let running = AtomicBool::new(false);
let counters = fluxframe_core::metrics::Counters::new();
let generation = retry_reacquire(
&target,
&signal,
&running,
&counters,
policy(60_000, 1, 8),
Instant::now(),
|_| panic!("must not even attempt a reacquire"),
)
.expect("a stopping run exits cleanly");
assert_eq!(generation, 1);
assert_eq!(target.attempts.get(), 0);
assert_eq!(counters.snapshot().input_reacquire_total, 0);
}
#[test]
fn a_failure_raised_during_the_winning_attempt_is_not_absorbed() {
let signal = InputFailureSignal::new();
signal.raise();
let raise_again = || signal.raise();
let target = ScriptedReacquire {
failures_before_success: 0,
attempts: std::cell::Cell::new(0),
during_attempt: Some(&raise_again),
};
let running = AtomicBool::new(true);
let counters = fluxframe_core::metrics::Counters::new();
let generation = retry_reacquire(
&target,
&signal,
&running,
&counters,
policy(60_000, 1, 8),
Instant::now(),
|_| false,
)
.expect("recovery should succeed");
assert_eq!(generation, 1, "snapshot is taken before the attempt");
assert_eq!(signal.generation(), 2);
let watch = InputFailureWatch {
signal: &signal,
entry_generation: generation,
};
assert!(watch.tripped());
}
fn spawn_finished(
outcome: crate::idle::reload::ResumeOutcome,
) -> std::thread::JoinHandle<crate::idle::reload::ResumeOutcome> {
let handle = std::thread::spawn(move || outcome);
while !handle.is_finished() {
std::thread::sleep(std::time::Duration::from_millis(1));
}
handle
}
#[test]
fn reap_reload_none_when_empty() {
let mut handle = None;
assert!(reap_reload(&mut handle).is_none());
}
#[test]
fn reap_reload_leaves_in_flight_handle() {
use std::sync::mpsc;
let (tx, rx) = mpsc::channel::<()>();
let mut handle = Some(std::thread::spawn(move || {
let _ = rx.recv(); crate::idle::reload::ResumeOutcome::Completed
}));
assert!(reap_reload(&mut handle).is_none());
assert!(handle.is_some(), "in-flight handle must be preserved");
tx.send(()).unwrap();
handle.take().unwrap().join().unwrap();
}
#[test]
fn reap_reload_returns_input_failed_outcome() {
use crate::idle::reload::ResumeOutcome;
use fluxframe_core::error::PipelineError;
let mut handle = Some(spawn_finished(ResumeOutcome::InputFailed(FluxError::from(
PipelineError::StateChangeFailed {
reason: "synthetic reacquire failure".into(),
},
))));
let outcome = reap_reload(&mut handle);
assert!(
matches!(outcome, Some(ResumeOutcome::InputFailed(ref e)) if e.is_transient()),
"InputFailed must be surfaced and be transient so run_auto retries, got {outcome:?}"
);
assert!(handle.is_none(), "reaped handle must be consumed");
}
#[test]
fn reap_reload_returns_completed_outcome() {
use crate::idle::reload::ResumeOutcome;
let mut handle = Some(spawn_finished(ResumeOutcome::Completed));
assert!(matches!(
reap_reload(&mut handle),
Some(ResumeOutcome::Completed)
));
assert!(handle.is_none());
}
#[test]
fn classify_input_recognises_testsrc() {
let mut cfg = base_cfg();
cfg.input.device = InputDevice::Testsrc;
assert_eq!(classify_input(&cfg), InputSpec::Testsrc);
}
#[test]
fn is_input_contention_retries_only_device_unavailable() {
let busy = FluxError::Pipeline(fluxframe_core::PipelineError::InputDeviceUnavailable {
device: "/dev/video0".into(),
reason: "device is busy".into(),
hint: "another app holds it".into(),
});
assert!(is_input_contention(&busy));
let missing = FluxError::Pipeline(fluxframe_core::PipelineError::MissingElement {
element: "v4l2src".into(),
hint: "install gst-plugins-good".into(),
});
assert!(!is_input_contention(&missing));
let cfg_err = FluxError::Config {
reason: "bad".into(),
hint: None,
};
assert!(!is_input_contention(&cfg_err));
}
#[test]
fn supervised_acquire_requires_idle_loopback_and_v4l2_input() {
let mut cfg = base_cfg();
cfg.idle.enabled = false;
cfg.input.device = InputDevice::Path("/dev/video0".into());
cfg.output.device = "/dev/video10".into();
assert!(!supervised_acquire(&cfg));
cfg.idle.enabled = true;
assert!(supervised_acquire(&cfg));
cfg.input.device = InputDevice::Testsrc;
assert!(!supervised_acquire(&cfg));
}
#[test]
fn classify_input_classifies_real_device_as_v4l2() {
let mut cfg = base_cfg();
cfg.input.device = InputDevice::Path(PathBuf::from("/dev/video0"));
assert_eq!(
classify_input(&cfg),
InputSpec::V4l2(PathBuf::from("/dev/video0"))
);
}
#[test]
fn classify_input_marks_auto_as_unsupported_escape_hatch() {
let mut cfg = base_cfg();
cfg.input.device = InputDevice::Auto;
match classify_input(&cfg) {
InputSpec::Unsupported(s) => {
assert!(s.contains("auto"), "diagnostic should mention auto: {s}");
}
other => panic!("expected Unsupported, got {other:?}"),
}
}
#[test]
fn resolve_output_sink_maps_auto() {
let mut cfg = base_cfg();
cfg.output.device = "auto".into();
assert_eq!(
resolve_output_sink(&cfg).expect("auto resolves"),
OutputSink::Auto
);
}
#[test]
fn resolve_output_sink_maps_dev_path_to_v4l2_loopback() {
let mut cfg = base_cfg();
cfg.output.device = "/dev/video10".into();
assert_eq!(
resolve_output_sink(&cfg).expect("dev path resolves"),
OutputSink::V4l2Loopback {
device: PathBuf::from("/dev/video10"),
}
);
}
#[test]
fn resolve_output_sink_maps_fakesink() {
let mut cfg = base_cfg();
cfg.output.device = "fakesink".into();
assert_eq!(
resolve_output_sink(&cfg).expect("fakesink resolves"),
OutputSink::Fake
);
}
#[test]
fn resolve_output_sink_rejects_unsupported() {
let mut cfg = base_cfg();
cfg.output.device = "http://example.com/stream".into();
let err = resolve_output_sink(&cfg).expect_err("unsupported sink must fail");
let msg = format!("{err}");
assert!(msg.contains("not supported"), "got: {msg}");
}
#[test]
fn classify_output_marks_unsupported() {
let mut cfg = base_cfg();
cfg.output.device = "http://example.com/stream".into();
assert_eq!(
classify_output(&cfg),
OutputSpec::Unsupported("http://example.com/stream".to_string())
);
}
#[test]
fn output_sink_label_covers_each_variant() {
assert_eq!(output_sink_label(&OutputSink::Fake), "fakesink");
assert_eq!(output_sink_label(&OutputSink::Auto), "autovideosink");
assert_eq!(
output_sink_label(&OutputSink::V4l2Loopback {
device: PathBuf::from("/dev/video10"),
}),
"v4l2sink"
);
}
#[test]
fn classify_input_path_returns_v4l2_with_path() {
let mut cfg = base_cfg();
cfg.input.device = InputDevice::Path(PathBuf::from("/dev/video2"));
assert_eq!(
classify_input(&cfg),
InputSpec::V4l2(PathBuf::from("/dev/video2"))
);
}
#[test]
fn classify_output_maps_auto() {
let mut cfg = base_cfg();
cfg.output.device = "auto".into();
assert_eq!(classify_output(&cfg), OutputSpec::Auto);
}
#[test]
fn classify_output_maps_fakesink() {
let mut cfg = base_cfg();
cfg.output.device = "fakesink".into();
assert_eq!(classify_output(&cfg), OutputSpec::Fake);
}
#[test]
fn classify_output_maps_dev_path() {
let mut cfg = base_cfg();
cfg.output.device = "/dev/video10".into();
assert_eq!(
classify_output(&cfg),
OutputSpec::V4l2(PathBuf::from("/dev/video10"))
);
}
#[test]
fn classify_output_maps_pipewire_bare() {
let mut cfg = base_cfg();
cfg.output.device = "pipewire".into();
assert_eq!(classify_output(&cfg), OutputSpec::Pipewire(None));
}
#[test]
fn classify_output_maps_pipewire_with_name() {
let mut cfg = base_cfg();
cfg.output.device = "pipewire:my-cam".into();
assert_eq!(
classify_output(&cfg),
OutputSpec::Pipewire(Some("my-cam".to_string()))
);
}
#[test]
fn classify_output_treats_pipewire_typos_as_unsupported() {
let mut cfg = base_cfg();
cfg.output.device = "pipewirefoo".into();
match classify_output(&cfg) {
OutputSpec::Unsupported(s) => assert_eq!(s, "pipewirefoo"),
other => panic!("expected Unsupported, got {other:?}"),
}
}
#[test]
fn classify_output_pipewire_colon_with_empty_name_is_anonymous() {
let mut cfg = base_cfg();
cfg.output.device = "pipewire:".into();
assert_eq!(classify_output(&cfg), OutputSpec::Pipewire(None));
}
#[test]
fn resolve_output_sink_maps_pipewire() {
let mut cfg = base_cfg();
cfg.output.device = "pipewire:flux".into();
assert_eq!(
resolve_output_sink(&cfg).expect("pipewire resolves"),
OutputSink::Pipewire {
node_name: Some("flux".into())
}
);
}
use fluxframe_core::PipelineSection;
use fluxframe_core::frame::PixelFormat;
use fluxframe_effects::EffectChain as StubEffectChain;
use fluxframe_effects::PassthroughEffect;
#[cfg(feature = "ml")]
fn composite_chain(preset: &Preset) -> StubEffectChain {
let mask_reg = fluxframe_effects::mask_effects::default_registry();
let plane_reg = fluxframe_effects::plane_effects::default_registry();
let post_reg = fluxframe_effects::post_effects::default_registry();
let composite =
fluxframe_effects::composite::CompositeBuilder::new(&mask_reg, &plane_reg, &post_reg)
.build(
preset.mask.as_ref().expect("test preset has [mask]"),
preset.background.as_ref(),
preset.foreground.as_ref(),
preset.post.as_ref(),
&ConfigBase::default(),
)
.expect("test composite builds");
StubEffectChain::new(vec![Box::new(composite)])
}
fn stub_chain() -> StubEffectChain {
StubEffectChain::new(vec![Box::new(PassthroughEffect::new())])
}
fn stub_ctx() -> ProcessingContext {
ProcessingContext {
width: 4,
height: 4,
format: PixelFormat::Rgb,
fps: 30,
counters: None,
}
}
fn ok_payload(r: &ControlResponse) -> &serde_json::Value {
match r {
ControlResponse::Ok { data } => data,
ControlResponse::Err { .. } => panic!("expected Ok, got {r:?}"),
_ => panic!("non-exhaustive Response variant: {r:?}"),
}
}
fn err_reason(r: &ControlResponse) -> &str {
match r {
ControlResponse::Err { error, .. } => error.as_str(),
ControlResponse::Ok { .. } => panic!("expected Err, got {r:?}"),
_ => panic!("non-exhaustive Response variant: {r:?}"),
}
}
#[test]
fn apply_control_command_list_presets_returns_names() {
let mut cfg = base_cfg();
cfg.presets.insert("a".into(), Preset::default());
cfg.presets.insert("b".into(), Preset::default());
let mut session = test_session(cfg, "a");
let resp = apply_control_command(
&mut session,
&stub_ctx(),
&mut stub_chain(),
&fluxframe_core::EffectTelemetry::default(),
ControlCommand::ListPresets,
);
let data = ok_payload(&resp);
let arr = data.as_array().expect("ListPresets returns array");
let names: Vec<&str> = arr.iter().filter_map(|v| v.as_str()).collect();
assert!(names.contains(&"a"), "names: {names:?}");
assert!(names.contains(&"b"), "names: {names:?}");
}
#[test]
fn apply_list_effects_payload_decodes_into_effect_schema() {
let resp = apply_list_effects_command();
let data = ok_payload(&resp);
for section in fluxframe_core::SubchainKind::ALL {
let rows = data[section.as_str()].clone();
let decoded: Vec<fluxframe_core::EffectSchema> = serde_json::from_value(rows.clone())
.unwrap_or_else(|e| panic!("section '{section}' fails to decode: {e}"));
assert_eq!(
serde_json::to_value(&decoded).expect("re-serialise"),
rows,
"section '{section}' changes shape through EffectSchema"
);
}
}
#[test]
fn apply_list_effects_returns_inventory_for_all_sections() {
use fluxframe_effects::{mask_effects, plane_effects};
let resp = apply_list_effects_command();
let data = ok_payload(&resp);
let obj = data.as_object().expect("ListEffects returns object");
for section in ["mask", "background", "foreground", "post"] {
let arr = obj
.get(section)
.and_then(serde_json::Value::as_array)
.unwrap_or_else(|| panic!("section '{section}' missing or not array"));
for row in arr {
let row_obj = row.as_object().expect("metadata is object");
assert!(row_obj.contains_key("name"));
assert!(row_obj.contains_key("params"));
}
}
for section in ["mask", "background", "foreground"] {
assert!(
!obj[section].as_array().unwrap().is_empty(),
"section '{section}' must list at least one effect"
);
}
#[cfg(feature = "ml")]
assert!(
!obj["post"].as_array().unwrap().is_empty(),
"post must populate under ml feature"
);
let mask_spot: Vec<_> = obj["mask"]
.as_array()
.unwrap()
.iter()
.filter_map(|v| v["name"].as_str())
.collect();
assert!(mask_spot.contains(&"threshold"), "got: {mask_spot:?}");
let mask_names: Vec<&str> = obj["mask"]
.as_array()
.unwrap()
.iter()
.filter_map(|v| v["name"].as_str())
.collect();
assert_eq!(
mask_names,
mask_effects::default_registry().names(),
"ListEffects mask list must equal default_registry().names()",
);
let bg_names: Vec<&str> = obj["background"]
.as_array()
.unwrap()
.iter()
.filter_map(|v| v["name"].as_str())
.collect();
assert_eq!(
bg_names,
plane_effects::default_registry().names(),
"ListEffects background list must equal plane registry names()",
);
let fg_names: Vec<&str> = obj["foreground"]
.as_array()
.unwrap()
.iter()
.filter_map(|v| v["name"].as_str())
.collect();
assert_eq!(
fg_names,
plane_effects::default_registry().names(),
"ListEffects foreground list must equal plane registry names()",
);
#[cfg(feature = "ml")]
{
use fluxframe_effects::post_effects;
let post_names: Vec<&str> = obj["post"]
.as_array()
.unwrap()
.iter()
.filter_map(|v| v["name"].as_str())
.collect();
assert_eq!(
post_names,
post_effects::default_registry().names(),
"ListEffects post list must equal post registry names() under ml",
);
}
assert!(
obj.contains_key("build_features"),
"build_features must be present in ListEffects response",
);
assert!(
obj["build_features"].is_array(),
"build_features must be an array",
);
}
#[test]
fn apply_list_effects_foreground_equals_background_today() {
let resp = apply_list_effects_command();
let data = ok_payload(&resp);
let obj = data.as_object().expect("ListEffects returns object");
let bg = obj["background"].as_array().expect("background is array");
let fg = obj["foreground"].as_array().expect("foreground is array");
assert_eq!(
bg.len(),
fg.len(),
"foreground and background must have the same length today",
);
for (i, (b, f)) in bg.iter().zip(fg.iter()).enumerate() {
assert_eq!(
b, f,
"foreground[{i}] must equal background[{i}] (shared plane registry)",
);
}
}
#[test]
fn apply_control_command_set_preset_unknown_name_lists_available() {
let mut cfg = base_cfg();
cfg.presets.insert("alpha".into(), Preset::default());
let mut session = test_session(cfg, "alpha");
let resp = apply_control_command(
&mut session,
&stub_ctx(),
&mut stub_chain(),
&fluxframe_core::EffectTelemetry::default(),
ControlCommand::SetPreset {
name: "missing".into(),
},
);
match resp {
ControlResponse::Err { error, hint } => {
assert!(error.contains("missing"), "error: {error}");
let hint = hint.expect("hint must list available presets");
assert!(hint.contains("alpha"), "hint: {hint}");
}
ControlResponse::Ok { .. } => panic!("expected Err"),
_ => panic!("non-exhaustive Response variant"),
}
}
fn test_session(cfg: FluxConfig, preset_name: &str) -> ControlSession {
let active_preset = cfg.presets.get(preset_name).cloned().unwrap_or_default();
ControlSession {
cfg,
config_path: None,
config_base: ConfigBase::default(),
active_preset_name: preset_name.into(),
active_preset,
}
}
#[test]
fn preset_switch_lands_in_the_session() {
let mut cfg = base_cfg();
cfg.presets.insert("alpha".into(), Preset::default());
cfg.presets.insert("beta".into(), Preset::default());
let mut session = test_session(cfg, "alpha");
let resp = apply_control_command(
&mut session,
&stub_ctx(),
&mut stub_chain(),
&fluxframe_core::EffectTelemetry::default(),
ControlCommand::SetPreset {
name: "beta".into(),
},
);
ok_payload(&resp);
assert_eq!(session.active_preset_name, "beta");
let current = apply_offline_command(&session, &ControlCommand::CurrentPreset);
assert_eq!(ok_payload(¤t), &serde_json::json!("beta"));
}
#[test]
fn offline_commands_serve_reads_and_refuse_edits() {
let mut cfg = base_cfg();
cfg.presets.insert("alpha".into(), Preset::default());
let session = test_session(cfg, "alpha");
for cmd in [
ControlCommand::ListPresets,
ControlCommand::CurrentPreset,
ControlCommand::ListEffects,
ControlCommand::GetConfig { path: None },
ControlCommand::ConfigPath,
ControlCommand::DaemonInfo,
] {
let resp = apply_offline_command(&session, &cmd);
assert!(
matches!(resp, ControlResponse::Ok { .. }),
"{cmd:?} must be answered without a pipeline, got {resp:?}"
);
}
for cmd in [
ControlCommand::SetPreset {
name: "alpha".into(),
},
ControlCommand::SetChain {
section: SubchainKind::Background,
chain: Vec::new(),
},
ControlCommand::Reload,
ControlCommand::SavePreset,
] {
let resp = apply_offline_command(&session, &cmd);
assert!(
err_reason(&resp).contains("pipeline is not running"),
"{cmd:?} must be refused without a pipeline"
);
}
}
#[test]
fn daemon_info_reports_the_configured_output() {
let mut cfg = base_cfg();
cfg.output.device = "pipewire:studio".into();
let session = test_session(cfg, "default");
let resp = apply_offline_command(&session, &ControlCommand::DaemonInfo);
assert_eq!(
ok_payload(&resp),
&serde_json::json!({"output": {"kind": "pipewire", "node": "studio"}})
);
}
#[test]
fn waiting_without_a_pipeline_still_answers_the_socket() {
let mut cfg = base_cfg();
cfg.presets.insert("alpha".into(), Preset::default());
let session = test_session(cfg, "alpha");
let (tx, rx) = crossbeam_channel::bounded::<ControlEnvelope>(CONTROL_CHANNEL_DEPTH);
let (reply_tx, reply_rx) = crossbeam_channel::bounded(REPLY_CHANNEL_DEPTH);
tx.send(ControlEnvelope {
cmd: ControlCommand::CurrentPreset,
reply_tx,
})
.expect("command channel is open");
let _ = wait_serving_control(Duration::from_millis(20), Some(&rx), &session);
let reply = reply_rx
.try_recv()
.expect("the wait answered the queued command");
assert_eq!(ok_payload(&reply), &serde_json::json!("alpha"));
}
#[test]
fn apply_set_command_revert_on_invalid_value() {
let mut chain = stub_chain();
let mut preset = Preset {
background: Some(PipelineSection::default()),
..Preset::default()
};
let before = preset.background.as_ref().unwrap().per_effect.clone();
let resp = apply_set_command(
&mut chain,
&mut preset,
&ConfigBase::default(),
"background.blur.radius",
serde_json::json!(42),
);
assert!(matches!(resp, ControlResponse::Err { .. }));
let after = preset.background.as_ref().unwrap().per_effect.clone();
assert_eq!(
before, after,
"in-memory preset must be unchanged after revert"
);
}
#[cfg(feature = "ml")]
#[test]
fn apply_set_command_on_disabled_effect_ignores_enabled_flag() {
let mut preset: Preset = toml::from_str(
r#"
[mask]
model = "/tmp/dummy.onnx"
chain = ["threshold"]
[background]
chain = ["blur"]
[background.blur]
enabled = false
radius = 10
"#,
)
.expect("test preset parses");
let mut chain = composite_chain(&preset);
let resp = apply_set_command(
&mut chain,
&mut preset,
&ConfigBase::default(),
"background.blur.passes",
serde_json::json!(3),
);
assert!(matches!(resp, ControlResponse::Ok { .. }), "{resp:?}");
let blur = &preset.background.as_ref().unwrap().per_effect["blur"];
assert_eq!(blur.get("enabled"), Some(&toml::Value::Boolean(false)));
assert_eq!(blur.get("passes"), Some(&toml::Value::Integer(3)));
let before = preset.clone();
let resp = apply_set_command(
&mut chain,
&mut preset,
&ConfigBase::default(),
"background.blur.passes",
serde_json::json!("many"),
);
assert!(matches!(resp, ControlResponse::Err { .. }), "{resp:?}");
assert_eq!(preset, before);
}
#[test]
fn apply_set_command_rejects_enabled_field() {
let mut chain = stub_chain();
let mut preset = Preset::default();
let resp = apply_set_command(
&mut chain,
&mut preset,
&ConfigBase::default(),
"background.blur.enabled",
serde_json::json!(false),
);
assert!(
err_reason(&resp).contains("not an effect parameter"),
"{resp:?}"
);
assert_eq!(preset, Preset::default());
}
#[cfg(feature = "image-fill")]
#[test]
fn set_resolves_relative_image_paths_against_the_config_base() {
let base = ConfigBase::for_config(Some(std::path::Path::new("/etc/ff/fluxframe.toml")));
let table = toml::Value::Table(
toml::from_str("enabled = false\npath = \"bg.png\"").expect("valid TOML"),
);
let params = live_effect_params(
"image_fill",
Some(&table),
effect_metadata(SubchainKind::Background, "image_fill"),
&base,
)
.expect("params resolve");
assert_eq!(
params,
toml::Value::Table(toml::from_str("path = \"/etc/ff/bg.png\"").expect("valid TOML"))
);
}
#[cfg(feature = "ml")]
fn toggle_preset() -> Preset {
toml::from_str(
r#"
[mask]
model = "/tmp/dummy.onnx"
chain = ["threshold"]
[background]
chain = ["color_fill", "blur"]
[background.blur]
radius = 10
"#,
)
.expect("test preset parses")
}
#[cfg(feature = "ml")]
fn live_disabled(chain: &mut StubEffectChain, section: SubchainKind) -> Vec<String> {
chain
.composite_mut()
.expect("chain hosts a composite")
.disabled_effects(section)
.into_iter()
.map(str::to_string)
.collect()
}
#[cfg(feature = "ml")]
fn table(text: &str) -> toml::Value {
toml::Value::Table(toml::from_str(text).expect("valid TOML"))
}
#[cfg(feature = "ml")]
#[test]
fn apply_set_enabled_command_toggles_live_chain_and_canonical_preset() {
let original = toggle_preset();
let mut preset = original.clone();
let mut chain = composite_chain(&preset);
let stages = std::sync::Arc::new(fluxframe_core::StageTimings::with_capacity(4));
let telemetry =
fluxframe_core::EffectTelemetry::default().with_stages(std::sync::Arc::clone(&stages));
telemetry.record_stage(
fluxframe_core::StageKey::new("background", "color_fill"),
Duration::from_micros(5),
);
let bg = SubchainKind::Background;
let ok =
|resp: ControlResponse| assert!(matches!(resp, ControlResponse::Ok { .. }), "{resp:?}");
ok(apply_set_enabled_command(
&mut chain,
&mut preset,
&telemetry,
bg,
"color_fill",
false,
));
assert_eq!(live_disabled(&mut chain, bg), vec!["color_fill"]);
let per_effect = &preset.background.as_ref().unwrap().per_effect;
assert_eq!(per_effect["color_fill"], table("enabled = false"));
assert!(stages.snapshot().is_empty(), "disabled stage is forgotten");
ok(apply_set_enabled_command(
&mut chain,
&mut preset,
&telemetry,
bg,
"blur",
false,
));
let per_effect = &preset.background.as_ref().unwrap().per_effect;
assert_eq!(per_effect["blur"], table("enabled = false\nradius = 10"));
ok(apply_set_enabled_command(
&mut chain,
&mut preset,
&telemetry,
bg,
"blur",
true,
));
let per_effect = &preset.background.as_ref().unwrap().per_effect;
assert_eq!(per_effect["blur"], table("radius = 10"));
ok(apply_set_enabled_command(
&mut chain,
&mut preset,
&telemetry,
bg,
"color_fill",
true,
));
assert_eq!(live_disabled(&mut chain, bg), Vec::<String>::new());
assert_eq!(preset, original);
ok(apply_set_enabled_command(
&mut chain,
&mut preset,
&telemetry,
bg,
"color_fill",
true,
));
assert_eq!(preset, original);
}
#[cfg(feature = "ml")]
#[test]
fn apply_set_enabled_command_keeps_mask_segmentation_fields() {
let mut preset = toggle_preset();
let mut chain = composite_chain(&preset);
let telemetry = fluxframe_core::EffectTelemetry::default();
let resp = apply_set_enabled_command(
&mut chain,
&mut preset,
&telemetry,
SubchainKind::Mask,
"threshold",
false,
);
assert!(matches!(resp, ControlResponse::Ok { .. }), "{resp:?}");
let mask = preset.mask.as_ref().unwrap();
assert_eq!(
mask.model.as_deref(),
Some(std::path::Path::new("/tmp/dummy.onnx"))
);
assert_eq!(mask.per_effect["threshold"], table("enabled = false"));
}
#[cfg(feature = "ml")]
#[test]
fn apply_set_enabled_command_rejections_leave_preset_untouched() {
let base = toggle_preset();
let telemetry = fluxframe_core::EffectTelemetry::default();
let mut preset = base.clone();
let mut chain = composite_chain(&preset);
let resp = apply_set_enabled_command(
&mut chain,
&mut preset,
&telemetry,
SubchainKind::Background,
"vignette",
false,
);
assert!(err_reason(&resp).contains("no effect named"), "{resp:?}");
assert_eq!(preset, base);
let resp = apply_set_enabled_command(
&mut chain,
&mut preset,
&telemetry,
SubchainKind::Post,
"mirror",
false,
);
assert!(err_reason(&resp).contains("[post]"), "{resp:?}");
assert_eq!(preset, base);
preset
.background
.as_mut()
.unwrap()
.per_effect
.insert("color_fill".into(), toml::Value::Integer(1));
let malformed = preset.clone();
let resp = apply_set_enabled_command(
&mut chain,
&mut preset,
&telemetry,
SubchainKind::Background,
"color_fill",
false,
);
assert!(err_reason(&resp).contains("not a table"), "{resp:?}");
assert_eq!(preset, malformed);
assert_eq!(
live_disabled(&mut chain, SubchainKind::Background),
Vec::<String>::new()
);
let mut maskless = Preset::default();
let resp = apply_set_enabled_command(
&mut stub_chain(),
&mut maskless,
&telemetry,
SubchainKind::Mask,
"threshold",
false,
);
assert!(err_reason(&resp).contains("[mask]"), "{resp:?}");
assert_eq!(maskless, Preset::default());
}
#[cfg(feature = "ml")]
#[test]
fn subchain_rebuild_synthesises_defaults_and_keeps_disabled_flag() {
let per_effect: std::collections::BTreeMap<String, toml::Value> =
toml::from_str("[color_fill]\nenabled = false\n").expect("valid TOML");
let names = ["vignette".to_string(), "color_fill".to_string()];
let Ok(payload) = build_and_configure_subchain(
SubchainKind::Background,
&names,
&per_effect,
&ConfigBase::default(),
) else {
panic!("rebuild must succeed for a flag-only table");
};
let fluxframe_effects::composite::SubChainPayload::Background(slots) = payload else {
panic!("background payload expected");
};
assert!(slots[0].is_enabled());
assert!(!slots[1].is_enabled());
}
#[test]
fn apply_get_config_command_walks_nested_path() {
let section = PipelineSection {
chain: vec!["blur".into()],
..PipelineSection::default()
};
let preset = Preset {
background: Some(section),
..Preset::default()
};
let resp = apply_get_config_command(&preset, Some("background.chain"));
let data = ok_payload(&resp);
let arr = data.as_array().expect("chain returns array");
assert_eq!(arr.len(), 1);
assert_eq!(arr[0].as_str(), Some("blur"));
}
#[test]
fn apply_get_config_command_rejects_empty_component() {
let preset = Preset::default();
let resp = apply_get_config_command(&preset, Some("background..chain"));
let reason = err_reason(&resp);
assert!(reason.contains("empty"), "reason: {reason}");
}
#[test]
fn ensure_plane_or_post_section_mut_materialises_absent_post() {
let mut p = fluxframe_core::Preset::default();
assert!(p.post.is_none(), "fixture preset has no [post]");
let section = ensure_plane_or_post_section_mut(&mut p, SubchainKind::Post);
assert!(
section.chain.is_empty(),
"newly-materialised chain is empty"
);
assert!(section.per_effect.is_empty(), "no per-effect overrides");
assert!(p.post.is_some(), "section persisted into preset");
}
#[test]
fn ensure_plane_or_post_section_mut_returns_existing_background() {
let mut p = fluxframe_core::Preset {
background: Some(fluxframe_core::PipelineSection {
chain: vec!["blur".to_string()],
..Default::default()
}),
..Default::default()
};
let section = ensure_plane_or_post_section_mut(&mut p, SubchainKind::Background);
assert_eq!(
section.chain,
vec!["blur".to_string()],
"existing chain preserved"
);
}
#[test]
fn mask_section_mut_does_not_materialise_absent() {
let mut p = fluxframe_core::Preset::default();
assert!(mask_section_mut(&mut p).is_none(), "absent mask stays None");
assert!(p.mask.is_none(), "preset.mask is not mutated");
}
#[test]
fn mask_section_mut_returns_existing() {
let mut p = fluxframe_core::Preset {
mask: Some(fluxframe_core::PipelineSection {
chain: vec!["threshold".to_string()],
..Default::default()
}),
..Default::default()
};
assert!(mask_section_mut(&mut p).is_some());
}
#[test]
fn apply_reload_command_without_path_errors() {
let mut cfg = base_cfg();
let mut chain = stub_chain();
let mut name = "default".to_string();
let mut preset = Preset::default();
let ctx = stub_ctx();
let resp = apply_reload_command(&mut cfg, None, &ctx, &mut chain, &mut name, &mut preset);
let reason = err_reason(&resp);
assert!(reason.contains("config path"), "reason: {reason}");
}
}
#[cfg(all(test, feature = "ml", feature = "image-fill"))]
mod default_synthesis_tests {
use super::*;
use std::collections::BTreeMap;
#[test]
fn synthesises_color_fill_defaults_when_per_effect_missing() {
let per_effect = BTreeMap::new();
let result = build_and_configure_subchain(
SubchainKind::Background,
&["color_fill".to_string()],
&per_effect,
&ConfigBase::default(),
);
assert!(
result.is_ok(),
"color_fill should succeed with metadata-synthesised defaults; got {:?}",
result.as_ref().err().map(|e| &e.reason),
);
}
#[test]
fn rejects_image_fill_with_helpful_message() {
let per_effect = BTreeMap::new();
let Err(err) = build_and_configure_subchain(
SubchainKind::Background,
&["image_fill".to_string()],
&per_effect,
&ConfigBase::default(),
) else {
panic!("image_fill should fail without an explicit path")
};
assert!(
err.reason.contains("missing required field"),
"expected missing-field error, got: {}",
err.reason,
);
assert!(
err.reason.contains("path"),
"expected `path` mentioned in error, got: {}",
err.reason,
);
assert!(
err.hint.is_some(),
"expected hint with editor suggestion, got reason={} hint={:?}",
err.reason,
err.hint,
);
}
}