diff --git a/scripts/setup_radxa_usb_gadget.sh b/scripts/setup_radxa_usb_gadget.sh index 5bdb6ff..c4db6e7 100755 --- a/scripts/setup_radxa_usb_gadget.sh +++ b/scripts/setup_radxa_usb_gadget.sh @@ -1,28 +1,46 @@ #!/usr/bin/env bash set -euo pipefail -ROOTFS="/run/media/bleack/rootfs" +ROOTFS="${1:-/run/media/${USER:-bleack}/rootfs}" if [ ! -d "${ROOTFS}/etc" ]; then echo "Erreur : La partition rootfs n'est pas montée dans ${ROOTFS}" + echo "Usage : $0 [/chemin/vers/rootfs]" exit 1 fi -echo "=== Configuration du mode USB Gadget (RNDIS / CDC) sur la Radxa Zero 3W ===" +echo "=== Configuration du mode USB Gadget (RNDIS / CDC) sur la Radxa Zero 3W (${ROOTFS}) ===" # 1. Activer l'overlay device-tree rk3568-dwc3-peripheral -echo "[1/4] Activation de l'overlay DWC3 Peripheral mode..." -cp "${ROOTFS}/boot/dtbo/rk3568-dwc3-peripheral.dtbo.disabled" "${ROOTFS}/boot/dtbo/rk3568-dwc3-peripheral.dtbo" +echo "[1/5] Activation de l'overlay DWC3 Peripheral mode..." +if [ -f "${ROOTFS}/boot/dtbo/rk3568-dwc3-peripheral.dtbo.disabled" ]; then + cp "${ROOTFS}/boot/dtbo/rk3568-dwc3-peripheral.dtbo.disabled" "${ROOTFS}/boot/dtbo/rk3568-dwc3-peripheral.dtbo" +fi EXTLINUX="${ROOTFS}/boot/extlinux/extlinux.conf" -if ! grep -q "rk3568-dwc3-peripheral.dtbo" "${EXTLINUX}"; then +if [ -f "${EXTLINUX}" ] && ! grep -q "rk3568-dwc3-peripheral.dtbo" "${EXTLINUX}"; then sed -i '/fdtdir/a \ fdtoverlays /boot/dtbo/rk3568-dwc3-peripheral.dtbo' "${EXTLINUX}" fi -# 1b. Forcer l'activation de la sortie HDMI en mode headless (sans écran physique) -echo "[1b/5] Forçage de la sortie HDMI virtuelle (headless) dans extlinux.conf..." -if ! grep -q "video=HDMI-A-1" "${EXTLINUX}"; then - sed -i '/append/ s/$/ video=HDMI-A-1:1920x1080@60e/' "${EXTLINUX}" +# 1b. Forcer l'activation de la sortie HDMI en mode headless (1280x720@60e cohérent avec Ruby) +# et persister dans /etc/default/u-boot pour survivre à u-boot-update +echo "[1b/5] Forçage de la sortie HDMI virtuelle (headless 1280x720@60e)..." +HDMI_PARAMS="drm.edid_firmware=HDMI-A-1:edid/edid.bin video=HDMI-A-1:1280x720@60e" +if [ -f "${EXTLINUX}" ]; then + if ! grep -q "video=HDMI-A-1" "${EXTLINUX}"; then + sed -i "/append/ s|\$| ${HDMI_PARAMS}|" "${EXTLINUX}" + else + sed -i "s|video=HDMI-A-1:[^ ]*|video=HDMI-A-1:1280x720@60e|g" "${EXTLINUX}" + fi +fi + +UBOOT_DEFAULT="${ROOTFS}/etc/default/u-boot" +if [ -f "${UBOOT_DEFAULT}" ]; then + if ! grep -q "video=HDMI-A-1" "${UBOOT_DEFAULT}"; then + sed -i "s|^U_BOOT_PARAMETERS=\"\\(.*\\)\"|U_BOOT_PARAMETERS=\"\\1 ${HDMI_PARAMS}\"|" "${UBOOT_DEFAULT}" + else + sed -i "s|video=HDMI-A-1:[^ \"]*|video=HDMI-A-1:1280x720@60e|g" "${UBOOT_DEFAULT}" + fi fi # 2. Charger le module g_cdc au boot diff --git a/src/engine.rs b/src/engine.rs index 4a099e0..f606e43 100644 --- a/src/engine.rs +++ b/src/engine.rs @@ -2,7 +2,7 @@ use crate::config::AppConfig; use crate::dome_projection::{DomeWarpLut, ProjectionMode}; use crate::nomad_elrs::{HeadPoseSample, NomadHeadTracker}; use crate::telemetry_osd::{OsdOverlay, TelemetryReceiver, TelemetryState}; -use crate::video_usb::UsbVideoReceiver; +use crate::video_usb::{UsbVideoReceiver, VideoLinkState}; use crate::vulkan_xr::VulkanXrContext; use anyhow::{Context, Result}; use glam::{EulerRot, Quat}; @@ -66,6 +66,42 @@ impl Default for RuntimeMonitor { } } +/// Poignée légère et sans verrou permettant à l'interface graphique de piloter +/// les commandes temps réel (Tare, OSD, Head-Tracking) sans jamais bloquer sur +/// le Mutex de cycle de vie du moteur (`start` / `stop`). +#[derive(Clone)] +pub struct EngineControlHandle { + recenter_flag: Arc, + telemetry_enabled_flag: Arc, + head_tracking_enabled_flag: Arc, +} + +impl EngineControlHandle { + pub fn request_recenter(&self) { + self.recenter_flag.store(true, Ordering::Release); + } + + pub fn set_telemetry_enabled(&self, enabled: bool) { + let prev = self.telemetry_enabled_flag.swap(enabled, Ordering::AcqRel); + if prev != enabled { + log::info!( + "[Action Utilisateur] Télémétrie & OSD basculés sur : {}", + if enabled { "ON (Activé)" } else { "OFF (Désactivé)" } + ); + } + } + + pub fn set_head_tracking_enabled(&self, enabled: bool) { + let prev = self.head_tracking_enabled_flag.swap(enabled, Ordering::AcqRel); + if prev != enabled { + log::info!( + "[Action Utilisateur] Suivi de Tête (RadioMaster Nomad) basculé sur : {}", + if enabled { "ON (Activé)" } else { "OFF (Désactivé)" } + ); + } + } +} + pub struct FpvEngineController { pub monitor: Arc>, stop_flag: Arc, @@ -87,6 +123,14 @@ impl FpvEngineController { } } + pub fn control_handle(&self) -> EngineControlHandle { + EngineControlHandle { + recenter_flag: Arc::clone(&self.recenter_flag), + telemetry_enabled_flag: Arc::clone(&self.telemetry_enabled_flag), + head_tracking_enabled_flag: Arc::clone(&self.head_tracking_enabled_flag), + } + } + pub fn is_running(&self) -> bool { self.worker_handle .as_ref() @@ -269,6 +313,41 @@ fn sync_head_tracker( } } +fn sync_video_status( + cfg: &AppConfig, + video_rx_opt: Option<&UsbVideoReceiver>, + monitor: &Arc>, +) { + let status_desc = if cfg.usb_video_mode.eq_ignore_ascii_case("uvc") { + format!("Mini-HDMI UVC ({})", cfg.uvc_device) + } else { + format!( + "USB OTG RNDIS {}:{} ({}/{})", + cfg.usb_bind_ip, + cfg.video_udp_port, + cfg.codec.to_uppercase(), + cfg.stream_transport.to_uppercase() + ) + }; + + let next_status = match video_rx_opt.map(|rx| rx.link_state()) { + Some(VideoLinkState::Live) => SubsystemStatus::Running(status_desc), + Some(VideoLinkState::Waiting) => { + SubsystemStatus::Warning(format!("En attente flux ({})", status_desc)) + } + Some(VideoLinkState::Lost) => { + SubsystemStatus::Warning(format!("Signal perdu ({})", status_desc)) + } + Some(VideoLinkState::Error(e)) => SubsystemStatus::Error(e), + None => SubsystemStatus::Error("Pipeline vidéo non initialisé".to_string()), + }; + + let mut mon = monitor.lock(); + if mon.usb_video_status != next_status { + mon.usb_video_status = next_status; + } +} + fn run_engine_worker( cfg: AppConfig, monitor: Arc>, @@ -284,8 +363,8 @@ fn run_engine_worker( cfg.usb_video_mode ); - // 1. Démarrage Vidéo USB (Mode OTG/RNDIS ou Mode Mini-HDMI UVC) - let mut video_rx_opt = match UsbVideoReceiver::start( + // 1. Démarrage Vidéo USB (Mode OTG/RNDIS ou Mode Mini-HDMI UVC) avec superviseur autonome + let video_rx_opt = match UsbVideoReceiver::start( &cfg.usb_video_mode, &cfg.uvc_device, &cfg.usb_bind_ip, @@ -296,18 +375,7 @@ fn run_engine_worker( cfg.video_height, ) { Ok(rx) => { - let status_desc = if cfg.usb_video_mode.eq_ignore_ascii_case("uvc") { - format!("Mini-HDMI UVC ({})", cfg.uvc_device) - } else { - format!( - "USB OTG RNDIS {}:{} ({}/{})", - cfg.usb_bind_ip, - cfg.video_udp_port, - cfg.codec.to_uppercase(), - cfg.stream_transport.to_uppercase() - ) - }; - monitor.lock().usb_video_status = SubsystemStatus::Running(status_desc); + sync_video_status(&cfg, Some(&rx), &monitor); Some(rx) } Err(e) => { @@ -336,37 +404,48 @@ fn run_engine_worker( ); // 4. Tentative d'initialisation OpenXR sur le Steam Frame - if let Err(xr_err) = try_run_openxr_session( + let xr_res = try_run_openxr_session( &cfg, &monitor, &stop_flag, &recenter_flag, &telem_enabled_flag, &ht_enabled_flag, - &mut video_rx_opt, + video_rx_opt.as_ref(), &mut telem_rx_opt, &mut head_tracker_opt, - ) { - if !stop_flag.load(Ordering::Relaxed) { - log::warn!( - "[OpenXR] Session VR indisponible ({}). Bascule automatique en mode Monitoring Bureau / Simulation.", - xr_err - ); - monitor.lock().openxr_status = - SubsystemStatus::Warning(format!("Mode Bureau (OpenXR inactif : {})", xr_err)); + ); - run_desktop_fallback_loop( - &cfg, - &monitor, - &stop_flag, - &recenter_flag, - &telem_enabled_flag, - &ht_enabled_flag, - &mut video_rx_opt, - &mut telem_rx_opt, - &mut head_tracker_opt, - ); + if !stop_flag.load(Ordering::Acquire) { + match xr_res { + Err(xr_err) => { + log::warn!( + "[OpenXR] Session VR indisponible ({}). Bascule automatique en mode Monitoring Bureau / Simulation.", + xr_err + ); + monitor.lock().openxr_status = + SubsystemStatus::Warning(format!("Mode Bureau (OpenXR inactif : {})", xr_err)); + } + Ok(()) => { + log::warn!( + "[OpenXR] Session VR terminée par le runtime. Bascule automatique en mode Monitoring Bureau / Simulation." + ); + monitor.lock().openxr_status = + SubsystemStatus::Warning("Mode Bureau (Session OpenXR terminée)".to_string()); + } } + + run_desktop_fallback_loop( + &cfg, + &monitor, + &stop_flag, + &recenter_flag, + &telem_enabled_flag, + &ht_enabled_flag, + video_rx_opt.as_ref(), + &mut telem_rx_opt, + &mut head_tracker_opt, + ); } log::info!("[Moteur FPV] Tous les sous-systèmes ont été arrêtés."); @@ -380,7 +459,7 @@ fn try_run_openxr_session( recenter_flag: &Arc, telem_enabled_flag: &Arc, ht_enabled_flag: &Arc, - video_rx_opt: &mut Option, + video_rx_opt: Option<&UsbVideoReceiver>, telem_rx_opt: &mut Option, head_tracker_opt: &mut Option, ) -> Result<()> { @@ -487,7 +566,6 @@ fn try_run_openxr_session( let mut fps_counter: u32 = 0; let mut fps_timer = Instant::now(); let mut last_frame_id: u64 = 0; - let mut last_rx_retry = Instant::now(); while !stop_flag.load(Ordering::Relaxed) { let telem_on = telem_enabled_flag.load(Ordering::Relaxed); @@ -567,7 +645,7 @@ fn try_run_openxr_session( let mut new_raw_frame: Option> = None; let mut has_video_stream = false; - if let Some(rx) = video_rx_opt.as_mut() { + if let Some(rx) = video_rx_opt { let lock = rx.latest_frame(); let guard = lock.lock(); if let Some(ref vf) = *guard { @@ -602,38 +680,6 @@ fn try_run_openxr_session( (cfg.video_height / 360).max(2), [255, 180, 40, 255], ); - - // Réarmement / reconnexion automatique du pipeline GStreamer toutes les 2 secondes - if last_rx_retry.elapsed() > Duration::from_millis(2000) { - last_rx_retry = Instant::now(); - if let Some(rx) = video_rx_opt.as_mut() { - log::info!("[USB Vidéo] Flux vidéo inactif, réarmement automatique du pipeline..."); - if rx.restart().is_err() || rx.is_broken() { - log::warn!("[USB Vidéo] Échec redémarrage doux, reconstruction complète du pipeline..."); - *video_rx_opt = UsbVideoReceiver::start( - &cfg.usb_video_mode, - &cfg.uvc_device, - &cfg.usb_bind_ip, - cfg.video_udp_port, - &cfg.codec, - &cfg.stream_transport, - cfg.video_width, - cfg.video_height, - ).ok(); - } - } else { - *video_rx_opt = UsbVideoReceiver::start( - &cfg.usb_video_mode, - &cfg.uvc_device, - &cfg.usb_bind_ip, - cfg.video_udp_port, - &cfg.codec, - &cfg.stream_transport, - cfg.video_width, - cfg.video_height, - ).ok(); - } - } } let telem_snapshot = telem_rx_opt @@ -659,6 +705,7 @@ fn try_run_openxr_session( vk_xr.upload_rgba_to_swapchain(&composited_rgba)?; if standby_tick % 2 == 0 || last_frame_id % 2 == 0 { + sync_video_status(cfg, video_rx_opt, monitor); let mut mon = monitor.lock(); if fps_timer.elapsed() >= Duration::from_secs(1) { if has_video_stream { @@ -763,7 +810,7 @@ fn run_desktop_fallback_loop( recenter_flag: &Arc, telem_enabled_flag: &Arc, ht_enabled_flag: &Arc, - video_rx_opt: &mut Option, + video_rx_opt: Option<&UsbVideoReceiver>, telem_rx_opt: &mut Option, head_tracker_opt: &mut Option, ) { @@ -780,7 +827,6 @@ fn run_desktop_fallback_loop( let mut last_frame_id: u64 = 0; let mut fps_counter: u32 = 0; let mut fps_timer = Instant::now(); - let mut last_rx_retry = Instant::now(); while !stop_flag.load(Ordering::Relaxed) { let loop_start = Instant::now(); @@ -820,7 +866,7 @@ fn run_desktop_fallback_loop( let mut new_raw_frame: Option> = None; let mut has_video_stream = false; - if let Some(rx) = video_rx_opt.as_mut() { + if let Some(rx) = video_rx_opt { let lock = rx.latest_frame(); let guard = lock.lock(); if let Some(ref vf) = *guard { @@ -855,38 +901,6 @@ fn run_desktop_fallback_loop( (cfg.video_height / 360).max(2), [255, 180, 40, 255], ); - - // Réarmement / reconnexion automatique du pipeline GStreamer toutes les 2 secondes - if last_rx_retry.elapsed() > Duration::from_millis(2000) { - last_rx_retry = Instant::now(); - if let Some(rx) = video_rx_opt.as_mut() { - log::info!("[USB Vidéo] Flux vidéo inactif, réarmement automatique du pipeline..."); - if rx.restart().is_err() || rx.is_broken() { - log::warn!("[USB Vidéo] Échec redémarrage doux, reconstruction complète du pipeline..."); - *video_rx_opt = UsbVideoReceiver::start( - &cfg.usb_video_mode, - &cfg.uvc_device, - &cfg.usb_bind_ip, - cfg.video_udp_port, - &cfg.codec, - &cfg.stream_transport, - cfg.video_width, - cfg.video_height, - ).ok(); - } - } else { - *video_rx_opt = UsbVideoReceiver::start( - &cfg.usb_video_mode, - &cfg.uvc_device, - &cfg.usb_bind_ip, - cfg.video_udp_port, - &cfg.codec, - &cfg.stream_transport, - cfg.video_width, - cfg.video_height, - ).ok(); - } - } } let telem_snapshot = telem_rx_opt @@ -909,6 +923,7 @@ fn run_desktop_fallback_loop( ); } + sync_video_status(cfg, video_rx_opt, monitor); { let mut mon = monitor.lock(); if fps_timer.elapsed() >= Duration::from_secs(1) { diff --git a/src/gui_gpui.rs b/src/gui_gpui.rs index c2f8437..de7ecef 100644 --- a/src/gui_gpui.rs +++ b/src/gui_gpui.rs @@ -1,5 +1,5 @@ use crate::config::AppConfig; -use crate::engine::{FpvEngineController, RuntimeMonitor, SubsystemStatus}; +use crate::engine::{EngineControlHandle, FpvEngineController, RuntimeMonitor, SubsystemStatus}; use crate::logger::{LogBuffer, LogEntry, LogFilter}; use crate::nomad_elrs::{HeadPoseSample, NomadHeadTracker}; use crate::telemetry_osd::TelemetryState; @@ -43,6 +43,7 @@ pub enum ActiveTab { pub struct SteamFrameGpuiApp { cfg: AppConfig, engine: Arc>, + controls: EngineControlHandle, engine_monitor: Arc>, log_buffer: Arc>, log_revision: Arc, @@ -73,12 +74,14 @@ impl SteamFrameGpuiApp { let mut engine = FpvEngineController::new(cfg.telemetry_enabled, cfg.head_tracking_enabled); engine.start(cfg.clone()); + let controls = engine.control_handle(); let engine_monitor = Arc::clone(&engine.monitor); let engine = Arc::new(Mutex::new(engine)); Self { cfg, engine, + controls, engine_monitor, log_buffer, log_revision, @@ -381,8 +384,7 @@ impl SteamFrameGpuiApp { .cursor_pointer() .on_click(cx.listener(|this, _, _, cx| { this.cfg.head_tracking_enabled = !this.cfg.head_tracking_enabled; - this.engine - .lock() + this.controls .set_head_tracking_enabled(this.cfg.head_tracking_enabled); cx.notify(); })) @@ -398,8 +400,7 @@ impl SteamFrameGpuiApp { .cursor_pointer() .on_click(cx.listener(|this, _, _, cx| { this.cfg.telemetry_enabled = !this.cfg.telemetry_enabled; - this.engine - .lock() + this.controls .set_telemetry_enabled(this.cfg.telemetry_enabled); cx.notify(); })) @@ -422,7 +423,7 @@ impl SteamFrameGpuiApp { .font_weight(gpui::FontWeight::SEMIBOLD) .cursor_pointer() .on_click(cx.listener(|this, _, _, cx| { - this.engine.lock().request_recenter(); + this.controls.request_recenter(); cx.notify(); })) .child("🎯 Tare"), @@ -754,12 +755,15 @@ impl SteamFrameGpuiApp { .font_weight(gpui::FontWeight::BOLD) .cursor_pointer() .on_click(cx.listener(|this, _, _, cx| { - log::info!("[Réglages] Application et redémarrage asynchrone du moteur FPV..."); let engine_clone = Arc::clone(&this.engine); let cfg_clone = this.cfg.clone(); std::thread::spawn(move || { - let mut eng = engine_clone.lock(); - eng.start(cfg_clone); + if let Some(mut eng) = engine_clone.try_lock() { + log::info!("[Réglages] Application et redémarrage asynchrone du moteur FPV..."); + eng.start(cfg_clone); + } else { + log::warn!("[Réglages] Redémarrage déjà en cours, requête ignorée."); + } }); cx.notify(); })) @@ -972,7 +976,7 @@ impl SteamFrameGpuiApp { .font_weight(gpui::FontWeight::SEMIBOLD) .cursor_pointer() .on_click(cx.listener(|this, _, _, cx| { - this.engine.lock().request_recenter(); + this.controls.request_recenter(); cx.notify(); })) .child("🎯 Réinitialiser Zéro (Tare)"), @@ -1060,7 +1064,7 @@ impl SteamFrameGpuiApp { self.cfg.telemetry_enabled, cx.listener(|this, _, _, cx| { this.cfg.telemetry_enabled = true; - this.engine.lock().set_telemetry_enabled(true); + this.controls.set_telemetry_enabled(true); cx.notify(); }), )) @@ -1070,7 +1074,7 @@ impl SteamFrameGpuiApp { !self.cfg.telemetry_enabled, cx.listener(|this, _, _, cx| { this.cfg.telemetry_enabled = false; - this.engine.lock().set_telemetry_enabled(false); + this.controls.set_telemetry_enabled(false); cx.notify(); }), )), @@ -1702,6 +1706,13 @@ impl SteamFrameGpuiApp { pub fn run_gpui_app(cfg: AppConfig, log_buffer: Arc>) -> Result<()> { Application::new().run(move |cx: &mut App| { + cx.on_window_closed(|cx| { + if cx.windows().is_empty() { + cx.quit(); + } + }) + .detach(); + let bounds = Bounds::centered(None, size(px(1240.0), px(820.0)), cx); let window_res = cx.open_window( diff --git a/src/video_usb.rs b/src/video_usb.rs index 70747fb..d3bd943 100644 --- a/src/video_usb.rs +++ b/src/video_usb.rs @@ -4,10 +4,21 @@ use gstreamer::prelude::*; use gstreamer_app as gst_app; use gstreamer_video as gst_video; use parking_lot::Mutex; -use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use std::sync::Arc; -use std::thread; -use std::time::Instant; +use std::thread::{self, JoinHandle}; +use std::time::{Duration, Instant}; + +/// Délai sans trame au-delà duquel le superviseur considère le signal comme perdu. +const SIGNAL_LOST_AFTER: Duration = Duration::from_secs(1); +/// Délai initial / maximal entre deux reconstructions complètes du pipeline après une erreur. +const REBUILD_BACKOFF_MIN: Duration = Duration::from_secs(1); +const REBUILD_BACKOFF_MAX: Duration = Duration::from_secs(30); +/// Délai initial / maximal entre deux réarmements doux (NULL -> PLAYING) en l'absence de signal. +const SOFT_RESTART_MIN: Duration = Duration::from_secs(5); +const SOFT_RESTART_MAX: Duration = Duration::from_secs(60); +/// Intervalle minimal entre deux logs d'avertissement GStreamer (anti-spam). +const WARN_LOG_INTERVAL: Duration = Duration::from_secs(5); #[derive(Clone)] #[allow(dead_code)] @@ -19,17 +30,53 @@ pub struct VideoFrame { pub received_at: Instant, } +/// État de la liaison vidéo tel qu'observé par le superviseur. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum VideoLinkState { + /// Pipeline actif, aucune trame reçue depuis le (re)démarrage. + Waiting, + /// Trames reçues en continu. + Live, + /// Des trames ont été reçues, puis plus rien depuis `SIGNAL_LOST_AFTER`. + Lost, + /// Construction ou exécution du pipeline en échec (nouvel essai programmé). + Error(String), +} + +/// Paramètres nécessaires pour (re)construire le pipeline GStreamer. +#[derive(Clone)] +struct PipelineParams { + usb_video_mode: String, + uvc_device: String, + bind_ip: String, + port: u16, + codec: String, + stream_transport: String, + target_width: u32, + target_height: u32, +} + +/// Récepteur vidéo USB (RNDIS/UDP ou UVC). +/// +/// Le cycle de vie du pipeline (surveillance du bus, détection de perte de signal, +/// réarmement et reconstruction avec délai croissant) est entièrement géré par un +/// thread superviseur dédié : la boucle de rendu se contente de lire `latest_frame` +/// et n'est jamais bloquée par GStreamer. pub struct UsbVideoReceiver { - pipeline: gst::Pipeline, latest_frame: Arc>>, + link_state: Arc>, stop_flag: Arc, - has_error: Arc, + supervisor: Option>, } impl UsbVideoReceiver { /// Démarre l'acquisition vidéo USB depuis le VRX Radxa Zero 3W (Sphere Link) : /// - Mode `"rndis"` : Réception du flux RTP H.265/H.264 via le port USB OTG (`usb0`, UDP :5600) /// - Mode `"uvc"` : Réception directe depuis la sortie Mini-HDMI du VRX via une carte d'acquisition USB-C UVC (`/dev/video0`) + /// + /// Seule l'initialisation de GStreamer peut échouer ici. Les échecs de construction + /// du pipeline (périphérique absent, port occupé...) sont réessayés en arrière-plan. + #[allow(clippy::too_many_arguments)] pub fn start( usb_video_mode: &str, uvc_device: &str, @@ -44,179 +91,36 @@ impl UsbVideoReceiver { "Impossible d'initialiser GStreamer (vérifiez l'installation de gst-plugins-base/good/bad)", )?; - let pipeline_str = if usb_video_mode.eq_ignore_ascii_case("uvc") { - log::info!( - "[USB Vidéo UVC] Acquisition depuis la sortie Mini-HDMI de la Radxa Zero 3W via {}", - uvc_device - ); - format!( - "v4l2src device={uvc_device} do-timestamp=true ! \ - decodebin ! \ - videoconvert ! videoscale ! \ - video/x-raw,format=RGBA,width={target_width},height={target_height} ! \ - appsink name=fpv_sink sync=false max-buffers=1 drop=true emit-signals=false" - ) - } else { - let codec_lower = codec.to_lowercase(); - let is_h264 = codec_lower == "h264"; - let parser = if is_h264 { "h264parse" } else { "h265parse" }; - let codec_name = if is_h264 { "H264" } else { "H265" }; - let depay = if is_h264 { "rtph264depay" } else { "rtph265depay" }; - let decoder = if is_h264 { - "avdec_h264 max-threads=1 discard-corrupted-frames=true" - } else { - "avdec_h265 max-threads=1 discard-corrupted-frames=true" - }; - - let depay_and_parse = if stream_transport.eq_ignore_ascii_case("rtp") { - format!( - "application/x-rtp,media=video,clock-rate=90000,encoding-name={codec_name},payload=96 ! \ - rtpjitterbuffer latency=0 drop-on-latency=true ! \ - {depay} ! {parser} config-interval=-1" - ) - } else { - format!("{parser} config-interval=-1") - }; - - log::info!( - "[USB Vidéo OTG/RNDIS] Écoute du flux {transport} ({codec_name} faible latence) sur {bind_ip}:{port}", - transport = if stream_transport.eq_ignore_ascii_case("rtp") { "RTP" } else { "Raw NAL direct" }, - ); - - format!( - "udpsrc address={bind_ip} port={port} buffer-size=4194304 retrieve-sender-address=false ! \ - {depay_and_parse} ! \ - {decoder} ! \ - videoscale ! videoconvert ! \ - video/x-raw,format=RGBA,width={target_width},height={target_height} ! \ - appsink name=fpv_sink sync=false max-buffers=1 drop=true emit-signals=false" - ) + let params = PipelineParams { + usb_video_mode: usb_video_mode.to_string(), + uvc_device: uvc_device.to_string(), + bind_ip: bind_ip.to_string(), + port, + codec: codec.to_string(), + stream_transport: stream_transport.to_string(), + target_width, + target_height, }; - let element = gst::parse::launch(&pipeline_str).map_err(|e| { - log::error!( - "[USB Vidéo] Échec de construction du pipeline GStreamer : {} (Pipeline: {})", - e, - pipeline_str - ); - anyhow::anyhow!("Erreur pipeline GStreamer : {}", e) - })?; - - let pipeline = element - .dynamic_cast::() - .map_err(|_| anyhow::anyhow!("L'élément GStreamer n'est pas un Pipeline"))?; - - let appsink = pipeline - .by_name("fpv_sink") - .context("Appsink 'fpv_sink' introuvable dans le pipeline")? - .dynamic_cast::() - .map_err(|_| anyhow::anyhow!("Impossible de convertir fpv_sink en AppSink"))?; - let latest_frame: Arc>> = Arc::new(Mutex::new(None)); - let frame_store = Arc::clone(&latest_frame); - let mut sequence: u64 = 0; - - appsink.set_callbacks( - gst_app::AppSinkCallbacks::builder() - .new_sample(move |sink| { - let sample = sink.pull_sample().map_err(|_| gst::FlowError::Eos)?; - let buffer = sample.buffer().ok_or(gst::FlowError::Error)?; - let caps = sample.caps().ok_or(gst::FlowError::Error)?; - let video_info = gst_video::VideoInfo::from_caps(caps) - .map_err(|_| gst::FlowError::Error)?; - - let map = buffer.map_readable().map_err(|_| gst::FlowError::Error)?; - sequence = sequence.wrapping_add(1); - - if sequence == 1 { - log::info!( - "[USB Vidéo] Première image reçue depuis le VRX Sphere Link ({}x{}) !", - video_info.width(), - video_info.height() - ); - } - - let mut lock = frame_store.lock(); - if let Some(ref mut vf) = *lock { - vf.width = video_info.width(); - vf.height = video_info.height(); - vf.frame_id = sequence; - vf.received_at = Instant::now(); - vf.rgba_data.clear(); - vf.rgba_data.extend_from_slice(map.as_slice()); - } else { - *lock = Some(VideoFrame { - width: video_info.width(), - height: video_info.height(), - rgba_data: map.as_slice().to_vec(), - frame_id: sequence, - received_at: Instant::now(), - }); - } - - Ok(gst::FlowSuccess::Ok) - }) - .build(), - ); - + let link_state = Arc::new(Mutex::new(VideoLinkState::Waiting)); let stop_flag = Arc::new(AtomicBool::new(false)); - let has_error = Arc::new(AtomicBool::new(false)); - let error_clone = Arc::clone(&has_error); - if let Some(bus) = pipeline.bus() { - let stop_bus = Arc::clone(&stop_flag); - let _ = thread::Builder::new() - .name("gst-bus-monitor".into()) - .spawn(move || { - while !stop_bus.load(Ordering::Relaxed) { - if let Some(msg) = bus.timed_pop(gst::ClockTime::from_mseconds(100)) { - use gst::MessageView; - match msg.view() { - MessageView::Error(err) => { - let src_name = err - .src() - .map(|s| s.path_string().to_string()) - .unwrap_or_else(|| "inconnu".into()); - log::error!( - "[GStreamer ERREUR] Source={} : {} (Détail debug: {:?})", - src_name, - err.error(), - err.debug() - ); - error_clone.store(true, Ordering::Release); - } - MessageView::Eos(..) => { - log::warn!("[GStreamer] Fin de flux vidéo (EOS) reçu."); - error_clone.store(true, Ordering::Release); - } - MessageView::Warning(warn) => { - log::warn!( - "[GStreamer WARN] {} (Détail: {:?})", - warn.error(), - warn.debug() - ); - } - _ => {} - } - } - } - }); - } - - if let Err(e) = pipeline.set_state(gst::State::Playing) { - log::error!( - "[USB Vidéo] Impossible de démarrer le pipeline GStreamer (mode={}) : {}", - usb_video_mode, - e - ); - anyhow::bail!("Échec démarrage GStreamer ({}) : {}", usb_video_mode, e); - } + let supervisor = { + let latest_frame = Arc::clone(&latest_frame); + let link_state = Arc::clone(&link_state); + let stop_flag = Arc::clone(&stop_flag); + thread::Builder::new() + .name("gst-video-supervisor".into()) + .spawn(move || supervisor_loop(params, latest_frame, link_state, stop_flag)) + .context("Impossible de créer le thread superviseur vidéo")? + }; Ok(Self { - pipeline, latest_frame, + link_state, stop_flag, - has_error, + supervisor: Some(supervisor), }) } @@ -224,28 +128,9 @@ impl UsbVideoReceiver { Arc::clone(&self.latest_frame) } - pub fn is_broken(&self) -> bool { - self.has_error.load(Ordering::Acquire) - } - - #[allow(dead_code)] - pub fn is_stream_live(&self, timeout: std::time::Duration) -> bool { - let lock = self.latest_frame.lock(); - if let Some(ref vf) = *lock { - vf.received_at.elapsed() < timeout - } else { - false - } - } - - pub fn restart(&mut self) -> Result<()> { - log::info!("[USB Vidéo] Réarmement du pipeline GStreamer (State: NULL -> PLAYING)..."); - let _ = self.pipeline.set_state(gst::State::Null); - std::thread::sleep(std::time::Duration::from_millis(60)); - self.latest_frame.lock().take(); - self.has_error.store(false, Ordering::Release); - self.pipeline.set_state(gst::State::Playing)?; - Ok(()) + /// État courant de la liaison vidéo (mis à jour par le superviseur). + pub fn link_state(&self) -> VideoLinkState { + self.link_state.lock().clone() } pub fn render_standby_pattern(width: u32, height: u32, tick: u32, data: &mut [u8]) { @@ -286,8 +171,373 @@ impl UsbVideoReceiver { impl Drop for UsbVideoReceiver { fn drop(&mut self) { - self.stop_flag.store(true, Ordering::Relaxed); - let _ = self.pipeline.set_state(gst::State::Null); + self.stop_flag.store(true, Ordering::Release); + if let Some(handle) = self.supervisor.take() { + let _ = handle.join(); + } log::info!("[USB Vidéo] Pipeline GStreamer arrêté proprement."); } } + +/// Construit la description textuelle du pipeline GStreamer selon le mode choisi. +fn pipeline_description(p: &PipelineParams) -> String { + let (w, h) = (p.target_width, p.target_height); + if p.usb_video_mode.eq_ignore_ascii_case("uvc") { + return format!( + "v4l2src device={dev} do-timestamp=true ! \ + decodebin ! \ + videoconvert ! videoscale ! \ + video/x-raw,format=RGBA,width={w},height={h} ! \ + appsink name=fpv_sink sync=false max-buffers=1 drop=true emit-signals=false", + dev = p.uvc_device + ); + } + + let is_h264 = p.codec.eq_ignore_ascii_case("h264"); + let parser = if is_h264 { "h264parse" } else { "h265parse" }; + let codec_name = if is_h264 { "H264" } else { "H265" }; + let depay = if is_h264 { "rtph264depay" } else { "rtph265depay" }; + let decoder = if is_h264 { + "avdec_h264 max-threads=1 discard-corrupted-frames=true" + } else { + "avdec_h265 max-threads=1 discard-corrupted-frames=true" + }; + + let depay_and_parse = if p.stream_transport.eq_ignore_ascii_case("rtp") { + format!( + "application/x-rtp,media=video,clock-rate=90000,encoding-name={codec_name},payload=96 ! \ + rtpjitterbuffer latency=0 drop-on-latency=true ! \ + {depay} ! {parser} config-interval=-1" + ) + } else { + format!("{parser} config-interval=-1") + }; + + format!( + "udpsrc address={ip} port={port} buffer-size=4194304 retrieve-sender-address=false ! \ + {depay_and_parse} ! \ + {decoder} ! \ + videoscale ! videoconvert ! \ + video/x-raw,format=RGBA,width={w},height={h} ! \ + appsink name=fpv_sink sync=false max-buffers=1 drop=true emit-signals=false", + ip = p.bind_ip, + port = p.port + ) +} + +/// Construit le pipeline, branche l'appsink sur `latest_frame` et le passe en PLAYING. +fn build_pipeline( + params: &PipelineParams, + latest_frame: &Arc>>, + sequence: &Arc, +) -> Result { + let pipeline_str = pipeline_description(params); + + let element = gst::parse::launch(&pipeline_str) + .map_err(|e| anyhow::anyhow!("Erreur pipeline GStreamer : {} (Pipeline: {})", e, pipeline_str))?; + + let pipeline = element + .dynamic_cast::() + .map_err(|_| anyhow::anyhow!("L'élément GStreamer n'est pas un Pipeline"))?; + + let appsink = pipeline + .by_name("fpv_sink") + .context("Appsink 'fpv_sink' introuvable dans le pipeline")? + .dynamic_cast::() + .map_err(|_| anyhow::anyhow!("Impossible de convertir fpv_sink en AppSink"))?; + + let frame_store = Arc::clone(latest_frame); + // Compteur partagé entre les reconstructions : les identifiants de trame restent + // strictement croissants, la boucle de rendu ne rate donc jamais une nouvelle trame. + let sequence = Arc::clone(sequence); + let mut first_frame = true; + + appsink.set_callbacks( + gst_app::AppSinkCallbacks::builder() + .new_sample(move |sink| { + let sample = sink.pull_sample().map_err(|_| gst::FlowError::Eos)?; + let buffer = sample.buffer().ok_or(gst::FlowError::Error)?; + let caps = sample.caps().ok_or(gst::FlowError::Error)?; + let video_info = + gst_video::VideoInfo::from_caps(caps).map_err(|_| gst::FlowError::Error)?; + let map = buffer.map_readable().map_err(|_| gst::FlowError::Error)?; + let frame_id = sequence.fetch_add(1, Ordering::Relaxed) + 1; + + if first_frame { + first_frame = false; + log::info!( + "[USB Vidéo] Première image reçue depuis le VRX Sphere Link ({}x{}) !", + video_info.width(), + video_info.height() + ); + } + + let mut lock = frame_store.lock(); + if let Some(ref mut vf) = *lock { + vf.width = video_info.width(); + vf.height = video_info.height(); + vf.frame_id = frame_id; + vf.received_at = Instant::now(); + vf.rgba_data.clear(); + vf.rgba_data.extend_from_slice(map.as_slice()); + } else { + *lock = Some(VideoFrame { + width: video_info.width(), + height: video_info.height(), + rgba_data: map.as_slice().to_vec(), + frame_id, + received_at: Instant::now(), + }); + } + + Ok(gst::FlowSuccess::Ok) + }) + .build(), + ); + + if let Err(e) = pipeline.set_state(gst::State::Playing) { + let _ = pipeline.set_state(gst::State::Null); + anyhow::bail!( + "Échec démarrage GStreamer ({}) : {}", + params.usb_video_mode, + e + ); + } + + Ok(pipeline) +} + +/// Boucle du thread superviseur : possède le pipeline, surveille le bus et la +/// fraîcheur des trames, et (re)démarre le pipeline avec un délai croissant. +fn supervisor_loop( + params: PipelineParams, + latest_frame: Arc>>, + link_state: Arc>, + stop_flag: Arc, +) { + let source_desc = if params.usb_video_mode.eq_ignore_ascii_case("uvc") { + format!("UVC {}", params.uvc_device) + } else { + format!( + "{} {} sur {}:{}", + if params.stream_transport.eq_ignore_ascii_case("rtp") { "RTP" } else { "Raw NAL" }, + params.codec.to_uppercase(), + params.bind_ip, + params.port + ) + }; + log::info!("[USB Vidéo] Superviseur démarré ({source_desc})."); + + let sequence = Arc::new(AtomicU64::new(0)); + let mut pipeline: Option = None; + + let mut rebuild_backoff = REBUILD_BACKOFF_MIN; + let mut next_build_at = Instant::now(); + let mut last_build_error: Option = None; + + let mut soft_restart_backoff = SOFT_RESTART_MIN; + let mut last_soft_restart = Instant::now(); + + let mut was_live = false; + let mut last_warn_log: Option = None; + let mut suppressed_warnings: u32 = 0; + + let set_state = |s: VideoLinkState| { + let mut st = link_state.lock(); + if *st != s { + *st = s; + } + }; + + while !stop_flag.load(Ordering::Acquire) { + // 1. (Re)construction du pipeline si nécessaire + if pipeline.is_none() { + if Instant::now() < next_build_at { + thread::sleep(Duration::from_millis(100)); + continue; + } + match build_pipeline(¶ms, &latest_frame, &sequence) { + Ok(p) => { + if last_build_error.take().is_some() { + log::info!("[USB Vidéo] Pipeline reconstruit avec succès ({source_desc})."); + } + pipeline = Some(p); + last_soft_restart = Instant::now(); + if !was_live { + set_state(VideoLinkState::Waiting); + } + } + Err(e) => { + let msg = e.to_string(); + // Ne logger que si l'erreur change, pour éviter de remplir le journal + if last_build_error.as_deref() != Some(msg.as_str()) { + log::error!( + "[USB Vidéo] {} — nouvel essai dans {:?} (délai max {:?})", + msg, + rebuild_backoff, + REBUILD_BACKOFF_MAX + ); + } + set_state(VideoLinkState::Error(msg.clone())); + last_build_error = Some(msg); + next_build_at = Instant::now() + rebuild_backoff; + rebuild_backoff = (rebuild_backoff * 2).min(REBUILD_BACKOFF_MAX); + continue; + } + } + } + + let Some(p) = pipeline.as_ref() else { continue }; + let mut needs_rebuild = false; + + // 2. Messages du bus GStreamer (bloquant au plus 100 ms : cadence la boucle) + if let Some(bus) = p.bus() { + if let Some(msg) = bus.timed_pop(gst::ClockTime::from_mseconds(100)) { + use gst::MessageView; + match msg.view() { + MessageView::Error(err) => { + let src_name = err + .src() + .map(|s| s.path_string().to_string()) + .unwrap_or_else(|| "inconnu".into()); + log::error!( + "[GStreamer ERREUR] Source={} : {} (Détail debug: {:?})", + src_name, + err.error(), + err.debug() + ); + set_state(VideoLinkState::Error(err.error().to_string())); + needs_rebuild = true; + } + MessageView::Eos(..) => { + log::warn!("[GStreamer] Fin de flux vidéo (EOS) reçue."); + needs_rebuild = true; + } + MessageView::Warning(warn) => { + // Anti-spam : au plus un avertissement toutes les WARN_LOG_INTERVAL + let due = last_warn_log.map_or(true, |t| t.elapsed() >= WARN_LOG_INTERVAL); + if due { + if suppressed_warnings > 0 { + log::warn!( + "[GStreamer WARN] {} (Détail: {:?}) [+{} avertissements similaires masqués]", + warn.error(), + warn.debug(), + suppressed_warnings + ); + } else { + log::warn!( + "[GStreamer WARN] {} (Détail: {:?})", + warn.error(), + warn.debug() + ); + } + last_warn_log = Some(Instant::now()); + suppressed_warnings = 0; + } else { + suppressed_warnings += 1; + } + } + _ => {} + } + } + } else { + thread::sleep(Duration::from_millis(100)); + } + + // 3. Fraîcheur des trames : transitions Live <-> Lost (un seul log par transition) + let live = latest_frame + .lock() + .as_ref() + .is_some_and(|f| f.received_at.elapsed() < SIGNAL_LOST_AFTER); + + if live && !was_live { + log::info!("[USB Vidéo] Signal vidéo actif ({source_desc})."); + set_state(VideoLinkState::Live); + rebuild_backoff = REBUILD_BACKOFF_MIN; + soft_restart_backoff = SOFT_RESTART_MIN; + } else if !live && was_live { + log::warn!( + "[USB Vidéo] Signal vidéo perdu (aucune trame depuis {:?}). Réarmement automatique en arrière-plan.", + SIGNAL_LOST_AFTER + ); + set_state(VideoLinkState::Lost); + last_soft_restart = Instant::now(); + } + was_live = live; + + // 4. Réarmement doux en l'absence de signal (purge décodeur / socket), délai croissant. + // Log en debug uniquement : n'encombre pas le journal quand le drone est éteint. + if !live && !needs_rebuild && last_soft_restart.elapsed() >= soft_restart_backoff { + log::debug!( + "[USB Vidéo] Réarmement doux du pipeline (prochain dans {:?}).", + (soft_restart_backoff * 2).min(SOFT_RESTART_MAX) + ); + let _ = p.set_state(gst::State::Null); + if p.set_state(gst::State::Playing).is_err() { + needs_rebuild = true; + } + last_soft_restart = Instant::now(); + soft_restart_backoff = (soft_restart_backoff * 2).min(SOFT_RESTART_MAX); + } + + // 5. Reconstruction complète après erreur / EOS, avec délai croissant + if needs_rebuild { + if let Some(p) = pipeline.take() { + let _ = p.set_state(gst::State::Null); + } + log::warn!( + "[USB Vidéo] Reconstruction du pipeline dans {:?}.", + rebuild_backoff + ); + next_build_at = Instant::now() + rebuild_backoff; + rebuild_backoff = (rebuild_backoff * 2).min(REBUILD_BACKOFF_MAX); + } + } + + if let Some(p) = pipeline.take() { + let _ = p.set_state(gst::State::Null); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn params(mode: &str, codec: &str, transport: &str) -> PipelineParams { + PipelineParams { + usb_video_mode: mode.into(), + uvc_device: "/dev/video0".into(), + bind_ip: "0.0.0.0".into(), + port: 5600, + codec: codec.into(), + stream_transport: transport.into(), + target_width: 1280, + target_height: 720, + } + } + + #[test] + fn test_pipeline_description_raw_h264() { + let d = pipeline_description(¶ms("rndis", "h264", "raw")); + assert!(d.starts_with("udpsrc address=0.0.0.0 port=5600")); + assert!(d.contains("h264parse")); + assert!(d.contains("avdec_h264")); + assert!(!d.contains("rtph264depay")); + assert!(d.contains("width=1280,height=720")); + } + + #[test] + fn test_pipeline_description_rtp_h265() { + let d = pipeline_description(¶ms("rndis", "H265", "rtp")); + assert!(d.contains("encoding-name=H265")); + assert!(d.contains("rtph265depay ! h265parse")); + assert!(d.contains("avdec_h265")); + } + + #[test] + fn test_pipeline_description_uvc() { + let d = pipeline_description(¶ms("UVC", "h264", "raw")); + assert!(d.starts_with("v4l2src device=/dev/video0")); + assert!(!d.contains("udpsrc")); + } +}