mirror of
https://github.com/bleackstorm/SteamFrame-FPV-Control-Center.git
synced 2026-12-03 07:31:57 +01:00
feat: integrate DVR, live optical tuning and ARM64 tooling into modern GPUI Control Center
- Modern GPUI (src/gui_gpui.rs): Added 1-click DVR quick action button in header with live recording time/size, DVR status badge, reactive snapshots, live optical parameter tuning in Settings, and dedicated DVR settings card (MKV/MP4, StreamCopy/Composited). - Engine & DVR (src/engine.rs, src/dvr.rs, src/video_usb.rs): Integrated DVR recorder lifecycle with GStreamer supervisor probe for zero-CPU stream copy and hardware/composited OSD recording, dynamic optical updates without pipeline restarts. - Classic GUI fallback (src/gui.rs): Added DVR quick toggle, live optical slider callbacks, and full DVR settings section in egui. - OSD & Math optimizations: Zero-alloc stack formatting in src/telemetry_osd.rs, compile-time CRC8 table in src/nomad_elrs.rs, buffered file logger in src/logger.rs. - Steam Frame ARM64 scripts: udev rule scripts/99-radxa-vrx-rndis.rules, build & deployment tools scripts/build_steamframe_arm64.sh, scripts/deploy_to_steamframe.sh.
This commit is contained in:
1 parent
d5cc72750e
commit
7bee072e21
16 files changed
+1397
-75
No files matched your search
+333
@@ -0,0 +1,333 @@
|
||||
use anyhow::{Context, Result};
|
||||
use chrono::Local;
|
||||
use gstreamer as gst;
|
||||
use gstreamer::prelude::*;
|
||||
use gstreamer_app as gst_app;
|
||||
use std::fs;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
|
||||
use std::sync::Arc;
|
||||
use std::time::Instant;
|
||||
|
||||
/// Format de conteneur d'enregistrement DVR
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum DvrContainer {
|
||||
Mkv,
|
||||
Mp4,
|
||||
}
|
||||
|
||||
impl DvrContainer {
|
||||
pub fn from_str(s: &str) -> Self {
|
||||
if s.eq_ignore_ascii_case("mp4") {
|
||||
Self::Mp4
|
||||
} else {
|
||||
Self::Mkv
|
||||
}
|
||||
}
|
||||
|
||||
pub fn extension(&self) -> &'static str {
|
||||
match self {
|
||||
Self::Mkv => "mkv",
|
||||
Self::Mp4 => "mp4",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn muxer_element(&self) -> &'static str {
|
||||
match self {
|
||||
Self::Mkv => "matroskamux",
|
||||
Self::Mp4 => "mp4mux fragment-duration=2000 faststart=true",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Mode d'enregistrement DVR
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum DvrMode {
|
||||
/// Copie directe du flux compressé H.264/H.265 (Zéro-CPU, qualité 1:1 d'origine)
|
||||
StreamCopy,
|
||||
/// Enregistrement de la trame compositée (avec OSD et correction optique)
|
||||
CompositedOsd,
|
||||
}
|
||||
|
||||
impl DvrMode {
|
||||
pub fn from_str(s: &str) -> Self {
|
||||
if s.eq_ignore_ascii_case("osd") {
|
||||
Self::CompositedOsd
|
||||
} else {
|
||||
Self::StreamCopy
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub fn label(&self) -> &'static str {
|
||||
match self {
|
||||
Self::StreamCopy => "Flux Natif (Zéro-CPU)",
|
||||
Self::CompositedOsd => "Avec OSD incrusté",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Enregistreur vidéo DVR asynchrone basé sur GStreamer
|
||||
pub struct DvrRecorder {
|
||||
pipeline: gst::Pipeline,
|
||||
appsrc: gst_app::AppSrc,
|
||||
file_path: PathBuf,
|
||||
mode: DvrMode,
|
||||
start_time: Instant,
|
||||
bytes_written: Arc<AtomicU64>,
|
||||
frames_recorded: Arc<AtomicU64>,
|
||||
is_recording: Arc<AtomicBool>,
|
||||
}
|
||||
|
||||
impl DvrRecorder {
|
||||
/// Démarre un enregistrement en mode copie de flux direct H.264 / H.265 (Zéro-CPU)
|
||||
pub fn start_stream_copy(
|
||||
dir: &str,
|
||||
container: DvrContainer,
|
||||
codec: &str,
|
||||
) -> Result<Arc<Self>> {
|
||||
gst::init().context("Échec d'initialisation GStreamer pour le DVR")?;
|
||||
|
||||
fs::create_dir_all(dir)
|
||||
.with_context(|| format!("Impossible de créer le répertoire DVR '{}'", dir))?;
|
||||
|
||||
let file_path = Self::generate_filepath(dir, container);
|
||||
let path_str = file_path
|
||||
.to_str()
|
||||
.ok_or_else(|| anyhow::anyhow!("Chemin DVR invalide"))?;
|
||||
|
||||
let codec_lower = codec.to_lowercase();
|
||||
let is_h264 = codec_lower == "h264";
|
||||
let parser = if is_h264 { "h264parse" } else { "h265parse" };
|
||||
let caps = if is_h264 {
|
||||
"video/x-h264,stream-format=byte-stream"
|
||||
} else {
|
||||
"video/x-h265,stream-format=byte-stream"
|
||||
};
|
||||
let muxer = container.muxer_element();
|
||||
|
||||
let pipeline_str = format!(
|
||||
"appsrc name=dvr_src is-live=true format=time do-timestamp=true caps={caps} ! \
|
||||
{parser} config-interval=-1 ! \
|
||||
{muxer} ! \
|
||||
filesink location=\"{path_str}\" sync=false"
|
||||
);
|
||||
|
||||
log::info!(
|
||||
"[DVR] Démarrage enregistrement StreamCopy ({}) -> {:?}",
|
||||
codec.to_uppercase(),
|
||||
file_path
|
||||
);
|
||||
|
||||
Self::launch(pipeline_str, file_path, DvrMode::StreamCopy)
|
||||
}
|
||||
|
||||
/// Démarre un enregistrement en mode incrustation OSD (re-encodage rapide x264enc)
|
||||
pub fn start_composited_osd(
|
||||
dir: &str,
|
||||
container: DvrContainer,
|
||||
width: u32,
|
||||
height: u32,
|
||||
) -> Result<Arc<Self>> {
|
||||
gst::init().context("Échec d'initialisation GStreamer pour le DVR")?;
|
||||
|
||||
fs::create_dir_all(dir)
|
||||
.with_context(|| format!("Impossible de créer le répertoire DVR '{}'", dir))?;
|
||||
|
||||
let file_path = Self::generate_filepath(dir, container);
|
||||
let path_str = file_path
|
||||
.to_str()
|
||||
.ok_or_else(|| anyhow::anyhow!("Chemin DVR invalide"))?;
|
||||
|
||||
let muxer = container.muxer_element();
|
||||
|
||||
let pipeline_str = format!(
|
||||
"appsrc name=dvr_src is-live=true format=time do-timestamp=true \
|
||||
caps=video/x-raw,format=RGBA,width={width},height={height},framerate=60/1 ! \
|
||||
videoconvert ! \
|
||||
x264enc tune=zerolatency speed-preset=ultrafast bitrate=8000 key-int-max=60 ! \
|
||||
h264parse config-interval=-1 ! \
|
||||
{muxer} ! \
|
||||
filesink location=\"{path_str}\" sync=false"
|
||||
);
|
||||
|
||||
log::info!(
|
||||
"[DVR] Démarrage enregistrement OSD ({width}x{height} @ 60 FPS) -> {:?}",
|
||||
file_path
|
||||
);
|
||||
|
||||
Self::launch(pipeline_str, file_path, DvrMode::CompositedOsd)
|
||||
}
|
||||
|
||||
fn launch(pipeline_str: String, file_path: PathBuf, mode: DvrMode) -> Result<Arc<Self>> {
|
||||
let element = gst::parse::launch(&pipeline_str).map_err(|e| {
|
||||
log::error!("[DVR] Erreur pipeline GStreamer : {} (Cmd: {})", e, pipeline_str);
|
||||
anyhow::anyhow!("Erreur pipeline DVR : {}", e)
|
||||
})?;
|
||||
|
||||
let pipeline = element
|
||||
.dynamic_cast::<gst::Pipeline>()
|
||||
.map_err(|_| anyhow::anyhow!("L'élément DVR n'est pas un Pipeline"))?;
|
||||
|
||||
let appsrc = pipeline
|
||||
.by_name("dvr_src")
|
||||
.context("Appsrc 'dvr_src' introuvable dans le pipeline DVR")?
|
||||
.dynamic_cast::<gst_app::AppSrc>()
|
||||
.map_err(|_| anyhow::anyhow!("Impossible de convertir dvr_src en AppSrc"))?;
|
||||
|
||||
pipeline
|
||||
.set_state(gst::State::Playing)
|
||||
.map_err(|e| anyhow::anyhow!("Impossible de démarrer le pipeline DVR : {}", e))?;
|
||||
|
||||
Ok(Arc::new(Self {
|
||||
pipeline,
|
||||
appsrc,
|
||||
file_path,
|
||||
mode,
|
||||
start_time: Instant::now(),
|
||||
bytes_written: Arc::new(AtomicU64::new(0)),
|
||||
frames_recorded: Arc::new(AtomicU64::new(0)),
|
||||
is_recording: Arc::new(AtomicBool::new(true)),
|
||||
}))
|
||||
}
|
||||
|
||||
/// Génère un nom de fichier horodaté `fpv_YYYYMMDD_HHMMSS.<ext>`
|
||||
pub fn generate_filepath(dir: &str, container: DvrContainer) -> PathBuf {
|
||||
let now = Local::now();
|
||||
let filename = format!(
|
||||
"fpv_{}.{}",
|
||||
now.format("%Y%m%d_%H%M%S"),
|
||||
container.extension()
|
||||
);
|
||||
Path::new(dir).join(filename)
|
||||
}
|
||||
|
||||
pub fn mode(&self) -> DvrMode {
|
||||
self.mode
|
||||
}
|
||||
|
||||
pub fn file_path(&self) -> &Path {
|
||||
&self.file_path
|
||||
}
|
||||
|
||||
pub fn elapsed_secs(&self) -> u64 {
|
||||
self.start_time.elapsed().as_secs()
|
||||
}
|
||||
|
||||
pub fn bytes_written(&self) -> u64 {
|
||||
self.bytes_written.load(Ordering::Relaxed)
|
||||
}
|
||||
|
||||
pub fn frames_recorded(&self) -> u64 {
|
||||
self.frames_recorded.load(Ordering::Relaxed)
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub fn is_recording(&self) -> bool {
|
||||
self.is_recording.load(Ordering::Relaxed)
|
||||
}
|
||||
|
||||
/// Pousse un buffer GStreamer existant (zéro-copie de pointeur GstBuffer)
|
||||
pub fn push_buffer(&self, buffer: gst::Buffer) {
|
||||
if !self.is_recording.load(Ordering::Relaxed) {
|
||||
return;
|
||||
}
|
||||
self.bytes_written
|
||||
.fetch_add(buffer.size() as u64, Ordering::Relaxed);
|
||||
self.frames_recorded.fetch_add(1, Ordering::Relaxed);
|
||||
let _ = self.appsrc.push_buffer(buffer);
|
||||
}
|
||||
|
||||
/// Pousse un bloc d'octets mémoire (ex: trame RGBA compositée)
|
||||
pub fn push_slice(&self, slice: &[u8]) {
|
||||
if !self.is_recording.load(Ordering::Relaxed) {
|
||||
return;
|
||||
}
|
||||
let buffer = gst::Buffer::from_slice(slice.to_vec());
|
||||
self.push_buffer(buffer);
|
||||
}
|
||||
|
||||
/// Arrête proprement l'enregistrement en envoyant un signal EOS pour finaliser les en-têtes
|
||||
pub fn stop(&self) {
|
||||
if !self.is_recording.swap(false, Ordering::SeqCst) {
|
||||
return;
|
||||
}
|
||||
|
||||
log::info!(
|
||||
"[DVR] Finalisation de l'enregistrement {:?}...",
|
||||
self.file_path
|
||||
);
|
||||
|
||||
let _ = self.appsrc.end_of_stream();
|
||||
|
||||
if let Some(bus) = self.pipeline.bus() {
|
||||
let deadline = Instant::now() + std::time::Duration::from_millis(1500);
|
||||
while Instant::now() < deadline {
|
||||
if let Some(msg) = bus.timed_pop(gst::ClockTime::from_mseconds(100)) {
|
||||
use gst::MessageView;
|
||||
match msg.view() {
|
||||
MessageView::Eos(..) => {
|
||||
log::info!("[DVR] En-têtes finalisés (EOS reçu).");
|
||||
break;
|
||||
}
|
||||
MessageView::Error(err) => {
|
||||
log::error!(
|
||||
"[DVR] Erreur GStreamer pendant la finalisation : {}",
|
||||
err.error()
|
||||
);
|
||||
break;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let _ = self.pipeline.set_state(gst::State::Null);
|
||||
log::info!(
|
||||
"[DVR] Fichier sauvegardé : {:?} ({} trames, {:.2} Mo)",
|
||||
self.file_path,
|
||||
self.frames_recorded.load(Ordering::Relaxed),
|
||||
self.bytes_written.load(Ordering::Relaxed) as f64 / (1024.0 * 1024.0)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for DvrRecorder {
|
||||
fn drop(&mut self) {
|
||||
self.stop();
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_dvr_filename_generation() {
|
||||
let path = DvrRecorder::generate_filepath("/tmp/test_dvr", DvrContainer::Mkv);
|
||||
assert!(path.to_str().unwrap().starts_with("/tmp/test_dvr/fpv_"));
|
||||
assert!(path.to_str().unwrap().ends_with(".mkv"));
|
||||
|
||||
let path_mp4 = DvrRecorder::generate_filepath("/tmp/test_dvr", DvrContainer::Mp4);
|
||||
assert!(path_mp4.to_str().unwrap().ends_with(".mp4"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_dvr_recording_mkv_and_stop() {
|
||||
let dir = "/tmp/test_dvr_run";
|
||||
let dvr = DvrRecorder::start_composited_osd(dir, DvrContainer::Mkv, 320, 240)
|
||||
.expect("start dvr failed");
|
||||
let fake_rgba = vec![0u8; 320 * 240 * 4];
|
||||
for _ in 0..10 {
|
||||
dvr.push_slice(&fake_rgba);
|
||||
std::thread::sleep(std::time::Duration::from_millis(10));
|
||||
}
|
||||
let path = dvr.file_path().to_path_buf();
|
||||
dvr.stop();
|
||||
assert!(path.exists());
|
||||
let meta = std::fs::metadata(&path).expect("file metadata");
|
||||
assert!(meta.len() > 0);
|
||||
let _ = std::fs::remove_file(&path);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user