lesavka/server/src/camera.rs

326 lines
9.8 KiB
Rust
Raw Normal View History

2026-01-28 17:52:00 -03:00
// server/src/camera.rs
use gstreamer as gst;
use std::collections::HashMap;
use std::fs;
use std::sync::{OnceLock, RwLock};
use tracing::{info, warn};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum CameraOutput {
Uvc,
Hdmi,
}
impl CameraOutput {
/// Return the canonical string name for the transport.
2026-01-28 17:52:00 -03:00
pub fn as_str(self) -> &'static str {
match self {
CameraOutput::Uvc => "uvc",
CameraOutput::Hdmi => "hdmi",
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum CameraCodec {
H264,
Mjpeg,
}
impl CameraCodec {
/// Return the canonical string name for the codec.
2026-01-28 17:52:00 -03:00
pub fn as_str(self) -> &'static str {
match self {
CameraCodec::H264 => "h264",
CameraCodec::Mjpeg => "mjpeg",
}
}
}
#[derive(Clone, Debug)]
pub struct HdmiConnector {
pub name: String,
pub id: Option<u32>,
}
#[derive(Clone, Debug)]
pub struct CameraConfig {
pub output: CameraOutput,
pub codec: CameraCodec,
pub width: u32,
pub height: u32,
pub fps: u32,
pub hdmi: Option<HdmiConnector>,
}
static LAST_CONFIG: OnceLock<RwLock<CameraConfig>> = OnceLock::new();
/// Refresh the cached camera config from the current environment.
///
/// Inputs: none; the selector consults the current environment and local
/// `/sys/class/drm` state.
/// Outputs: the newly selected camera configuration, which is also stored as
/// the last-known config for future reads.
/// Why: callers need a single entrypoint for changing the active output mode
/// without re-implementing the selection rules.
2026-01-28 17:52:00 -03:00
pub fn update_camera_config() -> CameraConfig {
let cfg = select_camera_config();
let lock = LAST_CONFIG.get_or_init(|| RwLock::new(cfg.clone()));
*lock.write().unwrap() = cfg.clone();
cfg
}
/// Return the last selected camera configuration.
///
/// Inputs: none.
/// Outputs: the cached camera configuration, or a freshly selected one when
/// the cache has not been initialized yet.
/// Why: call sites can read the active config without worrying about whether
/// initialization already happened in this process.
2026-01-28 17:52:00 -03:00
pub fn current_camera_config() -> CameraConfig {
if let Some(lock) = LAST_CONFIG.get() {
return lock.read().unwrap().clone();
}
update_camera_config()
}
fn select_camera_config() -> CameraConfig {
let output_env = std::env::var("LESAVKA_CAM_OUTPUT").ok();
let output_override = output_env.as_deref().and_then(parse_camera_output);
2026-01-28 17:52:00 -03:00
let require_connected = output_override != Some(CameraOutput::Hdmi);
let hdmi = detect_hdmi_connector(require_connected);
if output_override == Some(CameraOutput::Hdmi) && hdmi.is_none() {
warn!("📷 HDMI output forced but no connector detected");
}
let output = match output_override {
Some(v) => v,
None => {
if hdmi.is_some() {
CameraOutput::Hdmi
} else {
CameraOutput::Uvc
}
}
};
let cfg = match output {
CameraOutput::Hdmi => select_hdmi_config(hdmi),
CameraOutput::Uvc => select_uvc_config(),
};
info!(
output = cfg.output.as_str(),
codec = cfg.codec.as_str(),
width = cfg.width,
height = cfg.height,
fps = cfg.fps,
hdmi = cfg.hdmi.as_ref().map(|h| h.name.as_str()).unwrap_or("none"),
"📷 camera output selected"
);
cfg
}
fn parse_camera_output(raw: &str) -> Option<CameraOutput> {
match raw.trim().to_ascii_lowercase().as_str() {
"uvc" => Some(CameraOutput::Uvc),
"hdmi" => Some(CameraOutput::Hdmi),
"auto" | "" => None,
_ => None,
}
}
fn select_hdmi_config(hdmi: Option<HdmiConnector>) -> CameraConfig {
let hw_decode = has_hw_h264_decode();
let (width, height) = if hw_decode { (1920, 1080) } else { (1280, 720) };
let fps = 30;
if !hw_decode {
warn!("📷 HDMI output: hardware H264 decoder not detected; using 720p30");
}
CameraConfig {
output: CameraOutput::Hdmi,
codec: CameraCodec::H264,
width,
height,
fps,
hdmi,
}
}
fn select_uvc_config() -> CameraConfig {
let mut uvc_env = HashMap::new();
if let Ok(text) = fs::read_to_string("/etc/lesavka/uvc.env") {
uvc_env = parse_env_file(&text);
}
let width = read_u32_from_env("LESAVKA_UVC_WIDTH")
.or_else(|| read_u32_from_map(&uvc_env, "LESAVKA_UVC_WIDTH"))
.unwrap_or(1280);
let height = read_u32_from_env("LESAVKA_UVC_HEIGHT")
.or_else(|| read_u32_from_map(&uvc_env, "LESAVKA_UVC_HEIGHT"))
.unwrap_or(720);
let fps = read_u32_from_env("LESAVKA_UVC_FPS")
.or_else(|| read_u32_from_map(&uvc_env, "LESAVKA_UVC_FPS"))
.or_else(|| {
read_u32_from_env("LESAVKA_UVC_INTERVAL")
.or_else(|| read_u32_from_map(&uvc_env, "LESAVKA_UVC_INTERVAL"))
.and_then(|interval| {
if interval == 0 {
None
} else {
Some(10_000_000 / interval)
}
})
})
.unwrap_or(25);
CameraConfig {
output: CameraOutput::Uvc,
codec: CameraCodec::Mjpeg,
width,
height,
fps,
hdmi: None,
}
}
fn has_hw_h264_decode() -> bool {
if gst::init().is_err() {
return false;
}
for name in ["v4l2h264dec", "v4l2slh264dec", "omxh264dec"] {
if gst::ElementFactory::find(name).is_some() {
return true;
}
}
false
}
fn detect_hdmi_connector(require_connected: bool) -> Option<HdmiConnector> {
let preferred = std::env::var("LESAVKA_HDMI_CONNECTOR").ok();
let entries = fs::read_dir("/sys/class/drm").ok()?;
let mut connectors = Vec::new();
for entry in entries.flatten() {
let name = entry.file_name().to_string_lossy().into_owned();
if !name.contains("HDMI-A-") {
continue;
}
let status_path = entry.path().join("status");
let status = fs::read_to_string(&status_path)
.ok()
.map(|v| v.trim().to_string())
.unwrap_or_default();
let id = fs::read_to_string(entry.path().join("connector_id"))
.ok()
.and_then(|v| v.trim().parse::<u32>().ok());
connectors.push((name, status, id));
}
connectors.sort_by(|a, b| a.0.cmp(&b.0));
2026-01-28 17:52:00 -03:00
let matches_preferred =
|name: &str, preferred: &str| name == preferred || name.ends_with(preferred);
2026-01-28 17:52:00 -03:00
if let Some(pref) = preferred.as_deref() {
for (name, status, id) in &connectors {
if matches_preferred(name, pref) && (!require_connected || status == "connected") {
2026-01-28 17:52:00 -03:00
return Some(HdmiConnector {
name: name.clone(),
id: *id,
});
}
}
}
// Keep the previously-selected connector stable when no explicit override is set.
// This prevents connector flapping when multiple HDMI outputs are simultaneously connected.
if preferred.is_none() {
let previous = LAST_CONFIG
.get()
.and_then(|lock| lock.read().ok())
.and_then(|cfg| cfg.hdmi.as_ref().map(|h| h.name.clone()));
if let Some(prev) = previous {
for (name, status, id) in &connectors {
if *name == prev && (!require_connected || status == "connected") {
return Some(HdmiConnector {
name: name.clone(),
id: *id,
});
}
}
}
}
2026-01-28 17:52:00 -03:00
for (name, status, id) in connectors {
if !require_connected || status == "connected" {
return Some(HdmiConnector { name, id });
}
}
None
}
fn parse_env_file(text: &str) -> HashMap<String, String> {
let mut out = HashMap::new();
for line in text.lines() {
let line = line.trim();
if line.is_empty() || line.starts_with('#') {
continue;
}
let mut parts = line.splitn(2, '=');
let key = match parts.next() {
Some(v) => v.trim(),
None => continue,
};
let val = match parts.next() {
Some(v) => v.trim(),
None => continue,
};
out.insert(key.to_string(), val.to_string());
}
out
}
fn read_u32_from_env(key: &str) -> Option<u32> {
std::env::var(key).ok().and_then(|v| v.parse::<u32>().ok())
}
fn read_u32_from_map(map: &HashMap<String, String>, key: &str) -> Option<u32> {
map.get(key).and_then(|v| v.parse::<u32>().ok())
}
#[cfg(test)]
mod tests {
use super::{CameraCodec, CameraOutput, current_camera_config, update_camera_config};
use serial_test::serial;
use temp_env::with_var;
#[test]
#[serial]
fn camera_config_env_override_prefers_uvc_values() {
with_var("LESAVKA_CAM_OUTPUT", Some("uvc"), || {
with_var("LESAVKA_UVC_WIDTH", Some("800"), || {
with_var("LESAVKA_UVC_HEIGHT", Some("600"), || {
with_var("LESAVKA_UVC_FPS", Some("24"), || {
let cfg = update_camera_config();
assert_eq!(cfg.output, CameraOutput::Uvc);
assert_eq!(cfg.codec, CameraCodec::Mjpeg);
assert_eq!(cfg.width, 800);
assert_eq!(cfg.height, 600);
assert_eq!(cfg.fps, 24);
let cached = current_camera_config();
assert_eq!(cached.output, CameraOutput::Uvc);
assert_eq!(cached.codec, CameraCodec::Mjpeg);
assert_eq!(cached.width, 800);
assert_eq!(cached.height, 600);
assert_eq!(cached.fps, 24);
});
});
});
});
}
}