mirror of
https://github.com/bleackstorm/SteamFrame-FPV-Control-Center.git
synced 2026-12-03 07:31:57 +01:00
922 lines
32 KiB
Rust
922 lines
32 KiB
Rust
use anyhow::{anyhow, Context, Result};
|
|
use chrono::Local;
|
|
use gstreamer as gst;
|
|
use gstreamer::prelude::*;
|
|
use gstreamer_app as gst_app;
|
|
use parking_lot::Mutex;
|
|
use std::collections::VecDeque;
|
|
use std::fs::{self, File};
|
|
use std::io::{BufWriter, Write};
|
|
use std::path::{Path, PathBuf};
|
|
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
|
|
use std::sync::Arc;
|
|
use std::time::{Duration, Instant};
|
|
|
|
/// Plafond mémoire de la file `appsrc` DVR (32 Mo) pour empêcher tout OOM si le stockage ralentit.
|
|
const DVR_MAX_QUEUE_BYTES: u64 = 32 * 1024 * 1024;
|
|
/// Fenêtre du pré-buffer Instant Replay (30 s) et plafond RAM (48 Mo).
|
|
pub const REPLAY_WINDOW_SECS: u64 = 30;
|
|
const REPLAY_MAX_BYTES: usize = 48 * 1024 * 1024;
|
|
|
|
#[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",
|
|
// fMP4 (fragment-duration=2000) est déjà résistant aux coupures sans réécriture `faststart` à l'EOS
|
|
Self::Mp4 => "mp4mux fragment-duration=2000",
|
|
}
|
|
}
|
|
}
|
|
|
|
/// 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") || s.eq_ignore_ascii_case("composited") {
|
|
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é",
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Formate un décalage en millisecondes au format SubRip (`HH:MM:SS,mmm`).
|
|
pub fn format_srt_timestamp(ms: u64) -> String {
|
|
let hours = ms / 3_600_000;
|
|
let mins = (ms % 3_600_000) / 60_000;
|
|
let secs = (ms % 60_000) / 1_000;
|
|
let millis = ms % 1_000;
|
|
format!("{hours:02}:{mins:02}:{secs:02},{millis:03}")
|
|
}
|
|
|
|
/// Écrivain de sous-titres télémétrie `.srt` synchronisés avec le fichier DVR (0 % coût encodage vidéo).
|
|
struct SrtWriterState {
|
|
writer: Option<BufWriter<File>>,
|
|
path: PathBuf,
|
|
seq: u32,
|
|
last_emit_ms: Option<u64>,
|
|
pending_text: Option<(u64, String)>,
|
|
}
|
|
|
|
impl SrtWriterState {
|
|
fn open_for_video(video_path: &Path) -> Self {
|
|
let srt_path = video_path.with_extension("srt");
|
|
let writer = File::create(&srt_path).ok().map(BufWriter::new);
|
|
Self {
|
|
writer,
|
|
path: srt_path,
|
|
seq: 0,
|
|
last_emit_ms: None,
|
|
pending_text: None,
|
|
}
|
|
}
|
|
|
|
fn push_caption(&mut self, elapsed_ms: u64, text: &str) {
|
|
if let Some(last) = self.last_emit_ms {
|
|
if elapsed_ms.saturating_sub(last) < 950 {
|
|
return;
|
|
}
|
|
}
|
|
self.last_emit_ms = Some(elapsed_ms);
|
|
|
|
// Fermer le bloc précédent jusqu'à `elapsed_ms`
|
|
if let Some((prev_start, prev_text)) = self.pending_text.take() {
|
|
let end_ms = elapsed_ms.max(prev_start + 500);
|
|
self.write_block(prev_start, end_ms, &prev_text);
|
|
}
|
|
self.pending_text = Some((elapsed_ms, text.to_string()));
|
|
}
|
|
|
|
fn write_block(&mut self, start_ms: u64, end_ms: u64, text: &str) {
|
|
let Some(ref mut w) = self.writer else {
|
|
return;
|
|
};
|
|
self.seq = self.seq.saturating_add(1);
|
|
let _ = writeln!(
|
|
w,
|
|
"{}\n{} --> {}\n{}\n",
|
|
self.seq,
|
|
format_srt_timestamp(start_ms),
|
|
format_srt_timestamp(end_ms),
|
|
text.trim()
|
|
);
|
|
}
|
|
|
|
fn finish(&mut self, end_ms: u64) {
|
|
if let Some((prev_start, prev_text)) = self.pending_text.take() {
|
|
let final_end = end_ms.max(prev_start + 1000);
|
|
self.write_block(prev_start, final_end, &prev_text);
|
|
}
|
|
if let Some(ref mut w) = self.writer {
|
|
let _ = w.flush();
|
|
}
|
|
self.writer = None;
|
|
// Supprimer le .srt si aucune télémétrie n'a été écrite
|
|
if self.seq == 0 {
|
|
let _ = fs::remove_file(&self.path);
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Écrivain de trace GPS `.gpx` 1.1 compagnon du fichier DVR (throttlé ~1 Hz, supprimé si 0 point GPS).
|
|
struct GpxWriterState {
|
|
writer: Option<BufWriter<File>>,
|
|
path: PathBuf,
|
|
points: u32,
|
|
last_emit: Option<Instant>,
|
|
}
|
|
|
|
impl GpxWriterState {
|
|
fn open_for_video(video_path: &Path) -> Self {
|
|
let gpx_path = video_path.with_extension("gpx");
|
|
let mut writer = File::create(&gpx_path).ok().map(BufWriter::new);
|
|
if let Some(ref mut w) = writer {
|
|
let name = video_path
|
|
.file_stem()
|
|
.and_then(|s| s.to_str())
|
|
.unwrap_or("steamframe_fpv");
|
|
let _ = writeln!(
|
|
w,
|
|
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n\
|
|
<gpx version=\"1.1\" creator=\"steamframe-fpv\" xmlns=\"http://www.topografix.com/GPX/1/1\">\n\
|
|
<trk>\n\
|
|
<name>{}</name>\n\
|
|
<trkseg>",
|
|
name
|
|
);
|
|
}
|
|
Self {
|
|
writer,
|
|
path: gpx_path,
|
|
points: 0,
|
|
last_emit: None,
|
|
}
|
|
}
|
|
|
|
fn push_point(&mut self, lat_deg: f64, lon_deg: f64, alt_m: f32) {
|
|
if !lat_deg.is_finite() || !lon_deg.is_finite() || (lat_deg.abs() < 1e-4 && lon_deg.abs() < 1e-4) {
|
|
return;
|
|
}
|
|
if let Some(last) = self.last_emit {
|
|
if last.elapsed() < Duration::from_millis(950) {
|
|
return;
|
|
}
|
|
}
|
|
self.last_emit = Some(Instant::now());
|
|
if let Some(ref mut w) = self.writer {
|
|
let iso_utc = chrono::Utc::now().format("%Y-%m-%dT%H:%M:%SZ");
|
|
let ele = if alt_m.is_finite() { alt_m } else { 0.0 };
|
|
if writeln!(
|
|
w,
|
|
" <trkpt lat=\"{:.7}\" lon=\"{:.7}\"><ele>{:.1}</ele><time>{}</time></trkpt>",
|
|
lat_deg, lon_deg, ele, iso_utc
|
|
)
|
|
.is_ok()
|
|
{
|
|
self.points = self.points.saturating_add(1);
|
|
}
|
|
}
|
|
}
|
|
|
|
fn finish(&mut self) {
|
|
if let Some(ref mut w) = self.writer {
|
|
let _ = writeln!(w, " </trkseg>\n </trk>\n</gpx>");
|
|
let _ = w.flush();
|
|
}
|
|
self.writer = None;
|
|
if self.points == 0 {
|
|
let _ = fs::remove_file(&self.path);
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Détecte si un paquet bitstream H.264 ou H.265 contient une image clé (IDR / SPS / IRAP / VPS).
|
|
pub fn detect_keyframe(bytes: &[u8], codec: &str, gst_is_delta: bool) -> bool {
|
|
if !gst_is_delta {
|
|
return true;
|
|
}
|
|
let is_h265 = codec.eq_ignore_ascii_case("h265") || codec.eq_ignore_ascii_case("hevc");
|
|
let mut i = 0usize;
|
|
while i + 4 < bytes.len() {
|
|
let sc_len = if bytes[i] == 0 && bytes[i + 1] == 0 && bytes[i + 2] == 1 {
|
|
3
|
|
} else if bytes[i] == 0 && bytes[i + 1] == 0 && bytes[i + 2] == 0 && bytes[i + 3] == 1 {
|
|
4
|
|
} else {
|
|
i += 1;
|
|
continue;
|
|
};
|
|
let nal_idx = i + sc_len;
|
|
if nal_idx < bytes.len() {
|
|
let hdr = bytes[nal_idx];
|
|
if is_h265 {
|
|
let nal_type = (hdr >> 1) & 0x3F;
|
|
if matches!(nal_type, 19..=21 | 32 | 33) {
|
|
return true;
|
|
}
|
|
} else {
|
|
let nal_type = hdr & 0x1F;
|
|
if matches!(nal_type, 5 | 7) {
|
|
return true;
|
|
}
|
|
}
|
|
}
|
|
i = nal_idx + 1;
|
|
}
|
|
false
|
|
}
|
|
|
|
#[derive(Clone)]
|
|
struct ReplayPacket {
|
|
data: Vec<u8>,
|
|
received_at: Instant,
|
|
is_keyframe: bool,
|
|
}
|
|
|
|
#[derive(Clone)]
|
|
struct ReplayCaption {
|
|
text: String,
|
|
received_at: Instant,
|
|
}
|
|
|
|
/// Pré-buffer circulaire en RAM (Blackbox 30 s) pour Instant Replay zéro-CPU en flux H.264/H.265.
|
|
pub struct ReplayRingBuffer {
|
|
packets: Mutex<VecDeque<ReplayPacket>>,
|
|
captions: Mutex<VecDeque<ReplayCaption>>,
|
|
total_bytes: AtomicU64,
|
|
window: Duration,
|
|
max_bytes: usize,
|
|
}
|
|
|
|
impl Default for ReplayRingBuffer {
|
|
fn default() -> Self {
|
|
Self::new(Duration::from_secs(REPLAY_WINDOW_SECS), REPLAY_MAX_BYTES)
|
|
}
|
|
}
|
|
|
|
impl ReplayRingBuffer {
|
|
pub fn new(window: Duration, max_bytes: usize) -> Self {
|
|
Self {
|
|
packets: Mutex::new(VecDeque::with_capacity(1800)),
|
|
captions: Mutex::new(VecDeque::with_capacity(64)),
|
|
total_bytes: AtomicU64::new(0),
|
|
window,
|
|
max_bytes,
|
|
}
|
|
}
|
|
|
|
/// Empile un paquet compressé H.264/H.265 dans le pré-buffer circulaire.
|
|
pub fn push_encoded_packet(&self, data: &[u8], codec: &str, gst_is_delta: bool) {
|
|
if data.is_empty() || data.len() > self.max_bytes / 2 {
|
|
return;
|
|
}
|
|
let now = Instant::now();
|
|
let is_keyframe = detect_keyframe(data, codec, gst_is_delta);
|
|
let pkt_len = data.len();
|
|
|
|
let mut q = self.packets.lock();
|
|
q.push_back(ReplayPacket {
|
|
data: data.to_vec(),
|
|
received_at: now,
|
|
is_keyframe,
|
|
});
|
|
let mut cur_bytes = self.total_bytes.load(Ordering::Relaxed) as usize + pkt_len;
|
|
|
|
while let Some(front) = q.front() {
|
|
let expired = now.saturating_duration_since(front.received_at) > self.window;
|
|
let over_cap = cur_bytes > self.max_bytes;
|
|
if (expired || over_cap) && q.len() > 1 {
|
|
let removed = q.pop_front().unwrap();
|
|
cur_bytes = cur_bytes.saturating_sub(removed.data.len());
|
|
} else {
|
|
break;
|
|
}
|
|
}
|
|
self.total_bytes.store(cur_bytes as u64, Ordering::Relaxed);
|
|
}
|
|
|
|
/// Empile un sous-titre télémétrie horodaté (1 Hz) pour accompagner l'Instant Replay.
|
|
pub fn push_caption(&self, text: String) {
|
|
let now = Instant::now();
|
|
let mut q = self.captions.lock();
|
|
if let Some(back) = q.back() {
|
|
if now.saturating_duration_since(back.received_at) < Duration::from_millis(950) {
|
|
return;
|
|
}
|
|
}
|
|
q.push_back(ReplayCaption {
|
|
text,
|
|
received_at: now,
|
|
});
|
|
while let Some(front) = q.front() {
|
|
if now.saturating_duration_since(front.received_at) > self.window + Duration::from_secs(2)
|
|
{
|
|
q.pop_front();
|
|
} else {
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
|
|
pub fn buffered_bytes(&self) -> u64 {
|
|
self.total_bytes.load(Ordering::Relaxed)
|
|
}
|
|
|
|
pub fn clear(&self) {
|
|
self.packets.lock().clear();
|
|
self.captions.lock().clear();
|
|
self.total_bytes.store(0, Ordering::Relaxed);
|
|
}
|
|
|
|
/// Exporte les 30 dernières secondes (à partir de la plus ancienne image-clé) vers `replay_YYYYMMDD_HHMMSS.<ext>` + `.srt`.
|
|
pub fn save_instant_replay(
|
|
&self,
|
|
dir: &str,
|
|
container: DvrContainer,
|
|
codec: &str,
|
|
) -> Result<(PathBuf, usize, f32)> {
|
|
let snapshot: Vec<ReplayPacket> = {
|
|
let q = self.packets.lock();
|
|
if q.is_empty() {
|
|
return Err(anyhow!(
|
|
"Pré-buffer Replay vide (aucun flux H.264/H.265 reçu récemment)"
|
|
));
|
|
}
|
|
let start_idx = q.iter().position(|p| p.is_keyframe).unwrap_or(0);
|
|
q.iter().skip(start_idx).cloned().collect()
|
|
};
|
|
if snapshot.is_empty() {
|
|
return Err(anyhow!("Aucune trame exploitable dans le pré-buffer Replay"));
|
|
}
|
|
let t0 = snapshot.first().unwrap().received_at;
|
|
let t_end = snapshot.last().unwrap().received_at;
|
|
let duration_s = t_end.saturating_duration_since(t0).as_secs_f32();
|
|
|
|
let captions: Vec<ReplayCaption> = {
|
|
let c = self.captions.lock();
|
|
let min_t = t0.checked_sub(Duration::from_secs(1)).unwrap_or(t0);
|
|
c.iter().filter(|cap| cap.received_at >= min_t).cloned().collect()
|
|
};
|
|
|
|
gst::init().context("Échec d'initialisation GStreamer pour Instant Replay")?;
|
|
fs::create_dir_all(dir)
|
|
.with_context(|| format!("Impossible de créer le répertoire DVR '{}'", dir))?;
|
|
|
|
let file_path = DvrRecorder::generate_prefixed_filepath(dir, "replay", container);
|
|
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=rep_src format=time caps={caps} ! \
|
|
{parser} config-interval=-1 ! \
|
|
{muxer} ! \
|
|
filesink name=rep_sink sync=false"
|
|
);
|
|
let element = gst::parse::launch(&pipeline_str)
|
|
.map_err(|e| anyhow!("Erreur pipeline Replay : {}", e))?;
|
|
let pipeline = element
|
|
.dynamic_cast::<gst::Pipeline>()
|
|
.map_err(|_| anyhow!("L'élément Replay n'est pas un Pipeline"))?;
|
|
let appsrc = pipeline
|
|
.by_name("rep_src")
|
|
.context("rep_src introuvable")?
|
|
.dynamic_cast::<gst_app::AppSrc>()
|
|
.map_err(|_| anyhow!("Conversion rep_src -> AppSrc échouée"))?;
|
|
let filesink = pipeline.by_name("rep_sink").context("rep_sink introuvable")?;
|
|
filesink.set_property(
|
|
"location",
|
|
file_path
|
|
.to_str()
|
|
.ok_or_else(|| anyhow!("Chemin Replay invalide"))?,
|
|
);
|
|
|
|
pipeline
|
|
.set_state(gst::State::Playing)
|
|
.map_err(|e| anyhow!("Démarrage pipeline Replay échoué : {}", e))?;
|
|
|
|
let pkt_count = snapshot.len();
|
|
for pkt in snapshot {
|
|
let pts_ns = pkt.received_at.saturating_duration_since(t0).as_nanos() as u64;
|
|
let mut buf = gst::Buffer::from_slice(pkt.data);
|
|
if let Some(bref) = buf.get_mut() {
|
|
bref.set_pts(gst::ClockTime::from_nseconds(pts_ns));
|
|
}
|
|
if let Err(err) = appsrc.push_buffer(buf) {
|
|
log::warn!("[Replay] Arrêt anticipé push_buffer : {:?}", err);
|
|
break;
|
|
}
|
|
}
|
|
let _ = appsrc.end_of_stream();
|
|
|
|
if let Some(bus) = pipeline.bus() {
|
|
let deadline = Instant::now() + Duration::from_millis(3000);
|
|
while Instant::now() < deadline {
|
|
if let Some(msg) = bus.timed_pop(gst::ClockTime::from_mseconds(50)) {
|
|
use gst::MessageView;
|
|
match msg.view() {
|
|
MessageView::Eos(..) | MessageView::Error(..) => break,
|
|
_ => {}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
let _ = pipeline.set_state(gst::State::Null);
|
|
|
|
// Écrire le fichier sous-titres .srt synchronisé avec l'Instant Replay
|
|
if !captions.is_empty() {
|
|
let mut srt = SrtWriterState::open_for_video(&file_path);
|
|
for cap in &captions {
|
|
let rel_ms = cap.received_at.saturating_duration_since(t0).as_millis() as u64;
|
|
srt.push_caption(rel_ms, &cap.text);
|
|
}
|
|
srt.finish((duration_s * 1000.0) as u64);
|
|
}
|
|
|
|
log::info!(
|
|
"[Replay] Instant Replay sauvegardé : {:?} ({} paquets, {:.1} s)",
|
|
file_path,
|
|
pkt_count,
|
|
duration_s
|
|
);
|
|
Ok((file_path, pkt_count, duration_s))
|
|
}
|
|
}
|
|
|
|
/// Enregistreur vidéo DVR asynchrone basé sur GStreamer avec sous-titres télémétrie `.srt` synchronisés.
|
|
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>,
|
|
srt_writer: Mutex<SrtWriterState>,
|
|
gpx_writer: Mutex<GpxWriterState>,
|
|
}
|
|
|
|
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 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 max-bytes={DVR_MAX_QUEUE_BYTES} caps={caps} ! \
|
|
{parser} config-interval=-1 ! \
|
|
{muxer} ! \
|
|
filesink name=dvr_sink sync=false"
|
|
);
|
|
|
|
log::info!(
|
|
"[DVR] Démarrage enregistrement StreamCopy ({}) -> {:?} (+ .srt télémétrie)",
|
|
codec.to_uppercase(),
|
|
file_path
|
|
);
|
|
|
|
Self::launch(pipeline_str, file_path, DvrMode::StreamCopy)
|
|
}
|
|
|
|
/// Démarre un enregistrement en mode incrustation OSD (sonde encodeur H.264 matériel puis repli 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 muxer = container.muxer_element();
|
|
|
|
let make_pipeline = |encoder: &str| {
|
|
format!(
|
|
"appsrc name=dvr_src is-live=true format=time do-timestamp=true max-bytes={DVR_MAX_QUEUE_BYTES} \
|
|
caps=video/x-raw,format=RGBA,width={width},height={height},framerate=0/1 ! \
|
|
videoconvert ! \
|
|
{encoder} ! \
|
|
h264parse config-interval=-1 ! \
|
|
{muxer} ! \
|
|
filesink name=dvr_sink sync=false"
|
|
)
|
|
};
|
|
|
|
// En production, tenter un encodeur matériel (v4l2h264enc / vah264enc) avant x264enc CPU
|
|
#[cfg(not(test))]
|
|
for &(factory, desc) in &[
|
|
("v4l2h264enc", "v4l2h264enc"),
|
|
("vah264enc", "vah264enc bitrate=8000"),
|
|
] {
|
|
if gst::ElementFactory::find(factory).is_some() {
|
|
if let Ok(rec) =
|
|
Self::launch(make_pipeline(desc), file_path.clone(), DvrMode::CompositedOsd)
|
|
{
|
|
log::info!(
|
|
"[DVR] Démarrage enregistrement OSD HW ({factory}, {width}x{height} VFR) -> {:?}",
|
|
file_path
|
|
);
|
|
return Ok(rec);
|
|
}
|
|
}
|
|
}
|
|
|
|
let pipeline_str = make_pipeline(
|
|
"x264enc tune=zerolatency speed-preset=ultrafast bitrate=8000 key-int-max=60",
|
|
);
|
|
|
|
log::info!(
|
|
"[DVR] Démarrage enregistrement OSD ({width}x{height} VFR) -> {:?}",
|
|
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!("Erreur pipeline DVR : {}", e)
|
|
})?;
|
|
|
|
let pipeline = element
|
|
.dynamic_cast::<gst::Pipeline>()
|
|
.map_err(|_| 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!("Impossible de convertir dvr_src en AppSrc"))?;
|
|
|
|
let filesink = pipeline
|
|
.by_name("dvr_sink")
|
|
.context("Filesink 'dvr_sink' introuvable dans le pipeline DVR")?;
|
|
let path_str = file_path
|
|
.to_str()
|
|
.ok_or_else(|| anyhow!("Chemin DVR invalide"))?;
|
|
filesink.set_property("location", path_str);
|
|
|
|
pipeline
|
|
.set_state(gst::State::Playing)
|
|
.map_err(|e| anyhow!("Impossible de démarrer le pipeline DVR : {}", e))?;
|
|
|
|
let srt_writer = Mutex::new(SrtWriterState::open_for_video(&file_path));
|
|
let gpx_writer = Mutex::new(GpxWriterState::open_for_video(&file_path));
|
|
|
|
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)),
|
|
srt_writer,
|
|
gpx_writer,
|
|
}))
|
|
}
|
|
|
|
/// Génère un nom de fichier horodaté `fpv_YYYYMMDD_HHMMSS.<ext>` sans écrasement
|
|
pub fn generate_filepath(dir: &str, container: DvrContainer) -> PathBuf {
|
|
Self::generate_prefixed_filepath(dir, "fpv", container)
|
|
}
|
|
|
|
pub fn generate_prefixed_filepath(dir: &str, prefix: &str, container: DvrContainer) -> PathBuf {
|
|
let now = Local::now();
|
|
let stamp = now.format("%Y%m%d_%H%M%S");
|
|
let ext = container.extension();
|
|
let base_dir = Path::new(dir);
|
|
let candidate = base_dir.join(format!("{}_{}.{}", prefix, stamp, ext));
|
|
if !candidate.exists() {
|
|
return candidate;
|
|
}
|
|
for n in 1..1000 {
|
|
let numbered = base_dir.join(format!("{}_{}_{}.{}", prefix, stamp, n, ext));
|
|
if !numbered.exists() {
|
|
return numbered;
|
|
}
|
|
}
|
|
candidate
|
|
}
|
|
|
|
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)
|
|
}
|
|
|
|
/// Enregistre une entrée télémétrie dans le fichier sous-titres `.srt` compagnon (throttlé ~1 Hz).
|
|
pub fn push_telemetry_caption(&self, caption: &str) {
|
|
if !self.is_recording.load(Ordering::Acquire) || caption.trim().is_empty() {
|
|
return;
|
|
}
|
|
let elapsed_ms = self.start_time.elapsed().as_millis() as u64;
|
|
self.srt_writer.lock().push_caption(elapsed_ms, caption);
|
|
}
|
|
|
|
/// Enregistre un point GPS dans la trace `.gpx` compagnon (throttlé ~1 Hz).
|
|
pub fn push_gps_point(&self, lat_deg: f64, lon_deg: f64, alt_m: f32) {
|
|
if !self.is_recording.load(Ordering::Acquire) {
|
|
return;
|
|
}
|
|
self.gpx_writer.lock().push_point(lat_deg, lon_deg, alt_m);
|
|
}
|
|
|
|
/// Sonde le bus GStreamer (non-bloquant) et rafraîchit la taille réelle du fichier sur disque.
|
|
fn poll_health_and_size(&self) {
|
|
if let Some(bus) = self.pipeline.bus() {
|
|
while let Some(msg) = bus.pop() {
|
|
use gst::MessageView;
|
|
match msg.view() {
|
|
MessageView::Error(err) => {
|
|
log::error!(
|
|
"[DVR] Erreur pipeline en cours d'enregistrement ({:?}) : {} — arrêt DVR.",
|
|
self.file_path,
|
|
err.error()
|
|
);
|
|
self.is_recording.store(false, Ordering::Release);
|
|
break;
|
|
}
|
|
MessageView::Eos(..) => {
|
|
log::warn!("[DVR] EOS inattendu reçu pendant l'enregistrement.");
|
|
self.is_recording.store(false, Ordering::Release);
|
|
break;
|
|
}
|
|
_ => {}
|
|
}
|
|
}
|
|
}
|
|
if let Ok(meta) = fs::metadata(&self.file_path) {
|
|
self.bytes_written.store(meta.len(), Ordering::Relaxed);
|
|
}
|
|
}
|
|
|
|
/// Pousse un buffer GStreamer existant (zéro-copie de pointeur GstBuffer, avec garde-fou anti-OOM)
|
|
pub fn push_buffer(&self, buffer: gst::Buffer) {
|
|
if !self.is_recording.load(Ordering::Acquire) {
|
|
return;
|
|
}
|
|
if self.appsrc.current_level_bytes() >= DVR_MAX_QUEUE_BYTES {
|
|
return;
|
|
}
|
|
let buf_len = buffer.size() as u64;
|
|
if let Err(flow_err) = self.appsrc.push_buffer(buffer) {
|
|
log::error!(
|
|
"[DVR] Échec push_buffer ({:?}) : arrêt de l'enregistrement.",
|
|
flow_err
|
|
);
|
|
self.is_recording.store(false, Ordering::Release);
|
|
return;
|
|
}
|
|
let frame_num = self.frames_recorded.fetch_add(1, Ordering::Relaxed) + 1;
|
|
if self.mode == DvrMode::StreamCopy {
|
|
self.bytes_written.fetch_add(buf_len, Ordering::Relaxed);
|
|
}
|
|
if frame_num.is_multiple_of(30) {
|
|
self.poll_health_and_size();
|
|
}
|
|
}
|
|
|
|
/// 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::Acquire) {
|
|
return;
|
|
}
|
|
if self.appsrc.current_level_bytes() >= DVR_MAX_QUEUE_BYTES {
|
|
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 + `.srt`.
|
|
pub fn stop(&self) {
|
|
if !self.is_recording.swap(false, Ordering::SeqCst) {
|
|
return;
|
|
}
|
|
|
|
log::info!(
|
|
"[DVR] Finalisation de l'enregistrement {:?}...",
|
|
self.file_path
|
|
);
|
|
|
|
let end_ms = self.start_time.elapsed().as_millis() as u64;
|
|
self.srt_writer.lock().finish(end_ms);
|
|
self.gpx_writer.lock().finish();
|
|
|
|
let _ = self.appsrc.end_of_stream();
|
|
|
|
if let Some(bus) = self.pipeline.bus() {
|
|
let deadline = Instant::now() + Duration::from_millis(2500);
|
|
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);
|
|
if let Ok(meta) = fs::metadata(&self.file_path) {
|
|
self.bytes_written.store(meta.len(), Ordering::Relaxed);
|
|
}
|
|
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_mode_parsing() {
|
|
assert_eq!(DvrMode::from_str("composited"), DvrMode::CompositedOsd);
|
|
assert_eq!(DvrMode::from_str("COMPOSITED"), DvrMode::CompositedOsd);
|
|
assert_eq!(DvrMode::from_str("osd"), DvrMode::CompositedOsd);
|
|
assert_eq!(DvrMode::from_str("copy"), DvrMode::StreamCopy);
|
|
}
|
|
|
|
#[test]
|
|
fn test_srt_timestamp_and_keyframe_detection() {
|
|
assert_eq!(format_srt_timestamp(0), "00:00:00,000");
|
|
assert_eq!(format_srt_timestamp(3_723_456), "01:02:03,456");
|
|
|
|
// H.264 IDR (NAL type 5 = 0x65) et SPS (NAL type 7 = 0x67)
|
|
assert!(detect_keyframe(&[0, 0, 0, 1, 0x65, 0x88], "h264", true));
|
|
assert!(detect_keyframe(&[0, 0, 1, 0x67, 0x42], "h264", true));
|
|
// H.264 P-frame (NAL type 1 = 0x41)
|
|
assert!(!detect_keyframe(&[0, 0, 0, 1, 0x41, 0x9A], "h264", true));
|
|
// H.265 IDR_W_RADL (NAL type 19 -> (19 << 1) = 0x26)
|
|
assert!(detect_keyframe(&[0, 0, 0, 1, 0x26, 0x01], "h265", true));
|
|
// Non-delta GStreamer flag -> toujours keyframe
|
|
assert!(detect_keyframe(&[0, 0, 0, 1, 0x41], "h264", false));
|
|
}
|
|
|
|
#[test]
|
|
fn test_replay_ring_buffer_cap_and_eviction() {
|
|
let rb = ReplayRingBuffer::new(Duration::from_secs(30), 2048);
|
|
let idr = vec![0u8, 0, 0, 1, 0x65, 1, 2, 3];
|
|
let pframe = vec![0u8; 600];
|
|
rb.push_encoded_packet(&idr, "h264", true);
|
|
for _ in 0..5 {
|
|
rb.push_encoded_packet(&pframe, "h264", true);
|
|
}
|
|
assert!(rb.buffered_bytes() <= 2048);
|
|
assert!(rb.buffered_bytes() >= 600);
|
|
}
|
|
|
|
#[test]
|
|
fn test_dvr_recording_mkv_srt_and_stop() {
|
|
let dir = format!("/tmp/test_dvr_run_{}", std::process::id());
|
|
let dvr = DvrRecorder::start_composited_osd(&dir, DvrContainer::Mkv, 320, 240)
|
|
.expect("start dvr failed");
|
|
dvr.push_telemetry_caption("BAT 15.2V (3.80V/c) | LQ 99% | G2 | 24 km/h");
|
|
dvr.push_gps_point(48.856614, 2.3522219, 35.4);
|
|
let fake_rgba = vec![0u8; 320 * 240 * 4];
|
|
for _ in 0..10 {
|
|
dvr.push_slice(&fake_rgba);
|
|
std::thread::sleep(Duration::from_millis(10));
|
|
}
|
|
let path = dvr.file_path().to_path_buf();
|
|
let srt_path = path.with_extension("srt");
|
|
let gpx_path = path.with_extension("gpx");
|
|
dvr.stop();
|
|
assert!(path.exists());
|
|
assert!(srt_path.exists());
|
|
assert!(gpx_path.exists());
|
|
let srt_content = fs::read_to_string(&srt_path).expect("read srt");
|
|
assert!(srt_content.contains("BAT 15.2V"));
|
|
assert!(srt_content.contains("-->"));
|
|
let gpx_content = fs::read_to_string(&gpx_path).expect("read gpx");
|
|
assert!(gpx_content.contains("<gpx"));
|
|
assert!(gpx_content.contains("48.8566140"));
|
|
assert!(gpx_content.contains("</gpx>"));
|
|
let meta = fs::metadata(&path).expect("file metadata");
|
|
assert!(meta.len() > 0);
|
|
let _ = fs::remove_dir_all(&dir);
|
|
}
|
|
}
|