mirror of
https://github.com/bleackstorm/SteamFrame-FPV-Control-Center.git
synced 2026-12-03 07:31:57 +01:00
feat: initial commit of SteamFrame FPV Control Center
This commit is contained in:
commit
4459f5ffa4
18 files changed
+8571
No files matched your search
@@ -0,0 +1,246 @@
|
||||
use anyhow::{Context, Result};
|
||||
use gstreamer as gst;
|
||||
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::Arc;
|
||||
use std::thread;
|
||||
use std::time::Instant;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct VideoFrame {
|
||||
pub width: u32,
|
||||
pub height: u32,
|
||||
pub rgba_data: Vec<u8>,
|
||||
pub frame_id: u64,
|
||||
pub received_at: Instant,
|
||||
}
|
||||
|
||||
pub struct UsbVideoReceiver {
|
||||
pipeline: gst::Pipeline,
|
||||
latest_frame: Arc<Mutex<Option<VideoFrame>>>,
|
||||
stop_flag: Arc<AtomicBool>,
|
||||
}
|
||||
|
||||
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`)
|
||||
pub fn start(
|
||||
usb_video_mode: &str,
|
||||
uvc_device: &str,
|
||||
bind_ip: &str,
|
||||
port: u16,
|
||||
codec: &str,
|
||||
stream_transport: &str,
|
||||
target_width: u32,
|
||||
target_height: u32,
|
||||
) -> Result<Self> {
|
||||
gst::init().context(
|
||||
"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=true"
|
||||
)
|
||||
} 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 ! \
|
||||
{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=524288 retrieve-sender-address=false ! \
|
||||
{depay_and_parse} ! \
|
||||
{decoder} ! \
|
||||
videoconvert n-threads=2 ! videoscale method=1 ! \
|
||||
video/x-raw,format=RGBA,width={target_width},height={target_height} ! \
|
||||
appsink name=fpv_sink sync=false max-buffers=1 drop=true emit-signals=true"
|
||||
)
|
||||
};
|
||||
|
||||
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::<gst::Pipeline>()
|
||||
.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::<gst_app::AppSink>()
|
||||
.map_err(|_| anyhow::anyhow!("Impossible de convertir fpv_sink en AppSink"))?;
|
||||
|
||||
let latest_frame: Arc<Mutex<Option<VideoFrame>>> = 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();
|
||||
*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 stop_flag = Arc::new(AtomicBool::new(false));
|
||||
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()
|
||||
);
|
||||
}
|
||||
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);
|
||||
}
|
||||
|
||||
Ok(Self {
|
||||
pipeline,
|
||||
latest_frame,
|
||||
stop_flag,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn latest_frame(&self) -> Arc<Mutex<Option<VideoFrame>>> {
|
||||
Arc::clone(&self.latest_frame)
|
||||
}
|
||||
|
||||
pub fn generate_standby_pattern(width: u32, height: u32, tick: u32) -> Vec<u8> {
|
||||
let mut data = vec![0u8; (width * height * 4) as usize];
|
||||
let cx = (width / 2) as i32;
|
||||
let cy = (height / 2) as i32;
|
||||
let pulse = ((tick % 120) as f32 / 120.0 * std::f32::consts::TAU).sin() * 0.5 + 0.5;
|
||||
let accent = (80.0 + pulse * 140.0) as u8;
|
||||
|
||||
for y in 0..height as i32 {
|
||||
for x in 0..width as i32 {
|
||||
let idx = ((y as u32 * width + x as u32) * 4) as usize;
|
||||
let dx = (x - cx).abs();
|
||||
let dy = (y - cy).abs();
|
||||
|
||||
let dist_sq = (x - cx) * (x - cx) + (y - cy) * (y - cy);
|
||||
let on_crosshair = (dx < 2 && dy < 40) || (dy < 2 && dx < 60);
|
||||
let on_ring = (dist_sq - 120 * 120).abs() < 350;
|
||||
|
||||
if on_crosshair || on_ring {
|
||||
data[idx] = 0;
|
||||
data[idx + 1] = accent;
|
||||
data[idx + 2] = 255;
|
||||
data[idx + 3] = 255;
|
||||
} else {
|
||||
data[idx] = 14;
|
||||
data[idx + 1] = 18;
|
||||
data[idx + 2] = 26;
|
||||
data[idx + 3] = 255;
|
||||
}
|
||||
}
|
||||
}
|
||||
data
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for UsbVideoReceiver {
|
||||
fn drop(&mut self) {
|
||||
self.stop_flag.store(true, Ordering::Relaxed);
|
||||
let _ = self.pipeline.set_state(gst::State::Null);
|
||||
log::info!("[USB Vidéo] Pipeline GStreamer arrêté proprement.");
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user