mirror of
https://github.com/bleackstorm/SteamFrame-FPV-Control-Center.git
synced 2026-12-03 07:31:57 +01:00
feat(gpu,dvr,ci): image enhance/SBS/DMA-BUF, DVR .srt + Replay 30s, GPS Home arrow, CI & modular split
This commit is contained in:
1 parent
4aa4fc06e7
commit
b4642ddc95
33 files changed
+8279
-6092
No files matched your search
+425
-22
@@ -1,16 +1,23 @@
|
||||
use anyhow::{Context, Result};
|
||||
use anyhow::{anyhow, Context, Result};
|
||||
use chrono::Local;
|
||||
use gstreamer as gst;
|
||||
use gstreamer::prelude::*;
|
||||
use gstreamer_app as gst_app;
|
||||
use std::fs;
|
||||
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::Instant;
|
||||
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,
|
||||
@@ -69,7 +76,344 @@ impl DvrMode {
|
||||
}
|
||||
}
|
||||
|
||||
/// Enregistreur vidéo DVR asynchrone basé sur GStreamer
|
||||
/// 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 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,
|
||||
@@ -79,6 +423,7 @@ pub struct DvrRecorder {
|
||||
bytes_written: Arc<AtomicU64>,
|
||||
frames_recorded: Arc<AtomicU64>,
|
||||
is_recording: Arc<AtomicBool>,
|
||||
srt_writer: Mutex<SrtWriterState>,
|
||||
}
|
||||
|
||||
impl DvrRecorder {
|
||||
@@ -113,7 +458,7 @@ impl DvrRecorder {
|
||||
);
|
||||
|
||||
log::info!(
|
||||
"[DVR] Démarrage enregistrement StreamCopy ({}) -> {:?}",
|
||||
"[DVR] Démarrage enregistrement StreamCopy ({}) -> {:?} (+ .srt télémétrie)",
|
||||
codec.to_uppercase(),
|
||||
file_path
|
||||
);
|
||||
@@ -155,7 +500,9 @@ impl DvrRecorder {
|
||||
("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) {
|
||||
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
|
||||
@@ -179,31 +526,37 @@ impl DvrRecorder {
|
||||
|
||||
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)
|
||||
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::anyhow!("L'élément DVR n'est pas un 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::anyhow!("Impossible de convertir dvr_src en 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::anyhow!("Chemin DVR invalide"))?;
|
||||
.ok_or_else(|| anyhow!("Chemin DVR invalide"))?;
|
||||
filesink.set_property("location", path_str);
|
||||
|
||||
pipeline
|
||||
.set_state(gst::State::Playing)
|
||||
.map_err(|e| anyhow::anyhow!("Impossible de démarrer le pipeline DVR : {}", e))?;
|
||||
.map_err(|e| anyhow!("Impossible de démarrer le pipeline DVR : {}", e))?;
|
||||
|
||||
let srt_writer = Mutex::new(SrtWriterState::open_for_video(&file_path));
|
||||
|
||||
Ok(Arc::new(Self {
|
||||
pipeline,
|
||||
@@ -214,21 +567,26 @@ impl DvrRecorder {
|
||||
bytes_written: Arc::new(AtomicU64::new(0)),
|
||||
frames_recorded: Arc::new(AtomicU64::new(0)),
|
||||
is_recording: Arc::new(AtomicBool::new(true)),
|
||||
srt_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!("fpv_{}.{}", stamp, ext));
|
||||
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!("fpv_{}_{}.{}", stamp, n, ext));
|
||||
let numbered = base_dir.join(format!("{}_{}_{}.{}", prefix, stamp, n, ext));
|
||||
if !numbered.exists() {
|
||||
return numbered;
|
||||
}
|
||||
@@ -261,6 +619,15 @@ impl DvrRecorder {
|
||||
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);
|
||||
}
|
||||
|
||||
/// 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() {
|
||||
@@ -296,7 +663,6 @@ impl DvrRecorder {
|
||||
return;
|
||||
}
|
||||
if self.appsrc.current_level_bytes() >= DVR_MAX_QUEUE_BYTES {
|
||||
// File saturée (stockage lent) : abandonner la trame plutôt que saturer la RAM en vol.
|
||||
return;
|
||||
}
|
||||
let buf_len = buffer.size() as u64;
|
||||
@@ -322,7 +688,6 @@ impl DvrRecorder {
|
||||
if !self.is_recording.load(Ordering::Acquire) {
|
||||
return;
|
||||
}
|
||||
// Vérifier la saturation AVANT l'allocation `slice.to_vec()` (4 à 8 Mo)
|
||||
if self.appsrc.current_level_bytes() >= DVR_MAX_QUEUE_BYTES {
|
||||
return;
|
||||
}
|
||||
@@ -330,7 +695,7 @@ impl DvrRecorder {
|
||||
self.push_buffer(buffer);
|
||||
}
|
||||
|
||||
/// Arrête proprement l'enregistrement en envoyant un signal EOS pour finaliser les en-têtes
|
||||
/// 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;
|
||||
@@ -341,10 +706,13 @@ impl DvrRecorder {
|
||||
self.file_path
|
||||
);
|
||||
|
||||
let end_ms = self.start_time.elapsed().as_millis() as u64;
|
||||
self.srt_writer.lock().finish(end_ms);
|
||||
|
||||
let _ = self.appsrc.end_of_stream();
|
||||
|
||||
if let Some(bus) = self.pipeline.bus() {
|
||||
let deadline = Instant::now() + std::time::Duration::from_millis(2500);
|
||||
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;
|
||||
@@ -408,20 +776,55 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_dvr_recording_mkv_and_stop() {
|
||||
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");
|
||||
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));
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
}
|
||||
let path = dvr.file_path().to_path_buf();
|
||||
let srt_path = path.with_extension("srt");
|
||||
dvr.stop();
|
||||
assert!(path.exists());
|
||||
let meta = std::fs::metadata(&path).expect("file metadata");
|
||||
assert!(srt_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 meta = fs::metadata(&path).expect("file metadata");
|
||||
assert!(meta.len() > 0);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user