From 4fdffe33936c3ca1a3dd99362dd82505d5c432f8 Mon Sep 17 00:00:00 2001 From: bleack Date: Sat, 28 Nov 2026 00:40:08 +0100 Subject: [PATCH 1/2] perf(video): immediate Annex-B burst flush for Android and Condvar frame wake-up on PC --- crates/fpv-core/src/video_udp.rs | 71 +++++++++++++++++++++++++++++++- src/engine/desktop_loop.rs | 9 +++- src/video_usb.rs | 23 ++++++++++- 3 files changed, 98 insertions(+), 5 deletions(-) diff --git a/crates/fpv-core/src/video_udp.rs b/crates/fpv-core/src/video_udp.rs index d26a659..c1ffed5 100644 --- a/crates/fpv-core/src/video_udp.rs +++ b/crates/fpv-core/src/video_udp.rs @@ -421,6 +421,34 @@ impl AnnexBFramer { cur_sc_len = next_sc_len; } } + + /// Émet immédiatement le dernier NAL en attente (ex. paquet de fin de burst `< 1024` octets + /// sous RubyFPV ou silence UDP >= 2 ms) afin d'éliminer 1 frame entière (+16,7 ms à 60 fps) + /// de latence d'attente du start code suivant. + pub fn flush_pending(&mut self, pts_us: u64, mut emit: F) -> bool + where + F: FnMut(VideoNalUnit), + { + let Some((pos, sc_len)) = Self::find_start_code(&self.buf, 0) else { + return false; + }; + if pos > 0 { + self.buf.drain(..pos); + } + if self.buf.len() <= sc_len { + return false; + } + let nal_hdr = self.buf[sc_len]; + let (is_keyframe, is_codec_config) = classify_nal(self.codec, nal_hdr); + let data = std::mem::take(&mut self.buf); + emit(VideoNalUnit { + data, + pts_us, + is_keyframe, + is_codec_config, + }); + true + } } /// Récepteur vidéo UDP pur Rust (port `5600` par défaut) destiné au décodeur matériel Android (`MediaCodec`). @@ -443,7 +471,13 @@ impl UdpVideoReceiver { { let addr = format!("{}:{}", bind_ip, port); let socket = UdpSocket::bind(&addr)?; - socket.set_read_timeout(Some(Duration::from_millis(100)))?; + // En mode Raw Annex-B (RubyFPV), un timeout de 2 ms permet de flusher immédiatement + // la dernière trame dès la fin d'un burst UDP sans attendre le start code suivant. + let read_timeout = match transport { + StreamTransport::Raw => Duration::from_millis(2), + StreamTransport::Rtp => Duration::from_millis(50), + }; + socket.set_read_timeout(Some(read_timeout))?; log::info!( "[UDP Video] En écoute sur {} ({:?}, {:?})", addr, @@ -510,6 +544,11 @@ impl UdpVideoReceiver { pts_us, &mut emit_and_track, ); + // RubyFPV découpe en paquets de 1024 octets (`video_usb: 1 5600 1024`) : + // un paquet plus court marque la fin immédiate de la trame. + if len < 1024 { + annex_b_framer.flush_pending(pts_us, &mut emit_and_track); + } } } @@ -518,7 +557,30 @@ impl UdpVideoReceiver { m.dropped_packets = depacketizer.dropped_packets; m.signal_live = true; } - _ => {} + _ => { + if transport == StreamTransport::Raw { + let now = Instant::now(); + let pts_us = start_time.elapsed().as_micros() as u64; + annex_b_framer.flush_pending(pts_us, |nal| { + if !nal.is_codec_config { + fps_frames = fps_frames.saturating_add(1); + if let Some(prev_f) = last_frame_at { + let dt_ms = + now.duration_since(prev_f).as_secs_f32() * 1000.0; + if dt_ms > 1.0 && dt_ms < 250.0 { + expected_interval_ms = + expected_interval_ms * 0.9 + dt_ms * 0.1; + let diff = (dt_ms - expected_interval_ms).abs(); + jitter_ms_ewma = + jitter_ms_ewma * 0.85 + diff * 0.15; + } + } + last_frame_at = Some(now); + } + on_nal(nal); + }); + } + } } let win_elapsed = fps_window_start.elapsed(); @@ -651,5 +713,10 @@ mod tests { assert_eq!(out[0].data, vec![0, 0, 0, 1, 0x67, 0x42, 0x00, 0x1E]); assert!(out[1].is_keyframe); assert_eq!(out[1].data, vec![0, 0, 0, 1, 0x65, 0xAA, 0xBB]); + // Le dernier NAL (P-frame 0x41) est émis immédiatement via flush_pending + assert!(framer.flush_pending(2000, |n| out.push(n))); + assert_eq!(out.len(), 3); + assert_eq!(out[2].data, vec![0, 0, 0, 1, 0x41]); + assert!(!framer.flush_pending(2000, |n| out.push(n))); } } diff --git a/src/engine/desktop_loop.rs b/src/engine/desktop_loop.rs index 2c483d1..1fdd767 100644 --- a/src/engine/desktop_loop.rs +++ b/src/engine/desktop_loop.rs @@ -178,9 +178,14 @@ pub fn run_desktop_fallback_loop(ctx: &mut EngineWorkerRefs<'_>) { ); let elapsed = loop_start.elapsed(); - let target_dt = Duration::from_millis(8); // Jusqu'à 120 Hz sur les flux 90/120 FPS + let target_dt = Duration::from_millis(8); if elapsed < target_dt { - thread::sleep(target_dt - elapsed); + let remaining = target_dt - elapsed; + if let Some(rx) = ctx.video_rx_opt { + rx.wait_for_frame(last_frame_id, remaining); + } else { + thread::sleep(remaining); + } } } } diff --git a/src/video_usb.rs b/src/video_usb.rs index a980d14..708a873 100644 --- a/src/video_usb.rs +++ b/src/video_usb.rs @@ -5,7 +5,7 @@ use gstreamer::prelude::*; use gstreamer_app as gst_app; use gstreamer_video as gst_video; use gstreamer_video::prelude::*; -use parking_lot::Mutex; +use parking_lot::{Condvar, Mutex}; use std::os::fd::{BorrowedFd, OwnedFd}; use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use std::sync::Arc; @@ -101,6 +101,8 @@ pub struct FrameMailbox { /// Horodatage de la dernière trame publiée (conservé même après consommation par l'UI/VR /// pour éviter les faux positifs "Signal vidéo perdu" entre deux trames). last_received_at: Option, + /// Signal événementiel pour réveiller instantanément la boucle Bureau dès qu'une trame arrive. + frame_condvar: Arc, } impl FrameMailbox { @@ -114,12 +116,14 @@ impl FrameMailbox { if self.spare_buf.capacity() > incoming.capacity() { std::mem::swap(&mut self.spare_buf, incoming); } + self.frame_condvar.notify_all(); } /// Publie une trame DMA-BUF zéro-copie (sans aucune copie pixel côté CPU). fn publish_dmabuf(&mut self, dmabuf: DmaBufFrame) { self.last_received_at = Some(dmabuf.received_at); self.dmabuf_ready = Some(dmabuf); + self.frame_condvar.notify_all(); } /// Récupère la dernière trame DMA-BUF si plus récente que `last_frame_id` et fraîche. @@ -323,6 +327,23 @@ impl UsbVideoReceiver { .take_if_newer(consumer_buf, last_frame_id, max_age) } + /// Attend de manière événementielle (`Condvar`) l'arrivée d'une trame plus récente que `last_frame_id` + /// (jusqu'à `timeout`), supprimant le délai de polling fixe dans la boucle Bureau. + pub fn wait_for_frame(&self, last_frame_id: u64, timeout: Duration) { + let mut guard = self.mailbox.lock(); + let has_newer = guard + .ready_meta + .is_some_and(|m| m.frame_id != last_frame_id) + || guard + .dmabuf_ready + .as_ref() + .is_some_and(|d| d.frame_id != last_frame_id); + if !has_newer { + let cv = Arc::clone(&guard.frame_condvar); + cv.wait_for(&mut guard, timeout); + } + } + pub fn metrics(&self) -> VideoLinkMetrics { self.metrics.lock().clone() } From 19cdf982c4206c1dc3df09168d74ad87c4975869 Mon Sep 17 00:00:00 2001 From: bleack Date: Sat, 28 Nov 2026 00:58:55 +0100 Subject: [PATCH 2/2] perf(android): prefer Qualcomm c2.qti.*.low_latency decoder, picture-order output, and immediate VSync render --- .../steamframe/fpv/LowLatencyVideoDecoder.kt | 44 ++++++++++++++++--- 1 file changed, 38 insertions(+), 6 deletions(-) diff --git a/android/app/src/main/kotlin/com/steamframe/fpv/LowLatencyVideoDecoder.kt b/android/app/src/main/kotlin/com/steamframe/fpv/LowLatencyVideoDecoder.kt index 2e2609b..ce2dc5c 100644 --- a/android/app/src/main/kotlin/com/steamframe/fpv/LowLatencyVideoDecoder.kt +++ b/android/app/src/main/kotlin/com/steamframe/fpv/LowLatencyVideoDecoder.kt @@ -3,6 +3,8 @@ package com.steamframe.fpv import android.content.ContentValues import android.content.Context import android.media.MediaCodec +import android.media.MediaCodecInfo +import android.media.MediaCodecList import android.media.MediaFormat import android.media.MediaMuxer import android.os.Environment @@ -67,15 +69,45 @@ class LowLatencyVideoDecoder(private val context: Context) { } } + private fun createBestLowLatencyDecoder(mime: String): MediaCodec { + val list = MediaCodecList(MediaCodecList.REGULAR_CODECS).codecInfos + var featureMatch: String? = null + for (info in list) { + if (info.isEncoder) continue + if (!info.supportedTypes.any { it.equals(mime, ignoreCase = true) }) continue + val nameLower = info.name.lowercase(Locale.US) + if (nameLower.contains("low_latency")) { + Log.i(TAG, "Sélection décodeur matériel dédié low_latency : ${info.name}") + return MediaCodec.createByCodecName(info.name) + } + if (featureMatch == null && !nameLower.startsWith("c2.android.") && !nameLower.startsWith("omx.google.")) { + val caps = try { + info.getCapabilitiesForType(mime) + } catch (_: Exception) { + null + } + if (caps?.isFeatureSupported(MediaCodecInfo.CodecCapabilities.FEATURE_LowLatency) == true) { + featureMatch = info.name + } + } + } + if (featureMatch != null) { + Log.i(TAG, "Sélection décodeur matériel FEATURE_LowLatency : $featureMatch") + return MediaCodec.createByCodecName(featureMatch) + } + return MediaCodec.createDecoderByType(mime) + } + private fun initCodecLocked(targetSurface: Surface) { try { - val mc = MediaCodec.createDecoderByType(mimeType) - val format = MediaFormat.createVideoFormat(mimeType, 1920, 1080).apply { + val mc = createBestLowLatencyDecoder(mimeType) + val format = MediaFormat.createVideoFormat(mimeType, 1280, 720).apply { setInteger(MediaFormat.KEY_LOW_LATENCY, 1) setInteger(MediaFormat.KEY_PRIORITY, 0) // Temps réel setInteger(MediaFormat.KEY_OPERATING_RATE, Short.MAX_VALUE.toInt()) - // Clé matérielle Qualcomm (Snapdragon 8 Gen 1 / Tab S8 Ultra) pour zéro frame buffering + // Clés matérielles Qualcomm (Snapdragon 8 Gen 1 / Tab S8 Ultra) : zéro buffering + sortie en ordre de décodage setInteger("vendor.qti-ext-dec-low-latency.enable", 1) + setInteger("vendor.qti-ext-dec-picture-order.enable", 1) } mc.configure(format, targetSurface, null, 0) mc.start() @@ -93,7 +125,7 @@ class LowLatencyVideoDecoder(private val context: Context) { priority = Thread.MAX_PRIORITY start() } - Log.i(TAG, "MediaCodec démarré ($mimeType, Low-Latency Snapdragon actif)") + Log.i(TAG, "MediaCodec démarré (${mc.name}, $mimeType, Low-Latency + Picture-Order actif)") } catch (e: Exception) { Log.e(TAG, "Échec initialisation MediaCodec ($mimeType): ${e.message}") releaseCodecLocked() @@ -159,8 +191,8 @@ class LowLatencyVideoDecoder(private val context: Context) { try { val outIdx = mc.dequeueOutputBuffer(info, 10_000) if (outIdx >= 0) { - // render = true -> affichage immédiat sur SurfaceView sans attente de PTS (latence minimale) - mc.releaseOutputBuffer(outIdx, true) + // Présentation immédiate sur le tout prochain VSync 120 Hz (zéro attente PTS) + mc.releaseOutputBuffer(outIdx, System.nanoTime()) } } catch (_: IllegalStateException) { break