fix(openxr): graceful session exit, child-first teardown & clean Vulkan device destruction

This commit is contained in:
bleackstorm committed 2026-11-06 23:42:39 +01:00
1 parent dc6d796300
commit 378332b892
4 files changed
+190 -44

No files matched your search

+109 -23
View File
@@ -547,11 +547,13 @@ fn try_run_openxr_session(
); );
let mut composited_rgba = vec![0u8; (cfg.video_width * cfg.video_height * 4) as usize]; let mut composited_rgba = vec![0u8; (cfg.video_width * cfg.video_height * 4) as usize];
let local_space = vk_xr let session = vk_xr
.session .session
.as_ref()
.context("Session OpenXR non initialisée")?;
let local_space = session
.create_reference_space(xr::ReferenceSpaceType::LOCAL, xr::Posef::IDENTITY)?; .create_reference_space(xr::ReferenceSpaceType::LOCAL, xr::Posef::IDENTITY)?;
let view_space = vk_xr let view_space = session
.session
.create_reference_space(xr::ReferenceSpaceType::VIEW, xr::Posef::IDENTITY)?; .create_reference_space(xr::ReferenceSpaceType::VIEW, xr::Posef::IDENTITY)?;
let aspect = cfg.video_width as f32 / cfg.video_height as f32; let aspect = cfg.video_width as f32 / cfg.video_height as f32;
@@ -561,19 +563,59 @@ fn try_run_openxr_session(
let mut event_storage = xr::EventDataBuffer::new(); let mut event_storage = xr::EventDataBuffer::new();
let mut session_running = false; let mut session_running = false;
let mut exiting = false;
let mut exit_deadline: Option<Instant> = None;
let mut first_pose = true; let mut first_pose = true;
let mut standby_tick: u32 = 0; let mut standby_tick: u32 = 0;
let mut fps_counter: u32 = 0; let mut fps_counter: u32 = 0;
let mut fps_timer = Instant::now(); let mut fps_timer = Instant::now();
let mut last_frame_id: u64 = 0; let mut last_frame_id: u64 = 0;
while !stop_flag.load(Ordering::Relaxed) { while !stop_flag.load(Ordering::Relaxed) || session_running {
let telem_on = telem_enabled_flag.load(Ordering::Relaxed); let telem_on = telem_enabled_flag.load(Ordering::Relaxed);
sync_telemetry_receiver(cfg, telem_on, telem_rx_opt, monitor); sync_telemetry_receiver(cfg, telem_on, telem_rx_opt, monitor);
let ht_on = ht_enabled_flag.load(Ordering::Relaxed); let ht_on = ht_enabled_flag.load(Ordering::Relaxed);
sync_head_tracker(cfg, ht_on, head_tracker_opt, monitor); sync_head_tracker(cfg, ht_on, head_tracker_opt, monitor);
// Si l'arrêt de l'application est demandé et que la session tourne encore, notifier proprement le runtime
if stop_flag.load(Ordering::Relaxed) && !exiting {
exiting = true;
exit_deadline = Some(Instant::now() + Duration::from_millis(1500));
log::info!("[OpenXR] Arrêt demandé, notification du runtime (request_exit)...");
if let Some(ref s) = vk_xr.session {
match s.request_exit() {
Ok(()) => {}
Err(xr::sys::Result::ERROR_SESSION_NOT_RUNNING) => {
session_running = false;
break;
}
Err(e) => {
log::warn!("[OpenXR] Erreur lors de request_exit : {}", e);
break;
}
}
} else {
break;
}
}
// Si en cours de sortie et dépassement du délai de grâce
if exiting {
if let Some(deadline) = exit_deadline {
if Instant::now() > deadline {
log::warn!("[OpenXR] Timeout attente transition STOPPING, fin de session forcée.");
if session_running {
if let Some(ref s) = vk_xr.session {
let _ = s.end();
}
session_running = false;
}
break;
}
}
}
while let Some(event) = instance.poll_event(&mut event_storage)? { while let Some(event) = instance.poll_event(&mut event_storage)? {
use xr::Event::*; use xr::Event::*;
match event { match event {
@@ -581,17 +623,26 @@ fn try_run_openxr_session(
log::info!("[OpenXR] Changement d'état session : {:?}", e.state()); log::info!("[OpenXR] Changement d'état session : {:?}", e.state());
match e.state() { match e.state() {
xr::SessionState::READY => { xr::SessionState::READY => {
vk_xr if !exiting {
.session if let Some(ref s) = vk_xr.session {
.begin(xr::ViewConfigurationType::PRIMARY_STEREO)?; s.begin(xr::ViewConfigurationType::PRIMARY_STEREO)?;
session_running = true; session_running = true;
}
}
} }
xr::SessionState::STOPPING => { xr::SessionState::STOPPING => {
vk_xr.session.end()?; log::info!("[OpenXR] État STOPPING reçu, appel de session.end()...");
if let Some(ref s) = vk_xr.session {
let _ = s.end();
}
session_running = false; session_running = false;
if exiting {
break;
}
} }
xr::SessionState::EXITING | xr::SessionState::LOSS_PENDING => { xr::SessionState::EXITING | xr::SessionState::LOSS_PENDING => {
return Ok(()); session_running = false;
break;
} }
_ => {} _ => {}
} }
@@ -599,18 +650,29 @@ fn try_run_openxr_session(
ReferenceSpaceChangePending(_) => { ReferenceSpaceChangePending(_) => {
first_pose = true; first_pose = true;
} }
InstanceLossPending(_) => return Ok(()), InstanceLossPending(_) => {
session_running = false;
break;
}
_ => {} _ => {}
} }
} }
if !session_running { if !session_running || exiting {
thread::sleep(Duration::from_millis(10)); thread::sleep(Duration::from_millis(10));
continue; continue;
} }
let xr_frame_state = vk_xr.frame_wait.wait()?; let xr_frame_state = vk_xr
vk_xr.frame_stream.begin()?; .frame_wait
.as_mut()
.ok_or_else(|| anyhow::anyhow!("FrameWaiter absent"))?
.wait()?;
let frame_stream = vk_xr
.frame_stream
.as_mut()
.ok_or_else(|| anyhow::anyhow!("FrameStream absent"))?;
frame_stream.begin()?;
let location = view_space.locate(&local_space, xr_frame_state.predicted_display_time)?; let location = view_space.locate(&local_space, xr_frame_state.predicted_display_time)?;
let mut current_pose = HeadPoseSample::default(); let mut current_pose = HeadPoseSample::default();
@@ -634,11 +696,15 @@ fn try_run_openxr_session(
} }
if !xr_frame_state.should_render { if !xr_frame_state.should_render {
vk_xr.frame_stream.end( vk_xr
xr_frame_state.predicted_display_time, .frame_stream
xr::EnvironmentBlendMode::OPAQUE, .as_mut()
&[], .unwrap()
)?; .end(
xr_frame_state.predicted_display_time,
xr::EnvironmentBlendMode::OPAQUE,
&[],
)?;
continue; continue;
} }
@@ -725,8 +791,12 @@ fn try_run_openxr_session(
mon.preview_frame_seq = mon.preview_frame_seq.wrapping_add(1); mon.preview_frame_seq = mon.preview_frame_seq.wrapping_add(1);
} }
let swapchain_ref = vk_xr
.swapchain
.as_ref()
.ok_or_else(|| anyhow::anyhow!("Swapchain absent"))?;
let sub_image = xr::SwapchainSubImage::new() let sub_image = xr::SwapchainSubImage::new()
.swapchain(&vk_xr.swapchain) .swapchain(swapchain_ref)
.image_array_index(0) .image_array_index(0)
.image_rect(xr::Rect2Di { .image_rect(xr::Rect2Di {
offset: xr::Offset2Di { x: 0, y: 0 }, offset: xr::Offset2Di { x: 0, y: 0 },
@@ -736,6 +806,10 @@ fn try_run_openxr_session(
}, },
}); });
let frame_stream = vk_xr
.frame_stream
.as_mut()
.ok_or_else(|| anyhow::anyhow!("FrameStream absent"))?;
match active_proj { match active_proj {
ProjectionMode::Dome140 => { ProjectionMode::Dome140 => {
let equirect_layer = xr::CompositionLayerEquirect2KHR::new() let equirect_layer = xr::CompositionLayerEquirect2KHR::new()
@@ -748,7 +822,7 @@ fn try_run_openxr_session(
.upper_vertical_angle(half_vert_fov_rad) .upper_vertical_angle(half_vert_fov_rad)
.lower_vertical_angle(-half_vert_fov_rad); .lower_vertical_angle(-half_vert_fov_rad);
vk_xr.frame_stream.end( frame_stream.end(
xr_frame_state.predicted_display_time, xr_frame_state.predicted_display_time,
xr::EnvironmentBlendMode::OPAQUE, xr::EnvironmentBlendMode::OPAQUE,
&[&equirect_layer], &[&equirect_layer],
@@ -764,7 +838,7 @@ fn try_run_openxr_session(
.central_angle(horizontal_fov_rad) .central_angle(horizontal_fov_rad)
.aspect_ratio(aspect); .aspect_ratio(aspect);
vk_xr.frame_stream.end( frame_stream.end(
xr_frame_state.predicted_display_time, xr_frame_state.predicted_display_time,
xr::EnvironmentBlendMode::OPAQUE, xr::EnvironmentBlendMode::OPAQUE,
&[&cylinder_layer], &[&cylinder_layer],
@@ -790,7 +864,7 @@ fn try_run_openxr_session(
height: screen_height_m, height: screen_height_m,
}); });
vk_xr.frame_stream.end( frame_stream.end(
xr_frame_state.predicted_display_time, xr_frame_state.predicted_display_time,
xr::EnvironmentBlendMode::OPAQUE, xr::EnvironmentBlendMode::OPAQUE,
&[&quad_layer], &[&quad_layer],
@@ -799,6 +873,18 @@ fn try_run_openxr_session(
} }
} }
if session_running {
log::warn!("[OpenXR] Sortie de boucle avec session encore active, appel de session.end()...");
if let Some(ref s) = vk_xr.session {
let _ = s.end();
}
}
// Libération stricte dans l'ordre hiérarchique : Espaces -> Swapchain/Session -> Vulkan
drop(view_space);
drop(local_space);
drop(vk_xr);
Ok(()) Ok(())
} }
+5
View File
@@ -187,6 +187,11 @@ impl SteamFrameGuiApp {
} }
impl eframe::App for SteamFrameGuiApp { impl eframe::App for SteamFrameGuiApp {
fn on_exit(&mut self, _gl: Option<&eframe::glow::Context>) {
log::info!("[eframe] Fermeture de la fenêtre principale, arrêt propre du moteur FPV...");
self.engine.stop();
}
fn update(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) { fn update(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
ctx.request_repaint_after(Duration::from_millis(16)); ctx.request_repaint_after(Duration::from_millis(16));
+34 -9
View File
@@ -69,14 +69,14 @@ pub struct SteamFrameGpuiApp {
} }
impl SteamFrameGpuiApp { impl SteamFrameGpuiApp {
pub fn new(cfg: AppConfig, log_buffer: Arc<Mutex<LogBuffer>>) -> Self { pub fn new(
cfg: AppConfig,
log_buffer: Arc<Mutex<LogBuffer>>,
engine: Arc<Mutex<FpvEngineController>>,
controls: EngineControlHandle,
engine_monitor: Arc<Mutex<RuntimeMonitor>>,
) -> Self {
let log_revision = log_buffer.lock().revision.clone(); let log_revision = log_buffer.lock().revision.clone();
let mut engine =
FpvEngineController::new(cfg.telemetry_enabled, cfg.head_tracking_enabled);
engine.start(cfg.clone());
let controls = engine.control_handle();
let engine_monitor = Arc::clone(&engine.monitor);
let engine = Arc::new(Mutex::new(engine));
Self { Self {
cfg, cfg,
@@ -285,6 +285,13 @@ impl SteamFrameGpuiApp {
} }
} }
impl Drop for SteamFrameGpuiApp {
fn drop(&mut self) {
log::info!("[SteamFrameGpuiApp] Fermeture de l'interface IHM, arrêt propre du moteur FPV...");
self.engine.lock().stop();
}
}
impl Render for SteamFrameGpuiApp { impl Render for SteamFrameGpuiApp {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement { fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
div() div()
@@ -1706,8 +1713,18 @@ impl SteamFrameGpuiApp {
pub fn run_gpui_app(cfg: AppConfig, log_buffer: Arc<Mutex<LogBuffer>>) -> Result<()> { pub fn run_gpui_app(cfg: AppConfig, log_buffer: Arc<Mutex<LogBuffer>>) -> Result<()> {
Application::new().run(move |cx: &mut App| { Application::new().run(move |cx: &mut App| {
cx.on_window_closed(|cx| { let mut engine =
FpvEngineController::new(cfg.telemetry_enabled, cfg.head_tracking_enabled);
engine.start(cfg.clone());
let controls = engine.control_handle();
let engine_monitor = Arc::clone(&engine.monitor);
let engine = Arc::new(Mutex::new(engine));
let engine_for_close = Arc::clone(&engine);
cx.on_window_closed(move |cx| {
if cx.windows().is_empty() { if cx.windows().is_empty() {
log::info!("[GPUI] Dernière fenêtre fermée, arrêt propre et complet du moteur FPV...");
engine_for_close.lock().stop();
cx.quit(); cx.quit();
} }
}) })
@@ -1723,7 +1740,15 @@ pub fn run_gpui_app(cfg: AppConfig, log_buffer: Arc<Mutex<LogBuffer>>) -> Result
}, },
|window, cx| { |window, cx| {
// Création du modèle réactif de l'application // Création du modèle réactif de l'application
let app_view = cx.new(|_| SteamFrameGpuiApp::new(cfg.clone(), log_buffer.clone())); let app_view = cx.new(|_| {
SteamFrameGpuiApp::new(
cfg.clone(),
log_buffer.clone(),
engine,
controls,
engine_monitor,
)
});
// Boucle de rafraîchissement 60 FPS synchronisée avec le moteur FPV // Boucle de rafraîchissement 60 FPS synchronisée avec le moteur FPV
let weak_view = app_view.downgrade(); let weak_view = app_view.downgrade();
+42 -12
View File
@@ -19,11 +19,11 @@ pub struct VulkanXrContext {
pub staging_memory: vk::DeviceMemory, pub staging_memory: vk::DeviceMemory,
pub staging_mapped_ptr: *mut u8, pub staging_mapped_ptr: *mut u8,
pub staging_size: usize, pub staging_size: usize,
pub session: xr::Session<xr::Vulkan>, pub swapchain: Option<xr::Swapchain<xr::Vulkan>>,
pub frame_wait: xr::FrameWaiter,
pub frame_stream: xr::FrameStream<xr::Vulkan>,
pub swapchain: xr::Swapchain<xr::Vulkan>,
pub swapchain_images: Vec<vk::Image>, pub swapchain_images: Vec<vk::Image>,
pub frame_stream: Option<xr::FrameStream<xr::Vulkan>>,
pub frame_wait: Option<xr::FrameWaiter>,
pub session: Option<xr::Session<xr::Vulkan>>,
pub width: u32, pub width: u32,
pub height: u32, pub height: u32,
} }
@@ -244,10 +244,10 @@ impl VulkanXrContext {
staging_memory, staging_memory,
staging_mapped_ptr, staging_mapped_ptr,
staging_size, staging_size,
session, session: Some(session),
frame_wait, frame_wait: Some(frame_wait),
frame_stream, frame_stream: Some(frame_stream),
swapchain, swapchain: Some(swapchain),
swapchain_images, swapchain_images,
width, width,
height, height,
@@ -256,8 +256,12 @@ impl VulkanXrContext {
/// Copie les pixels RGBA de la frame vidéo dans l'image active du Swapchain OpenXR /// Copie les pixels RGBA de la frame vidéo dans l'image active du Swapchain OpenXR
pub fn upload_rgba_to_swapchain(&mut self, rgba_bytes: &[u8]) -> Result<()> { pub fn upload_rgba_to_swapchain(&mut self, rgba_bytes: &[u8]) -> Result<()> {
let img_idx = self.swapchain.acquire_image()?; let swapchain = self
self.swapchain.wait_image(xr::Duration::INFINITE)?; .swapchain
.as_mut()
.ok_or_else(|| anyhow!("Swapchain OpenXR indisponible"))?;
let img_idx = swapchain.acquire_image()?;
swapchain.wait_image(xr::Duration::INFINITE)?;
let copy_len = rgba_bytes.len().min(self.staging_size); let copy_len = rgba_bytes.len().min(self.staging_size);
unsafe { unsafe {
@@ -357,20 +361,46 @@ impl VulkanXrContext {
.wait_for_fences(&[self.upload_fence], true, u64::MAX)?; .wait_for_fences(&[self.upload_fence], true, u64::MAX)?;
} }
self.swapchain.release_image()?; swapchain.release_image()?;
Ok(()) Ok(())
} }
} }
impl Drop for VulkanXrContext { impl Drop for VulkanXrContext {
fn drop(&mut self) { fn drop(&mut self) {
log::info!("[VulkanXrContext] Nettoyage ordonné des ressources OpenXR et Vulkan...");
unsafe { unsafe {
// 1. Attendre l'inactivité complète de la file GPU
let _ = self.vk_device.device_wait_idle(); let _ = self.vk_device.device_wait_idle();
self.vk_device.unmap_memory(self.staging_memory);
// 2. Détruire le swapchain OpenXR EN PREMIER (doit impérativement précéder la destruction de la session)
drop(self.swapchain.take());
self.swapchain_images.clear();
// 3. Détruire frame_stream et frame_wait
drop(self.frame_stream.take());
drop(self.frame_wait.take());
// 4. Détruire la session OpenXR (doit impérativement être détruite avant le VkDevice)
drop(self.session.take());
// 5. Attendre que le runtime et le pilote Vulkan aient achevé leurs libérations
let _ = self.vk_device.device_wait_idle();
// 6. Libérer les ressources de staging Vulkan
if !self.staging_mapped_ptr.is_null() {
self.vk_device.unmap_memory(self.staging_memory);
self.staging_mapped_ptr = std::ptr::null_mut();
}
self.vk_device.destroy_buffer(self.staging_buffer, None); self.vk_device.destroy_buffer(self.staging_buffer, None);
self.vk_device.free_memory(self.staging_memory, None); self.vk_device.free_memory(self.staging_memory, None);
self.vk_device.destroy_fence(self.upload_fence, None); self.vk_device.destroy_fence(self.upload_fence, None);
self.vk_device.destroy_command_pool(self.command_pool, None); self.vk_device.destroy_command_pool(self.command_pool, None);
// 7. Détruire le VkDevice et le VkInstance (conformément à XR_KHR_vulkan_enable2)
self.vk_device.destroy_device(None);
self.vk_instance.destroy_instance(None);
log::info!("[VulkanXrContext] Ressources OpenXR/Vulkan libérées proprement.");
} }
} }
} }