use std::fs::{self, OpenOptions}; use std::io::Write; use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicU64, Ordering}; use std::time::{SystemTime, UNIX_EPOCH}; use gstreamer as gst; use gstreamer_app as gst_app; static SPOOL_SEQUENCE: AtomicU64 = AtomicU64::new(1); #[derive(Clone, Copy)] pub(super) struct MjpegSpoolTiming { pub profile: &'static str, pub source_pts_us: Option, pub decoded_pts_us: Option, } impl MjpegSpoolTiming { /// Build metadata for direct MJPEG ingress. /// /// Inputs: the upstream packet PTS in microseconds. Output: timing metadata /// labeled as passthrough MJPEG. Why: direct MJPEG and decoded HEVC share /// the same spool file, so future diagnostics need to distinguish them. pub(super) fn mjpeg_passthrough(source_pts_us: u64) -> Self { Self { profile: "mjpeg-passthrough", source_pts_us: Some(source_pts_us), decoded_pts_us: None, } } /// Build metadata for decoded HEVC entering the MJPEG UVC helper. /// /// Inputs: upstream packet PTS plus the decoded appsink buffer PTS. /// Output: timing metadata labeled as HEVC-decoded MJPEG. Why: the /// remaining HEVC sync jitter appears after transport, so we need a /// low-overhead marker at the decode-to-UVC handoff boundary. pub(super) fn hevc_decoded_mjpeg(source_pts_us: u64, decoded_pts_us: Option) -> Self { Self { profile: "hevc-decoded-mjpeg", source_pts_us: Some(source_pts_us), decoded_pts_us, } } } /// Decide whether the UVC helper file-spool path should own MJPEG emission. /// /// Inputs: `LESAVKA_UVC_MJPEG_SPOOL`. Output: true unless explicitly disabled. /// Why: the helper path prevents two processes from fighting over the UVC /// gadget node, while preserving a direct `v4l2sink` fallback for diagnostics. pub(super) fn mjpeg_spool_enabled() -> bool { std::env::var("LESAVKA_UVC_MJPEG_SPOOL") .ok() .map(|value| { let trimmed = value.trim(); !(trimmed.eq_ignore_ascii_case("0") || trimmed.eq_ignore_ascii_case("false") || trimmed.eq_ignore_ascii_case("no") || trimmed.eq_ignore_ascii_case("off")) }) .unwrap_or(true) } /// Resolve the frame path consumed by the UVC helper. /// /// Inputs: `LESAVKA_UVC_FRAME_PATH`. Output: filesystem path for the newest /// MJPEG frame. Why: the helper polls a single atomic frame file, so both direct /// MJPEG and decoded HEVC output need to agree on the handoff location. pub(super) fn mjpeg_spool_path() -> PathBuf { std::env::var("LESAVKA_UVC_FRAME_PATH") .map(PathBuf::from) .unwrap_or_else(|_| PathBuf::from("/run/lesavka-uvc-frame.mjpg")) } /// Decide whether frame spool metadata should be published. /// /// Inputs: `LESAVKA_UVC_FRAME_META`. Output: false unless explicitly enabled. /// Why: the metadata is useful for HEVC boundary diagnostics, but it adds one /// extra atomic sidecar write per frame and should stay opt-in during calls. pub(super) fn mjpeg_spool_metadata_enabled() -> bool { std::env::var("LESAVKA_UVC_FRAME_META") .ok() .map(|value| { let trimmed = value.trim(); trimmed.eq_ignore_ascii_case("1") || trimmed.eq_ignore_ascii_case("true") || trimmed.eq_ignore_ascii_case("yes") || trimmed.eq_ignore_ascii_case("on") }) .unwrap_or(false) } /// Resolve the metadata sidecar path for the UVC helper spool. /// /// Inputs: frame path plus `LESAVKA_UVC_FRAME_META_PATH`. Output: sidecar path. /// Why: keeping this path explicit lets capture scripts fetch timing evidence /// without guessing where the virtual webcam helper found the frame. pub(super) fn mjpeg_spool_metadata_path(frame_path: &Path) -> PathBuf { std::env::var("LESAVKA_UVC_FRAME_META_PATH") .map(PathBuf::from) .unwrap_or_else(|_| frame_path.with_extension("mjpg.meta.json")) } /// Resolve the optional JSONL metadata log for full-probe diagnostics. /// /// Inputs: `LESAVKA_UVC_FRAME_META_LOG_PATH`. Output: an append-only log path /// when configured. Why: a latest-frame sidecar is enough for spot checks, but /// client-to-RCT HEVC probes need the whole decode/spool timing sequence. pub(super) fn mjpeg_spool_metadata_log_path() -> Option { std::env::var("LESAVKA_UVC_FRAME_META_LOG_PATH") .ok() .map(|value| value.trim().to_string()) .filter(|value| !value.is_empty()) .map(PathBuf::from) } /// Bound how long one HEVC handoff may wait for decoded MJPEG output. /// /// Inputs: `LESAVKA_UVC_HEVC_SPOOL_PULL_TIMEOUT_MS`, clamped to 0..=50ms. /// Output: the timeout used by appsink polling. /// Why: decoded frames should be published when they are due, but the video /// handoff worker must not build a WAN-sized backlog while waiting on decode. pub(super) fn decoded_mjpeg_pull_timeout() -> gst::ClockTime { let timeout_ms = std::env::var("LESAVKA_UVC_HEVC_SPOOL_PULL_TIMEOUT_MS") .ok() .and_then(|value| value.trim().parse::().ok()) .unwrap_or(5) .min(50); gst::ClockTime::from_mseconds(timeout_ms) } /// Drain the decoded-MJPEG appsink down to its freshest sample. /// /// Inputs: the appsink owned by the HEVC-to-MJPEG branch. Output: the newest /// available sample, if any. Why: the UVC helper should see the latest decoded /// frame rather than letting stale decode output accumulate during CPU spikes. #[cfg(not(coverage))] pub(super) fn freshest_mjpeg_sample(sink: &gst_app::AppSink) -> Option { let mut newest = sink.try_pull_sample(decoded_mjpeg_pull_timeout()); while let Some(sample) = sink.try_pull_sample(gst::ClockTime::ZERO) { newest = Some(sample); } newest } fn unix_now_ns() -> u128 { SystemTime::now() .duration_since(UNIX_EPOCH) .map(|duration| duration.as_nanos()) .unwrap_or(0) } fn json_number_or_null(value: Option) -> String { value .map(|value| value.to_string()) .unwrap_or_else(|| "null".to_string()) } /// Atomically write a text sidecar beside the current frame. /// /// Inputs: a destination path and complete text payload. Output: success or /// filesystem error. Why: the latest-frame metadata sidecar should never be /// observed half-written while RCT probe scripts are collecting artifacts. fn write_atomic_text(path: &Path, data: &str) -> anyhow::Result<()> { if let Some(parent) = path.parent() { fs::create_dir_all(parent)?; } let tmp = path.with_extension(format!("json.{}.tmp", std::process::id())); fs::write(&tmp, data)?; fs::rename(&tmp, path)?; Ok(()) } /// Append one timing record to the optional full-probe metadata log. /// /// Inputs: a JSONL path and already formatted metadata record. Output: success /// or filesystem error. Why: HEVC/RCT debugging needs every decoded-MJPEG /// handoff timestamp, while the latest sidecar only preserves the newest frame. fn append_metadata_log(path: &Path, record: &str) -> anyhow::Result<()> { if let Some(parent) = path.parent() { fs::create_dir_all(parent)?; } OpenOptions::new() .create(true) .append(true) .open(path)? .write_all(record.as_bytes())?; Ok(()) } /// Render one metadata record for a spooled MJPEG frame. /// /// Inputs: a sequence number, frame size, and timing labels. Output: compact /// JSON suitable for sidecar artifacts. Why: keeping the format deterministic /// makes later client-to-RCT scripts able to compare server decode/spool timing /// against final RCT observations without parsing log prose. pub(super) fn format_mjpeg_spool_metadata( sequence: u64, bytes: usize, timing: MjpegSpoolTiming, ) -> String { format!( "{{\"schema\":\"lesavka.uvc-mjpeg-spool-meta.v1\",\"sequence\":{},\"profile\":\"{}\",\"bytes\":{},\"source_pts_us\":{},\"decoded_pts_us\":{},\"spool_unix_ns\":{}}}\n", sequence, timing.profile, bytes, json_number_or_null(timing.source_pts_us), json_number_or_null(timing.decoded_pts_us), unix_now_ns() ) } /// Atomically publish one MJPEG frame plus optional timing metadata. /// /// Inputs: destination path, JPEG bytes, and optional timing metadata. Output: /// success or filesystem error. Why: HEVC transport debugging needs to know /// whether residual jitter happens before or after the decoded-MJPEG handoff, /// while the default runtime path should remain identical when metadata is off. pub(super) fn spool_mjpeg_frame_with_timing( path: &Path, data: &[u8], timing: Option, ) -> anyhow::Result<()> { if let Some(parent) = path.parent() { fs::create_dir_all(parent)?; } let tmp = path.with_extension(format!("mjpg.{}.tmp", std::process::id())); fs::write(&tmp, data)?; fs::rename(&tmp, path)?; if mjpeg_spool_metadata_enabled() && let Some(timing) = timing { let sequence = SPOOL_SEQUENCE.fetch_add(1, Ordering::Relaxed); let record = format_mjpeg_spool_metadata(sequence, data.len(), timing); write_atomic_text(&mjpeg_spool_metadata_path(path), &record)?; if let Some(log_path) = mjpeg_spool_metadata_log_path() { append_metadata_log(&log_path, &record)?; } } Ok(()) } #[cfg(test)] mod tests { /// Verifies HEVC decoded-frame polling defaults to a freshness-first wait. /// /// Input: unset timeout env var. Output: 5ms appsink poll timeout. Why: /// server-side decode should keep enough patience for normal scheduling /// jitter without letting an HEVC backlog accumulate behind UVC playback. #[test] fn decoded_mjpeg_pull_timeout_defaults_to_short_bounded_wait() { temp_env::with_var_unset("LESAVKA_UVC_HEVC_SPOOL_PULL_TIMEOUT_MS", || { assert_eq!( super::decoded_mjpeg_pull_timeout(), gstreamer::ClockTime::from_mseconds(5) ); }); } /// Verifies explicit HEVC spool polling overrides stay bounded. /// /// Input: zero and oversized timeout values. Output: direct zero polling /// and a 50ms safety cap. Why: lab tuning may need aggressive polling, but /// no override should recreate the multi-second decoded-frame backlog. #[test] fn decoded_mjpeg_pull_timeout_allows_fast_poll_and_clamps_slow_waits() { temp_env::with_var("LESAVKA_UVC_HEVC_SPOOL_PULL_TIMEOUT_MS", Some("0"), || { assert_eq!( super::decoded_mjpeg_pull_timeout(), gstreamer::ClockTime::from_mseconds(0) ); }); temp_env::with_var("LESAVKA_UVC_HEVC_SPOOL_PULL_TIMEOUT_MS", Some("250"), || { assert_eq!( super::decoded_mjpeg_pull_timeout(), gstreamer::ClockTime::from_mseconds(50) ); }); } /// Verifies spool metadata remains opt-in and path-configurable. /// /// Input: default and explicit metadata env vars. Output: disabled by /// default plus deterministic sidecar path selection. Why: diagnostics must /// not add per-frame writes unless the operator asks for timing evidence. #[test] fn mjpeg_spool_metadata_is_opt_in_and_path_configurable() { temp_env::with_var_unset("LESAVKA_UVC_FRAME_META", || { assert!(!super::mjpeg_spool_metadata_enabled()); }); temp_env::with_var("LESAVKA_UVC_FRAME_META", Some("yes"), || { assert!(super::mjpeg_spool_metadata_enabled()); }); let frame = std::path::Path::new("/tmp/lesavka-frame.mjpg"); temp_env::with_var_unset("LESAVKA_UVC_FRAME_META_PATH", || { assert_eq!( super::mjpeg_spool_metadata_path(frame), std::path::PathBuf::from("/tmp/lesavka-frame.mjpg.meta.json") ); }); temp_env::with_var( "LESAVKA_UVC_FRAME_META_PATH", Some("/tmp/custom-meta.json"), || { assert_eq!( super::mjpeg_spool_metadata_path(frame), std::path::PathBuf::from("/tmp/custom-meta.json") ); }, ); temp_env::with_var_unset("LESAVKA_UVC_FRAME_META_LOG_PATH", || { assert_eq!(super::mjpeg_spool_metadata_log_path(), None); }); temp_env::with_var("LESAVKA_UVC_FRAME_META_LOG_PATH", Some(" "), || { assert_eq!(super::mjpeg_spool_metadata_log_path(), None); }); } /// Verifies metadata records carry enough timing evidence for RCT analysis. /// /// Input: HEVC-decoded spool timing. Output: JSON fields for source and /// decoded PTS. Why: future blind end-to-end probes need to tell whether a /// bad RCT result came from transport/decode or from the UVC helper/browser. #[test] fn mjpeg_spool_metadata_formats_timing_fields() { let record = super::format_mjpeg_spool_metadata( 7, 1234, super::MjpegSpoolTiming::hevc_decoded_mjpeg(42_000, Some(43_000)), ); assert!(record.contains("\"schema\":\"lesavka.uvc-mjpeg-spool-meta.v1\"")); assert!(record.contains("\"sequence\":7")); assert!(record.contains("\"profile\":\"hevc-decoded-mjpeg\"")); assert!(record.contains("\"bytes\":1234")); assert!(record.contains("\"source_pts_us\":42000")); assert!(record.contains("\"decoded_pts_us\":43000")); } /// Verifies direct MJPEG metadata explicitly marks passthrough timing. /// /// Input: an upstream MJPEG packet PTS. Output: metadata with no decoded /// PTS. Why: direct MJPEG ingress must remain distinguishable from HEVC /// decode when later RCT timing evidence is compared across profiles. #[test] fn mjpeg_passthrough_metadata_uses_source_pts_and_null_decode_pts() { let record = super::format_mjpeg_spool_metadata( 8, 99, super::MjpegSpoolTiming::mjpeg_passthrough(55_000), ); assert!(record.contains("\"profile\":\"mjpeg-passthrough\"")); assert!(record.contains("\"source_pts_us\":55000")); assert!(record.contains("\"decoded_pts_us\":null")); } /// Verifies frame spooling preserves default behavior unless metadata is enabled. /// /// Input: a temporary frame path plus disabled metadata env vars. Output: /// the frame file is atomically written and no sidecar appears. Why: /// diagnostics must not alter the normal UVC helper handoff during calls. #[test] fn spool_mjpeg_frame_writes_frame_without_default_sidecar() { let dir = tempfile::tempdir().expect("tempdir"); let frame = dir.path().join("nested").join("frame.mjpg"); let meta = frame.with_extension("mjpg.meta.json"); temp_env::with_var_unset("LESAVKA_UVC_FRAME_META", || { super::spool_mjpeg_frame_with_timing( &frame, b"jpeg-bytes", Some(super::MjpegSpoolTiming::mjpeg_passthrough(10)), ) .expect("spool frame"); }); assert_eq!(std::fs::read(&frame).expect("read frame"), b"jpeg-bytes"); assert!(!meta.exists()); } /// Verifies enabled frame metadata is atomically written beside the frame. /// /// Input: explicit metadata enablement, custom sidecar path, and HEVC /// timing. Output: both frame and sidecar are published. Why: this gives /// client-to-RCT probes a precise server decode/spool boundary without /// requiring invasive server logging. #[test] fn spool_mjpeg_frame_writes_enabled_sidecar_with_timing() { let dir = tempfile::tempdir().expect("tempdir"); let frame = dir.path().join("frame.mjpg"); let meta = dir.path().join("frame-meta.json"); let log = dir.path().join("frames.jsonl"); temp_env::with_vars( [ ("LESAVKA_UVC_FRAME_META", Some("on")), ( "LESAVKA_UVC_FRAME_META_PATH", Some(meta.to_str().expect("utf8 path")), ), ( "LESAVKA_UVC_FRAME_META_LOG_PATH", Some(log.to_str().expect("utf8 path")), ), ], || { super::spool_mjpeg_frame_with_timing( &frame, b"decoded-jpeg", Some(super::MjpegSpoolTiming::hevc_decoded_mjpeg( 100_000, Some(101_000), )), ) .expect("spool frame with metadata"); }, ); assert_eq!(std::fs::read(&frame).expect("read frame"), b"decoded-jpeg"); let record = std::fs::read_to_string(&meta).expect("read metadata"); assert!(record.contains("\"profile\":\"hevc-decoded-mjpeg\"")); assert!(record.contains("\"bytes\":12")); assert!(record.contains("\"source_pts_us\":100000")); assert!(record.contains("\"decoded_pts_us\":101000")); let log_record = std::fs::read_to_string(&log).expect("read metadata log"); assert_eq!(log_record.lines().count(), 1); assert!(log_record.contains("\"profile\":\"hevc-decoded-mjpeg\"")); } }