lesavka/client/src/input/camera.rs

224 lines
8.7 KiB
Rust
Raw Normal View History

2025-06-08 22:24:14 -05:00
// client/src/input/camera.rs
2025-07-03 08:19:59 -05:00
#![forbid(unsafe_code)]
2025-06-08 22:24:14 -05:00
2025-07-03 09:24:57 -05:00
use anyhow::Context;
use gst::prelude::*;
2025-07-03 08:19:59 -05:00
use gstreamer as gst;
use gstreamer_app as gst_app;
use lesavka_common::lesavka::VideoPacket;
2025-06-08 22:24:14 -05:00
fn env_u32(name: &str, default: u32) -> u32 {
std::env::var(name)
.ok()
.and_then(|v| v.parse::<u32>().ok())
.unwrap_or(default)
}
2025-06-08 22:24:14 -05:00
pub struct CameraCapture {
#[allow(dead_code)] // kept alive to hold PLAYING state
2025-07-03 08:19:59 -05:00
pipeline: gst::Pipeline,
sink: gst_app::AppSink,
2025-06-08 22:24:14 -05:00
}
impl CameraCapture {
2025-07-03 08:19:59 -05:00
pub fn new(device_fragment: Option<&str>) -> anyhow::Result<Self> {
gst::init().ok();
// Pick device (prefers V4L2 nodes with capture capability)
let dev = match device_fragment {
Some(path) if path.starts_with("/dev/") => path.to_string(),
Some(fragment) => Self::find_device(fragment).unwrap_or_else(|| "/dev/video0".into()),
None => "/dev/video0".into(),
};
2025-07-03 08:19:59 -05:00
2026-01-06 16:19:55 -03:00
let use_mjpg = std::env::var("LESAVKA_CAM_MJPG").is_ok()
|| std::env::var("LESAVKA_CAM_FORMAT")
.ok()
.map(|v| matches!(v.to_ascii_lowercase().as_str(), "mjpg" | "mjpeg" | "jpeg"))
.unwrap_or(false);
let (enc, kf_prop, kf_val) = if use_mjpg {
("x264enc", "key-int-max", "30")
} else {
Self::choose_encoder()
};
if use_mjpg {
tracing::info!("📸 using MJPG source with software encode");
}
2025-07-03 15:22:30 -05:00
tracing::info!("📸 using encoder element: {enc}");
let width = env_u32("LESAVKA_CAM_WIDTH", 1280);
let height = env_u32("LESAVKA_CAM_HEIGHT", 720);
2026-01-06 10:05:21 -03:00
let fps = env_u32("LESAVKA_CAM_FPS", 25).max(1);
2025-07-04 18:00:49 -05:00
let have_nvvidconv = gst::ElementFactory::find("nvvidconv").is_some();
2025-07-04 01:56:59 -05:00
let (src_caps, preenc) = match enc {
2025-07-04 18:00:49 -05:00
// ───────────────────────────────────────────────────────────────────
// Jetson (has nvvidconv) Desktop (falls back to videoconvert)
// ───────────────────────────────────────────────────────────────────
"nvh264enc" if have_nvvidconv =>
(format!(
"video/x-raw(memory:NVMM),format=NV12,width={width},height={height},framerate={fps}/1"
), "nvvidconv !"),
2025-07-04 18:00:49 -05:00
"nvh264enc" /* else */ =>
(format!(
"video/x-raw,format=NV12,width={width},height={height},framerate={fps}/1"
), "videoconvert !"),
2025-07-04 18:00:49 -05:00
"vaapih264enc" =>
(format!(
"video/x-raw,format=NV12,width={width},height={height},framerate={fps}/1"
), "videoconvert !"),
2025-07-04 18:00:49 -05:00
_ =>
(format!(
"video/x-raw,width={width},height={height},framerate={fps}/1"
), "videoconvert !"),
};
2025-07-03 15:22:30 -05:00
// let desc = format!(
// "v4l2src device={dev} do-timestamp=true ! {raw_caps},width=1280,height=720 ! \
// videoconvert ! {enc} key-int-max=30 ! \
// h264parse config-interval=-1 ! \
// appsink name=asink emit-signals=true max-buffers=60 drop=true"
// );
// tracing::debug!(%desc, "📸 pipeline-desc");
// Build a pipeline that works for any of the three encoders.
// * nvh264enc needs NVMM memory caps;
// * vaapih264enc wants system-memory caps;
// * x264enc needs the usual raw caps.
2026-01-06 16:19:55 -03:00
let desc = if use_mjpg {
format!(
"v4l2src device={dev} do-timestamp=true ! \
image/jpeg,width={width},height={height} ! \
jpegdec ! videorate ! video/x-raw,framerate={fps}/1 ! \
videoconvert ! {enc} {kf_prop}={kf_val} ! \
h264parse config-interval=-1 ! video/x-h264,stream-format=byte-stream,alignment=au ! \
queue max-size-buffers=30 leaky=downstream ! \
appsink name=asink emit-signals=true max-buffers=60 drop=true"
)
} else {
format!(
"v4l2src device={dev} do-timestamp=true ! {src_caps} ! \
{preenc} {enc} {kf_prop}={kf_val} ! \
h264parse config-interval=-1 ! video/x-h264,stream-format=byte-stream,alignment=au ! \
queue max-size-buffers=30 leaky=downstream ! \
appsink name=asink emit-signals=true max-buffers=60 drop=true"
)
};
tracing::info!(%enc, width, height, fps, ?desc, "📸 using encoder element");
2025-07-03 08:19:59 -05:00
2025-07-03 09:24:57 -05:00
let pipeline: gst::Pipeline = gst::parse::launch(&desc)
.context("gst parse_launch(cam)")?
2025-07-03 08:19:59 -05:00
.downcast::<gst::Pipeline>()
.expect("not a pipeline");
2025-07-03 09:24:57 -05:00
tracing::debug!("📸 pipeline built OK setting PLAYING…");
2025-07-03 08:19:59 -05:00
let sink: gst_app::AppSink = pipeline
.by_name("asink")
.expect("appsink element not found")
.downcast::<gst_app::AppSink>()
.expect("appsink downcast");
pipeline.set_state(gst::State::Playing)?;
2025-07-03 09:24:57 -05:00
tracing::info!("📸 webcam pipeline ▶️ device={dev}");
2025-07-03 08:19:59 -05:00
Ok(Self { pipeline, sink })
2025-06-08 22:24:14 -05:00
}
2025-07-03 08:19:59 -05:00
pub fn pull(&self) -> Option<VideoPacket> {
let sample = self.sink.pull_sample().ok()?;
let buf = sample.buffer()?;
let map = buf.map_readable().ok()?;
2025-07-03 08:19:59 -05:00
let pts = buf.pts().unwrap_or(gst::ClockTime::ZERO).nseconds() / 1_000;
Some(VideoPacket {
id: 2,
pts,
data: map.as_slice().to_vec(),
})
2025-07-03 08:19:59 -05:00
}
/// Fuzzymatch devices under `/dev/v4l/by-id`, preferring capture nodes
2025-07-03 08:19:59 -05:00
fn find_device(substr: &str) -> Option<String> {
let wanted = substr.to_ascii_lowercase();
let mut matches: Vec<_> = std::fs::read_dir("/dev/v4l/by-id")
.ok()?
.flatten()
.filter_map(|e| {
let p = e.path();
let name = p.file_name()?.to_string_lossy().to_ascii_lowercase();
if name.contains(&wanted) {
Some(p)
} else {
None
}
})
.collect();
// deterministic order
matches.sort();
for p in matches {
if let Ok(target) = std::fs::read_link(&p) {
let dev = format!("/dev/{}", target.file_name()?.to_string_lossy());
if Self::is_capture(&dev) {
return Some(dev);
2025-07-03 08:19:59 -05:00
}
}
}
None
}
fn is_capture(dev: &str) -> bool {
2025-11-30 23:41:29 -03:00
const V4L2_CAP_VIDEO_CAPTURE: u32 = 0x0000_0001;
const V4L2_CAP_VIDEO_CAPTURE_MPLANE: u32 = 0x0000_1000;
v4l::Device::with_path(dev)
.ok()
.and_then(|d| d.query_caps().ok())
.map(|caps| {
let bits = caps.capabilities.bits();
(bits & V4L2_CAP_VIDEO_CAPTURE != 0) || (bits & V4L2_CAP_VIDEO_CAPTURE_MPLANE != 0)
2025-11-30 23:41:29 -03:00
})
.unwrap_or(false)
}
2025-07-03 08:19:59 -05:00
/// Cheap stub used when the webcam is disabled
pub fn new_stub() -> Self {
let pipeline = gst::Pipeline::new();
let sink: gst_app::AppSink = gst::ElementFactory::make("appsink")
.build()
2025-07-03 09:24:57 -05:00
.expect("appsink")
2025-07-03 08:19:59 -05:00
.downcast::<gst_app::AppSink>()
2025-07-03 09:24:57 -05:00
.unwrap();
2025-07-03 08:19:59 -05:00
Self { pipeline, sink }
2025-06-08 22:24:14 -05:00
}
2025-07-03 15:22:30 -05:00
#[allow(dead_code)] // helper kept for future heuristics
2025-07-03 15:22:30 -05:00
fn pick_encoder() -> (&'static str, &'static str) {
let encoders = &[
("nvh264enc", "video/x-raw(memory:NVMM),format=NV12"),
("vaapih264enc", "video/x-raw,format=NV12"),
("v4l2h264enc", "video/x-raw"), // RPi, Jetson, etc.
("x264enc", "video/x-raw"), // software
2025-07-03 15:22:30 -05:00
];
for (name, caps) in encoders {
if gst::ElementFactory::find(name).is_some() {
return (name, caps);
}
}
// last resort software
("x264enc", "video/x-raw")
}
fn choose_encoder() -> (&'static str, &'static str, &'static str) {
2025-07-04 01:56:59 -05:00
match () {
_ if gst::ElementFactory::find("nvh264enc").is_some() => {
("nvh264enc", "gop-size", "30")
}
_ if gst::ElementFactory::find("vaapih264enc").is_some() => {
("vaapih264enc", "keyframe-period", "30")
}
_ if gst::ElementFactory::find("v4l2h264enc").is_some() => {
("v4l2h264enc", "idrcount", "30")
}
_ => ("x264enc", "key-int-max", "30"),
2025-07-03 15:22:30 -05:00
}
}
2025-06-08 22:24:14 -05:00
}