mirror of
https://github.com/nestriness/nestri.git
synced 2026-12-04 04:56:21 +02:00
MSG_WINDOW_PAUSE and MSG_WINDOW_RESUME on the control stream. The hub sends them to the encoder of the window the client is shown; nescapture stops capturing in the present hook while paused, and resume requests a keyframe.
477 lines
18 KiB
Rust
477 lines
18 KiB
Rust
use crate::capture;
|
|
use crate::encode::{CapturedFrame, FrameSource, PipelineConfig, PipelineHandle, PresentStep};
|
|
use crate::slots::SlotGuard;
|
|
use crate::state::{DEVICE_STATE, QUEUE_TO_DEVICE_KEY};
|
|
use ash::vk::{self, Handle};
|
|
use std::os::raw::c_void;
|
|
use std::sync::atomic::Ordering;
|
|
|
|
#[unsafe(no_mangle)]
|
|
pub unsafe extern "system" fn vkQueuePresentKHR(
|
|
queue: vk::Queue,
|
|
p_present_info: *const vk::PresentInfoKHR,
|
|
) -> vk::Result {
|
|
let ds = {
|
|
let dk = unsafe { crate::dispatch_key(queue.as_raw() as *const c_void) };
|
|
DEVICE_STATE
|
|
.get(&dk)
|
|
.map(|r| r.clone())
|
|
.or_else(|| {
|
|
QUEUE_TO_DEVICE_KEY
|
|
.get(&queue.as_raw())
|
|
.and_then(|dk| DEVICE_STATE.get(dk.value()).map(|r| r.clone()))
|
|
})
|
|
.or_else(|| DEVICE_STATE.iter().next().map(|e| e.value().clone()))
|
|
};
|
|
let ds = match ds {
|
|
Some(d) => d,
|
|
None => return vk::Result::ERROR_DEVICE_LOST,
|
|
};
|
|
|
|
// Entry. `gap` is measured from where the previous present *returned*, so
|
|
// it is the game's own frame time with this layer's cost excluded — the
|
|
// three spans then partition the wall clock between presents exactly.
|
|
let entered = std::time::Instant::now();
|
|
note_present(&ds, PresentStep::InHook);
|
|
|
|
ds.frame_counter.fetch_add(1, Ordering::Relaxed);
|
|
ds.hud_detected_frame.store(false, Ordering::Relaxed);
|
|
ds.pending_capture_frame.store(false, Ordering::Relaxed);
|
|
ds.capture_injected_frame.store(false, Ordering::Relaxed);
|
|
ds.skipped_draws_frame.store(0, Ordering::Relaxed);
|
|
|
|
if let Ok(enc) = ds.encoder.lock()
|
|
&& let Some(ref h) = *enc
|
|
{
|
|
h.present_attempts.fetch_add(1, Ordering::Relaxed);
|
|
if let Ok(prev) = ds.last_present_return.lock()
|
|
&& let Some(prev) = *prev
|
|
{
|
|
h.timing.record_gap(entered.saturating_duration_since(prev));
|
|
}
|
|
}
|
|
|
|
let pi = unsafe { &*p_present_info };
|
|
|
|
// Rewriting the wait semaphores is only well defined for a single
|
|
// swapchain. A multi-swapchain present is rare enough that passing it
|
|
// through untouched beats getting the interposition subtly wrong.
|
|
let single_swapchain =
|
|
pi.swapchain_count == 1 && !pi.p_swapchains.is_null() && !pi.p_image_indices.is_null();
|
|
|
|
let submission = if single_swapchain {
|
|
unsafe { try_capture(&ds, queue, pi) }
|
|
} else {
|
|
None
|
|
};
|
|
|
|
let down_us = std::cell::Cell::new(std::time::Duration::ZERO);
|
|
let call_down = |info: *const vk::PresentInfoKHR| match ds.fp.queue_present_khr {
|
|
Some(f) => {
|
|
note_present(&ds, PresentStep::Presenting);
|
|
let t = std::time::Instant::now();
|
|
let r = unsafe { f(queue, info) };
|
|
down_us.set(t.elapsed());
|
|
note_present(&ds, PresentStep::InHook);
|
|
r
|
|
}
|
|
None => vk::Result::ERROR_EXTENSION_NOT_PRESENT,
|
|
};
|
|
|
|
let Some(submission) = submission else {
|
|
let r = call_down(p_present_info);
|
|
finish(&ds, entered, down_us.get());
|
|
return r;
|
|
};
|
|
|
|
// The blit consumed the application's wait semaphores, so the present waits
|
|
// on ours instead. Presenting on the originals as well would be a second
|
|
// wait on an already-consumed signal.
|
|
let wait = submission.present_wait;
|
|
let rewritten = vk::PresentInfoKHR {
|
|
s_type: pi.s_type,
|
|
p_next: pi.p_next,
|
|
wait_semaphore_count: 1,
|
|
p_wait_semaphores: &wait,
|
|
swapchain_count: pi.swapchain_count,
|
|
p_swapchains: pi.p_swapchains,
|
|
p_image_indices: pi.p_image_indices,
|
|
p_results: pi.p_results,
|
|
_marker: std::marker::PhantomData,
|
|
};
|
|
|
|
let image_index = unsafe { *pi.p_image_indices } as usize;
|
|
let result = call_down(&rewritten);
|
|
|
|
// Only hand the frame on once the present has been accepted. A failed
|
|
// present drops the job, which returns the slot.
|
|
if matches!(result, vk::Result::SUCCESS | vk::Result::SUBOPTIMAL_KHR) {
|
|
queue_for_encode(&ds, submission);
|
|
} else {
|
|
// The blit signalled this semaphore; whether the failed present waited
|
|
// on it is undefined. Set it aside rather than signal it twice.
|
|
capture::retire_present_semaphore(&ds, image_index);
|
|
}
|
|
|
|
finish(&ds, entered, down_us.get());
|
|
result
|
|
}
|
|
|
|
/// Close out a present: record what this layer cost and stamp the return.
|
|
///
|
|
/// `layer` is everything in this hook that is not the down-call, both sides of
|
|
/// it added together, so `gap + layer + down` accounts for the wall clock
|
|
/// between one present and the next with nothing unattributed.
|
|
fn finish(ds: &crate::state::DeviceState, entered: std::time::Instant, down: std::time::Duration) {
|
|
// Everything this hook cost, before any deliberate waiting.
|
|
let worked = std::time::Instant::now();
|
|
|
|
// Hold the game to the target rate. *After* the down-call, so the frame
|
|
// went out the moment it was ready and this only keeps the application
|
|
// from starting the next one — the cadence without the latency.
|
|
let held = match ds.frame_pacer.lock() {
|
|
Ok(mut pacer) => pacer.hold(worked),
|
|
// A poisoned pacer must not wedge the game.
|
|
Err(_) => std::time::Duration::ZERO,
|
|
};
|
|
if !held.is_zero() {
|
|
note_present(ds, PresentStep::Holding);
|
|
// Absolute deadline, not a duration
|
|
crate::pacing::sleep_until(worked + held);
|
|
}
|
|
|
|
let now = std::time::Instant::now();
|
|
// What the sleep actually cost, not what it asked for. `thread::sleep`
|
|
// guarantees a floor and nothing else: on a box whose CPUs are all busy,
|
|
// waking is a scheduling decision and the overshoot can be many times the
|
|
// request. Recording the request would hide exactly the case worth seeing,
|
|
// and the overshoot lands nowhere else — the present-return is stamped
|
|
// after it, so `gap` cannot show it either.
|
|
let held = now.saturating_duration_since(worked);
|
|
if let Ok(enc) = ds.encoder.lock()
|
|
&& let Some(ref h) = *enc
|
|
{
|
|
// `layer` is this layer's cost, so the hold comes out of it: it is
|
|
// time spent on purpose, not overhead.
|
|
h.timing.layer.record(
|
|
worked
|
|
.saturating_duration_since(entered)
|
|
.saturating_sub(down),
|
|
);
|
|
h.timing.down.record(down);
|
|
h.timing.hold.record(held);
|
|
}
|
|
// Stamped after the hold, so the next frame's `gap` is the game's own
|
|
// work and not the waiting this layer asked it to do.
|
|
if let Ok(mut last) = ds.last_present_return.lock() {
|
|
*last = Some(now);
|
|
}
|
|
note_present(ds, PresentStep::InGame);
|
|
}
|
|
|
|
/// Tell the stall watchdog where the game's present thread is. A no-op until
|
|
/// the pipeline exists.
|
|
pub fn note_present(ds: &crate::state::DeviceState, step: PresentStep) {
|
|
if let Ok(enc) = ds.encoder.lock()
|
|
&& let Some(ref h) = *enc
|
|
{
|
|
h.note_present(step);
|
|
}
|
|
}
|
|
|
|
/// Everything the present hook needs to carry from the blit to the worker.
|
|
struct Submission {
|
|
slot: SlotGuard,
|
|
present_wait: vk::Semaphore,
|
|
blit: Option<pixelforge::TimelinePoint>,
|
|
width: u32,
|
|
height: u32,
|
|
sc_fmt: vk::Format,
|
|
present_time: std::time::Instant,
|
|
}
|
|
|
|
unsafe fn try_capture(
|
|
ds: &crate::state::DeviceState,
|
|
queue: vk::Queue,
|
|
pi: &vk::PresentInfoKHR,
|
|
) -> Option<Submission> {
|
|
let image_index = unsafe { *pi.p_image_indices } as usize;
|
|
// An image acquired from a retired swapchain may still be presented, and
|
|
// the tracked images belong to its replacement: the same index there is a
|
|
// different image, possibly of a different size.
|
|
let presented = unsafe { *pi.p_swapchains };
|
|
if !crate::swapchain::is_current(*ds.swapchain.lock().ok()?, presented) {
|
|
return None;
|
|
}
|
|
let (sc_image, sc_fmt, sc_ext, image_count) = {
|
|
let images = ds.swapchain_images.lock().ok()?;
|
|
let fmt = *ds.swapchain_format.lock().ok()?;
|
|
let ext = *ds.swapchain_extent.lock().ok()?;
|
|
if image_index >= images.len() || ext.width == 0 || ext.height == 0 {
|
|
return None;
|
|
}
|
|
(images[image_index], fmt, ext, images.len())
|
|
};
|
|
|
|
// A paused window captures nothing (ref d-0087): no blit, no slot, no
|
|
// encode. Before the gate, so the gate's own bookkeeping does not run
|
|
// either, and the frame the client resumes on is a fresh one.
|
|
if let Ok(enc) = ds.encoder.lock()
|
|
&& let Some(ref h) = *enc
|
|
&& h.is_paused()
|
|
{
|
|
h.note_paused();
|
|
return None;
|
|
}
|
|
|
|
// Gate before any GPU work is queued. A game presenting faster than the
|
|
// target would otherwise pay a full blit for frames the
|
|
// encoder throws away moments later.
|
|
let present_time = std::time::Instant::now();
|
|
let admitted = match ds.frame_gate.lock() {
|
|
Ok(mut gate) => gate.admit(present_time),
|
|
// A poisoned gate must not stop the stream; capture everything.
|
|
Err(_) => true,
|
|
};
|
|
if !admitted {
|
|
return None;
|
|
}
|
|
|
|
// Before the blit, not after it. A frame captured with nowhere to send it
|
|
// costs a slot, a copy and an export for nothing.
|
|
let ds_key = unsafe { crate::dispatch_key(ds.raw.as_raw() as *const c_void) };
|
|
if !encoder_ready(ds, ds_key, sc_ext.width, sc_ext.height) {
|
|
return None;
|
|
}
|
|
|
|
if let Ok(enc) = ds.encoder.lock() {
|
|
if let Some(ref h) = *enc {
|
|
h.capture_attempts.fetch_add(1, Ordering::Relaxed);
|
|
}
|
|
}
|
|
|
|
let app_waits: &[vk::Semaphore] =
|
|
if pi.wait_semaphore_count == 0 || pi.p_wait_semaphores.is_null() {
|
|
&[]
|
|
} else {
|
|
unsafe {
|
|
std::slice::from_raw_parts(pi.p_wait_semaphores, pi.wait_semaphore_count as usize)
|
|
}
|
|
};
|
|
|
|
let submission = unsafe {
|
|
capture::capture_present_frame(
|
|
ds,
|
|
queue,
|
|
sc_image,
|
|
sc_fmt,
|
|
sc_ext,
|
|
image_index,
|
|
image_count,
|
|
app_waits,
|
|
)
|
|
}?;
|
|
|
|
Some(Submission {
|
|
slot: submission.slot,
|
|
present_wait: submission.present_wait,
|
|
blit: submission.blit,
|
|
width: sc_ext.width,
|
|
height: sc_ext.height,
|
|
sc_fmt,
|
|
present_time,
|
|
})
|
|
}
|
|
|
|
fn queue_for_encode(ds: &crate::state::DeviceState, submission: Submission) {
|
|
let ds_key = unsafe { crate::dispatch_key(ds.raw.as_raw() as *const c_void) };
|
|
|
|
let Ok(enc) = ds.encoder.lock() else {
|
|
return;
|
|
};
|
|
let Some(handle) = enc.as_ref() else {
|
|
return;
|
|
};
|
|
// `push_frame` is a `try_send`, so this never blocks the game's thread. A
|
|
// refused frame is dropped and its slot goes back when the `CapturedFrame`
|
|
// does, which is the backpressure the ring was always providing.
|
|
handle.push_frame(CapturedFrame {
|
|
ds_key,
|
|
width: submission.width,
|
|
height: submission.height,
|
|
vk_format: submission.sc_fmt.as_raw() as u32,
|
|
vk_colorspace: ds.swapchain_colorspace.load(Ordering::Relaxed),
|
|
present_time: submission.present_time,
|
|
slot: Some(submission.slot),
|
|
blit: submission.blit,
|
|
});
|
|
}
|
|
|
|
/// Make sure the encode pipeline exists, without building it here.
|
|
///
|
|
/// Returns false until it is ready, and the frame is simply not captured. The
|
|
/// build opens a pixelforge `VideoContext` and starts four threads; doing that
|
|
/// on the game's present thread would be a visible hitch on the first frame,
|
|
/// and doing it after a blit would waste one. It runs once, on a thread of its
|
|
/// own, and frames presented in the meantime are skipped before any GPU work is
|
|
/// queued for them.
|
|
fn encoder_ready(ds: &crate::state::DeviceState, ds_key: usize, width: u32, height: u32) -> bool {
|
|
if let Ok(enc) = ds.encoder.lock() {
|
|
if enc.is_some() {
|
|
return true;
|
|
}
|
|
}
|
|
if ds.encoder_starting.swap(true, Ordering::SeqCst) {
|
|
return false;
|
|
}
|
|
std::thread::Builder::new()
|
|
.name("nescapture-encoder-init".into())
|
|
.spawn(move || {
|
|
let Some(ds) = DEVICE_STATE.get(&ds_key).map(|s| s.clone()) else {
|
|
return;
|
|
};
|
|
let Some(cfg) = PipelineConfig::from_env(width, height) else {
|
|
log::error!("no encode pipeline configuration; capture disabled");
|
|
return;
|
|
};
|
|
// On the game's own device where it was created for that, and
|
|
// on a device of the encoder's own where it was not, or where
|
|
// adopting it fails.
|
|
// Each encoder the device was set up for is adopted on its own; a
|
|
// failure in one costs only that one. Only when neither is left
|
|
// does the encoder move to a device of its own, which can then
|
|
// host Vulkan Video and nothing else.
|
|
let shared = ds.shared.as_ref().and_then(|s| {
|
|
let video = s.video_context().and_then(|r| {
|
|
r.map_err(|e| log::warn!("Vulkan Video on the game's device failed ({e})"))
|
|
.ok()
|
|
});
|
|
let pyro = s.pyro_context().and_then(|r| {
|
|
r.map_err(|e| log::warn!("PyroWave on the game's device failed ({e})"))
|
|
.ok()
|
|
});
|
|
if video.is_none() && pyro.is_none() {
|
|
log::warn!("no encoder on the game's device; using a device of its own");
|
|
return None;
|
|
}
|
|
Some(crate::encode::SharedEncoders { video, pyro })
|
|
});
|
|
let on_shared = shared.is_some();
|
|
match PipelineHandle::new(cfg, shared) {
|
|
Ok(h) => {
|
|
h.set_stall_probe(Box::new(move || describe_gpu(ds_key)));
|
|
// Before the handle is published: the first capture after
|
|
// it builds the ring, and must build it for this device.
|
|
ds.shared_active.store(on_shared, Ordering::Release);
|
|
if let Ok(mut enc) = ds.encoder.lock() {
|
|
*enc = Some(h);
|
|
}
|
|
if on_shared {
|
|
log::info!("encoding on the game's own device");
|
|
}
|
|
}
|
|
Err(e) => log::error!("encode pipeline: {e}"),
|
|
}
|
|
})
|
|
.ok();
|
|
false
|
|
}
|
|
|
|
/// Turn a frame's slot into something the encoder reads.
|
|
///
|
|
/// On a device the encoder shares this is immediate: the slot's image is read
|
|
/// in place, and the encoder's GPU work waits on the blit's timeline point, so
|
|
/// nothing here waits at all.
|
|
///
|
|
/// Otherwise this is the CPU handover two devices need: pixelforge's `VkDevice`
|
|
/// shares no timeline with the game's, so no semaphore can bridge them and
|
|
/// somebody has to block. It used to be a thread of its own between the present
|
|
/// hook and the encoder; it is now the first thing the encoder thread does with
|
|
/// a frame, which costs that thread nothing — the blit it waits for was
|
|
/// submitted a whole frame earlier and has long since completed — and takes a
|
|
/// channel and a wakeup out of every frame's path.
|
|
pub fn resolve_source(
|
|
ds: &crate::state::DeviceState,
|
|
frame: &CapturedFrame,
|
|
) -> Option<FrameSource> {
|
|
let slot_index = frame.slot.as_ref()?.index();
|
|
|
|
if let Some(blit) = frame.blit {
|
|
let ring = ds.capture_ring.lock().ok()?;
|
|
let image = ring.as_ref()?.slots.get(slot_index)?.image;
|
|
return Some(FrameSource::Shared { image, blit });
|
|
}
|
|
|
|
// Copy the handles out and drop the ring lock before waiting: the present
|
|
// hook needs that lock every frame and must not queue behind a GPU wait.
|
|
let (fence, image, memory) = {
|
|
let ring = ds.capture_ring.lock().ok()?;
|
|
ring.as_ref()
|
|
.and_then(|r| r.slots.get(slot_index))
|
|
.map(|s| (s.fence, s.image, s.memory))?
|
|
};
|
|
|
|
let waited = unsafe { (ds.fp.wait_for_fences)(ds.raw, 1, &fence, vk::TRUE, 1_000_000_000) };
|
|
if waited != vk::Result::SUCCESS {
|
|
log::warn!("capture blit did not complete — frame dropped");
|
|
return None;
|
|
}
|
|
|
|
// After the fence, so the queries have landed and `WAIT` returns at once.
|
|
if let Some(ns) = unsafe { capture::blit_gpu_time_ns(ds, slot_index, true) }
|
|
&& let Ok(enc) = ds.encoder.lock()
|
|
&& let Some(ref h) = *enc
|
|
{
|
|
h.timing.blit.record(std::time::Duration::from_nanos(ns));
|
|
}
|
|
|
|
match unsafe { capture::read_frame_pixels(ds, image, memory, frame.width, frame.height) } {
|
|
Some(p) if !p.is_empty() => Some(FrameSource::Pixels(p)),
|
|
_ => None,
|
|
}
|
|
}
|
|
|
|
/// Whether the GPU has got through the capture work this layer gave it, for
|
|
/// the stall watchdog.
|
|
///
|
|
/// A blit is queued behind the game's frame on the game's own queue, so a blit
|
|
/// that never completes means that queue stopped: the game is waiting on the
|
|
/// GPU. One that did complete means the GPU finished everything in front of
|
|
/// it, and whatever the game is waiting for is not GPU work on that queue.
|
|
///
|
|
/// Never blocks. It runs exactly when something may be holding a lock forever.
|
|
fn describe_gpu(ds_key: usize) -> String {
|
|
let Some(ds) = DEVICE_STATE.get(&ds_key).map(|s| s.clone()) else {
|
|
return "device gone".into();
|
|
};
|
|
let slots = format!(
|
|
"{} of {} capture slots free",
|
|
ds.capture_slots.available(),
|
|
crate::state::CAPTURE_SLOTS
|
|
);
|
|
let Ok(ring) = ds.capture_ring.try_lock() else {
|
|
return format!("{slots}; capture ring locked");
|
|
};
|
|
let Some(ring) = ring.as_ref() else {
|
|
return format!("{slots}; no capture ring");
|
|
};
|
|
if let Some(shared) = ds.shared.as_ref()
|
|
&& !ring.blit_timeline.is_null()
|
|
{
|
|
let reached = shared
|
|
.counter(ring.blit_timeline)
|
|
.map_or("unknown".to_string(), |v| v.to_string());
|
|
return format!(
|
|
"{slots}; last blit submitted signals {}, the GPU has reached {reached}",
|
|
ring.blit_value
|
|
);
|
|
}
|
|
let pending = ring
|
|
.slots
|
|
.iter()
|
|
.filter(|s| unsafe { (ds.fp.wait_for_fences)(ds.raw, 1, &s.fence, vk::TRUE, 0) }
|
|
== vk::Result::TIMEOUT)
|
|
.count();
|
|
format!("{slots}; {pending} blits submitted and not yet complete")
|
|
}
|