mirror of
https://github.com/seedds/nxnative.git
synced 2026-11-23 11:39:42 -10:00
After a late frame, frames stayed queued for the screen at a cap the game held, and the lag never went away: one link tick with the display link (Ocarina of Time at a 30 fps cap in a window, 115 ms from the game's present to the screen), and a period per late present without it (100-153 ms). With the display link, the callback wakes the acquire and takes the queue in the same instant, and the in-order rule kept the catch-up frame standing. When every frame taken over 2 s had a spare tick while the game waited in its acquire, the next acquire now waits those ticks once (nvn_link_drain.h); nothing is dropped or repeated. A 30 fps target in a window keeps the 60 Hz link with the drain, where a frame waits half as long for its tick. Without it, the acquire handed a texture back once its present was committed, not shown, so nothing tied the host's clock to the screen. The acquire now waits until the game's present of DM_PRESENT_DEPTH (1) frames back is on screen or dropped, and the pacer takes the screen's phase after that wait. Reconciled and fixed here: - The frame step takes a drain out of a frame's time only past its hold (nvn_fstep_drain_cut). The screen wait stays in: it is the pacing, and a frame it stretches is a refresh the screen missed (taking it out made Mario Kart World run 0.983-0.992 of real time instead of 1.000). - The screen wait is off with present snapshots, as the drain is. - A screen that never reported a frame (newest seen 0) now counts as silent: 0 read as not silent, so every acquire waited two periods. - Depth 0 was measured and left out: a 60 fps cap ran 40 fps (Cuphead) and Mario Kart World stuck at 30, the present reaching the screen ~24 ms after the enqueue on an M4 Pro. Checked on an M4 Pro (ProMotion, macOS 27.2) with a 40 ms hitch every 600 frames: Cuphead, Fire Emblem: Three Houses and Mario Kart World in window, fullscreen at fixed 60 Hz and variable refresh, with and without the link; enqueue to screen 17-58 ms lower, every cap held. Tests: t_link_drain, t_fstep, t_link_ticks, t_present_rescue, check_t_present_snap, the full dm/gfx/tests suite, test_docs, test_env_switches. regress.py check on OCTOPATH TRAVELER II and Hades: PASS, no new red lines. Not checked: iOS, fixed-rate or external screens in a window, Ocarina of Time itself. Co-authored-by: Amost <[email protected]> Co-authored-by: David Padron-Harris <[email protected]>
This commit is contained in:
1 parent
8e7b9bf09a
commit
34ada0283e
17 files changed
+432
-20
No files matched your search
@@ -60,7 +60,7 @@ jobs:
|
||||
make GAME="$GAME" -j3 t_perf_order
|
||||
./t_perf_order --cpu 2>&1 | tee ../../../logs/t_perf_order.log
|
||||
make GAME="$GAME" -j3 perf-order-tsan 2>&1 | tee ../../../logs/t_perf_order-tsan.log
|
||||
tests="t_gfx_suspend t_capture t_dirty_slots t_dirty_race t_dirty_retire_race t_tex_layout t_pace t_fstep t_link_ticks t_cpu_tex t_hmap t_cover t_pso_skey t_refl t_rt_range_ro t_present_rescue t_gpuprof t_sparse_layout t_timestamp t_counter_clock t_rt_depth_ro t_rt_range_shape t_ub t_pso_pending t_vk_desc t_rec_draws t_ubc_wait t_thread_rt t_rt_comp"
|
||||
tests="t_gfx_suspend t_capture t_dirty_slots t_dirty_race t_dirty_retire_race t_tex_layout t_pace t_fstep t_link_drain t_link_ticks t_cpu_tex t_hmap t_cover t_pso_skey t_refl t_rt_range_ro t_present_rescue t_gpuprof t_sparse_layout t_timestamp t_counter_clock t_rt_depth_ro t_rt_range_shape t_ub t_pso_pending t_vk_desc t_rec_draws t_ubc_wait t_thread_rt t_rt_comp"
|
||||
make GAME="$GAME" -j3 $tests 2>&1 | tee ../../../logs/gfx-build.log
|
||||
failed=0
|
||||
for t in $tests; do
|
||||
|
||||
@@ -128,6 +128,8 @@ Its 37 kernels that correct samples, NDSR's network among them, gave about 0.25
|
||||
|
||||
## Found on this game
|
||||
|
||||
- [A frame standing in the present queue after a late frame](../../../docs/reference/frame-rate.md#a-frame-standing-in-the-present-queue-after-a-late-frame): fixed. With the display link on an M2 Pro's ProMotion screen, the title screen at the 30 fps cap in a window showed frames 115.4 ms after the game queued them, 65.4 ms with the drain and the 60 Hz link; in game at the 60 setting, 82-102 ms became 65-70 ms.
|
||||
- [Frames pile up for the screen at a cap the game holds, without the display link](../../../docs/reference/frame-rate.md#frames-pile-up-for-the-screen-at-a-cap-the-game-holds-without-the-display-link): fixed. With `DM_PRESENT_LINK=0` on the M2 Air, fullscreen, at the 30 fps cap frames reached the screen 109-155 ms after the game queued them; with the screen wait, 57-65 ms, with frame times unchanged (33.3 ms).
|
||||
- [A game's own upscaler drawn by MetalFX](../../../docs/reference/rendering.md#a-games-own-upscaler-drawn-by-metalfx): with `DM_UPSCALER=metalfx` its upscaler reads a whole R11G11B10F texture and writes another (1440x810 → 1920x1080, [PR #2559](https://github.com/seedds/nxnative/pull/2559)); MetalFX now reads the input as it is, and the output is still drawn back, because MetalFX's own R11G11B10F writes come out about 2.4 % darker. Not yet run in game on this branch (the work folder and its libraries are gone).
|
||||
- [Pipeline archive files left behind by a major system update](../../../docs/reference/shaders.md#pipeline-archive-files-left-behind-by-a-major-system-update): resolved ([pull request #2539](https://github.com/seedds/nxnative/pull/2539)). After macOS 26.6.2 to 27.2.1 on an M1 Pro, 57 archive files (1.68 GB) were refused at every start and the prebuild was taken as done, so its bases were built at the draws (53 stalls, 39 s, in 24 minutes); the refused files and the stamp now go, and the next start runs the prebuild again (13.4 minutes for the 34,649 pairs on an empty archive, once).
|
||||
- [A submission's commit read the whole storage-write page set](../../../docs/reference/frame-rate.md#a-submissions-commit-read-the-whole-storage-write-page-set): resolved. About 30 commits a frame each read the 16,384-slot set of pages its storage buffers wrote (256 KB); standing on the Kokiri Forest deck the submit thread went from 42.8–43.9k to 38.7–39.3k instructions per draw (M4 Pro, 640 draws a frame), with no change in frame time, which waits for the GPU there.
|
||||
|
||||
+33
-7
@@ -1882,14 +1882,25 @@ extern uint32_t mtl_present_qos(void);
|
||||
static _Atomic uint64_t g_frame;
|
||||
static uint64_t g_acq_wait_ns, g_pq_wait_ns; // Accumulated display-link wait / wait for the present queue to return inside acquire, recorded per frame at present (there can be several acquires within one frame)
|
||||
static uint64_t g_fs_start, g_fs_wait; // frame step (fstep_tick): when the first acquire after a present returned (the frame's start, 0 = none yet), and its pacing wait
|
||||
// The acquire's two waits for the screen, which the frame step and the pacer read differently:
|
||||
// - a drain of frames standing in the display link's queue (nvn_mtl.m mtl_link_drain_take_ns, nvn_link_drain.h) is extra: the screen showed every queued frame for its hold
|
||||
// meanwhile, so the part that made the frame longer than its hold is neither late nor time the game owes (fstep_tick, nvn_fstep_drain_cut). g_fs_drain: in the acquire that
|
||||
// starts the frame (part of g_fs_wait and of the time since the previous start); g_fs_drain_late: in a later acquire of the same frame (part of the time to the next start only)
|
||||
// - without the link, the wait until the screen shows the game's present of DM_PRESENT_DEPTH frames back (mtl_present_screen_wait) is the pacing itself, on nearly every frame
|
||||
// at a cap the game holds, and a frame it lengthens past its hold is one the screen showed late: it stays in the frame's time (taken out, as for a drain, it threw away the
|
||||
// screen's missed refreshes: Mario Kart World without the link ran 0.983-0.992 of real time against 1.000). The pacer starts again from its release (g_screen_at,
|
||||
// nvnQueuePresentTexture) instead of paying the wait back with short frames
|
||||
static uint64_t g_fs_drain, g_fs_drain_late;
|
||||
static _Atomic uint64_t g_screen_at; // when the screen wait released the acquire of the frame being made (0 = it did not wait since the last present): the pacer takes the screen's phase
|
||||
uint64_t dm_nvn_frame_count(void) { return g_frame; }
|
||||
extern uint64_t g_t0_ns; // Host process start point (main.c; same base as the UIMSG timestamps)
|
||||
uint64_t mtl_present_screen_wait(double period); // nvn_mtl.m
|
||||
NVN(nvnWindowAcquireTexture, NVNwindowAcquireTextureResult, NVNwindow *w, NVNsync *s, int *idx) {
|
||||
win_t *o = (win_t *)w;
|
||||
int n = window_active(o);
|
||||
*idx = n ? o->next++ % n : 0;
|
||||
// Vsync blocks here (real-device NVN: when all textures in the swapchain are waiting for display, wait for the next one to be released), not in present -- the game often calls present while holding a lock
|
||||
uint64_t at = *idx < 4 ? o->avail[*idx] : 0, now = dm_detclock_enabled() ? guest_ns() : now_ns(), wait = at > now ? at - now : 0, pace_ns = 0;
|
||||
uint64_t at = *idx < 4 ? o->avail[*idx] : 0, now = dm_detclock_enabled() ? guest_ns() : now_ns(), wait = at > now ? at - now : 0, pace_ns = 0, drain_ns = 0;
|
||||
if (!dm_detclock_enabled()) { // Register the acquire thread as a time-constraint thread (no longer registered only when it "arrived early": it must also declare itself when it is constantly behind in the hot state)
|
||||
uint64_t period = present_period(o); rt_acquire(rt_period_ns(o, period));
|
||||
uint64_t p0 = now_ns(); int snap = mtl_snap_on();
|
||||
@@ -1901,6 +1912,8 @@ NVN(nvnWindowAcquireTexture, NVNwindowAcquireTextureResult, NVNwindow *w, NVNsyn
|
||||
// order and drops all but the newest two, and a dropped frame frees its slot, so Donkey Kong Bananza at the 30 fps cap ran 43-65 fps of game time and dropped about 110 of every 300 frames
|
||||
else if (mtl_link_active()) { if (!link_wait(o, period ? 2 * period : 33333333ull)) { o->follow = 0; if (wait) sleep_until_ns(at); } } // DM_PRESENT_LINK: pacing fully follows the display link (wait for the present interval's display-link ticks when running fast, go immediately when behind); our own 60 Hz clock is only the fallback when no display-link tick arrives
|
||||
else { o->follow = 0; if (wait) sleep_until_ns(at); }
|
||||
if (!present_unpaced(o) && mtl_present_screen_wait(period / 1e9)) atomic_store(&g_screen_at, now_ns()); // without the display link: until the screen has caught up (nvn_mtl.m, DM_PRESENT_DEPTH)
|
||||
drain_ns = mtl_link_drain_take_ns(); // with it: the ticks a drain of standing frames added to the link's wait
|
||||
pace_ns = now_ns() - p0;
|
||||
} else { // DM_DETCLOCK_PACE=1 (used by the screenshot gate): while the guest clock advances per frame, each frame's wall clock is no shorter than one step -- frame count and in-game time are deterministic, and the background loading thread has at least one step of wall clock available per frame;
|
||||
// When the machine is fully loaded frames only get slower and the background only gets more wall clock, so the picture captured at "the Nth frame after the message" is independent of load
|
||||
@@ -1914,7 +1927,8 @@ NVN(nvnWindowAcquireTexture, NVNwindowAcquireTextureResult, NVNwindow *w, NVNsyn
|
||||
uint64_t tk = *idx < 4 ? o->ticket[*idx] : 0;
|
||||
if (tk) { uint64_t w0 = now_ns(); nvn_queue_present_wait(tk); nvn_queue_present_release(tk); o->ticket[*idx]=0; g_pq_wait_ns += now_ns() - w0; }
|
||||
if (s) { nvn_sync_release((sync_t *)s); ((sync_t *)s)->fenced = 2; ((sync_t *)s)->fence = mtl_last_fence(); } // The swapchain texture becomes available once the commits before this point have completed (fenced 2: an acquire sync, for the wait ledger)
|
||||
if (!g_fs_start) { g_fs_start = now_ns(); g_fs_wait = pace_ns; } // the frame starts when the first acquire after a present returns: on a display-link tick when on time
|
||||
if (!g_fs_start) { g_fs_start = now_ns(); g_fs_wait = pace_ns; g_fs_drain += drain_ns; } // the frame starts when the first acquire after a present returns: on a display-link tick when on time
|
||||
else g_fs_drain_late += drain_ns;
|
||||
return NVN_WINDOW_ACQUIRE_TEXTURE_RESULT_SUCCESS;
|
||||
}
|
||||
// The older API (NVN 53, Super Mario 3D World + Bowser's Fury): the queue waits for the texture on the GPU and no sync object is handed out. The host replays in submission order, so later commands already come after earlier presents; the same as WindowAcquireTexture without a sync object
|
||||
@@ -2486,7 +2500,14 @@ static void fstep_tick(const win_t *o, int c) {
|
||||
static uint64_t prev, t0, v0, fixed_sum, held[FSTEP_MAX + 1]; static int nlog;
|
||||
const double v = 1e9 / fstep_hz();
|
||||
uint64_t st = g_fs_start ? g_fs_start : now_ns(), pw = g_fs_wait; g_fs_start = g_fs_wait = 0;
|
||||
double shown = prev ? (st - prev) / v : 0, gpu = 0; prev = st;
|
||||
// A drain of standing frames (g_fs_drain) comes out of the frame's time as far as it made the frame longer than its hold (nvn_fstep_drain_cut)
|
||||
static uint64_t drain_before; // a drain in a later acquire of the previous frame: in this frame's time since that start, not in its pacing wait
|
||||
static uint64_t drain_n, drain_cut; // frames a drain shortened and the time cut (ns), for the 1800-present line
|
||||
uint64_t span = prev && st > prev ? st - prev : 0, raw = span;
|
||||
span = nvn_fstep_drain_cut(span, (uint64_t)((g_fs.k ? g_fs.k : fstep_hz() / c) * v), g_fs_drain, drain_before, &pw);
|
||||
if (span < raw) { drain_n++; drain_cut += raw - span; }
|
||||
drain_before = g_fs_drain_late; g_fs_drain = g_fs_drain_late = 0;
|
||||
double shown = prev ? span / v : 0, gpu = 0; prev = st;
|
||||
for (uint64_t f = g_frame; f-- > 0 && g_frame - f <= 8;) { double g = mtl_gpu_ms(f); if (g >= 0) { gpu = g * 1e6 / v; break; } }
|
||||
double cpu = shown - pw / v, cost = cpu > gpu ? cpu : gpu;
|
||||
int kmin = fstep_hz() / c, kmax = fps_high() ? 2 : !fstep_hold() ? kmin : kmin >= 2 ? 2 : FSTEP_MAX, k0 = g_fs.k, // at 120 fps a late frame must step down whatever fps_hold says: the game steps by the target
|
||||
@@ -2537,13 +2558,14 @@ static void fstep_tick(const win_t *o, int c) {
|
||||
else if (probe0 == 2 && !g_fs.probe && g_fs.failed != failed0 && nlog < 40)
|
||||
LOG("[nvn] frame step: the run at hold %d after the probe lasted under %.0f s, counted as a failed probe (CPU %d%% on performance cores)%s", kmin, FSTEP_HOLD_MAX / 60, g_fs_pshare, ++nlog == 40 ? "; further changes only counted below" : "");
|
||||
if (!dm_fps_state) { // 120 fps: no game clock to read; the frames at each hold say how much of the time it held 120
|
||||
if (o->presents % 1800 == 0) { LOG("[nvn] 120 fps: held 1 / 2 ticks %llu / %llu frames, %llu late, %llu up / %llu down (%llu probes, %llu failed trials)", (unsigned long long)held[1], (unsigned long long)held[2], (unsigned long long)g_fs.late, (unsigned long long)g_fs.ups, (unsigned long long)g_fs.downs, (unsigned long long)g_fs.probes, (unsigned long long)g_fs.failed); memset(held, 0, sizeof held); }
|
||||
if (o->presents % 1800 == 0) { LOG("[nvn] 120 fps: held 1 / 2 ticks %llu / %llu frames, %llu late, %llu up / %llu down (%llu probes, %llu failed trials); standing-frame drains taken out of %llu frames (%.1f ticks)", (unsigned long long)held[1], (unsigned long long)held[2], (unsigned long long)g_fs.late, (unsigned long long)g_fs.ups, (unsigned long long)g_fs.downs, (unsigned long long)g_fs.probes, (unsigned long long)g_fs.failed, (unsigned long long)drain_n, drain_cut / v); memset(held, 0, sizeof held); drain_n = drain_cut = 0; }
|
||||
} else if (o->presents % 1800 == 0) { // game time against real time (1.000 = normal speed; lower when a device cannot hold 20 fps or after long stalls)
|
||||
uint64_t vs = __atomic_load_n((uint64_t *)(dm_fps_state + 0x30), __ATOMIC_RELAXED) + fixed_sum, t = now_ns();
|
||||
if (t0) LOG("[nvn] frame step: game time %.2f s in %.2f s (%.3f of real time); held 1 / 2 / 3 vsyncs %llu / %llu / %llu frames, %llu late, %llu vsyncs paid back, %.0f dropped, %llu up / %llu down (%llu probes, %llu failed trials)",
|
||||
if (t0) LOG("[nvn] frame step: game time %.2f s in %.2f s (%.3f of real time); held 1 / 2 / 3 vsyncs %llu / %llu / %llu frames, %llu late, %llu vsyncs paid back, %.0f dropped, %llu up / %llu down (%llu probes, %llu failed trials); standing-frame drains taken out of %llu frames (%.1f vsyncs)",
|
||||
(vs - v0) / 60.0, (t - t0) / 1e9, (vs - v0) / 60.0 / ((t - t0) / 1e9), (unsigned long long)held[1], (unsigned long long)held[2], (unsigned long long)held[3],
|
||||
(unsigned long long)g_fs.late, (unsigned long long)g_fs.paid, g_fs.dropped, (unsigned long long)g_fs.ups, (unsigned long long)g_fs.downs, (unsigned long long)g_fs.probes, (unsigned long long)g_fs.failed);
|
||||
t0 = t; v0 = vs; memset(held, 0, sizeof held);
|
||||
(unsigned long long)g_fs.late, (unsigned long long)g_fs.paid, g_fs.dropped, (unsigned long long)g_fs.ups, (unsigned long long)g_fs.downs, (unsigned long long)g_fs.probes, (unsigned long long)g_fs.failed,
|
||||
(unsigned long long)drain_n, drain_cut / v);
|
||||
t0 = t; v0 = vs; memset(held, 0, sizeof held); drain_n = drain_cut = 0;
|
||||
}
|
||||
}
|
||||
// The crop a present shows: the window's own (nvnWindowSetCrop), else the vi layer's (vi::SetLayerCrop, hle_vi.c); on the Switch both become the crop of the buffer queued to the layer.
|
||||
@@ -2684,6 +2706,10 @@ NVN(nvnQueuePresentTexture, void, NVNqueue *q, NVNwindow *w, int idx) {
|
||||
uint64_t period = present_period(o), now = dm_detclock_enabled() ? guest_ns() : now_ns();
|
||||
g_hold_ring[o->presents % 16] = (uint8_t)present_itv(o);
|
||||
nvn_pacer pc = {o->pace};
|
||||
// The screen wait released this frame's acquire (g_screen_at): the frame's phase is the screen's, so the pacer starts from the release, not from its own earlier slot.
|
||||
// Kept on its own phase, the pacer counted the wait as lateness and paid it back with short frames: frame starts of 25, 25, 48 ms at a 30 fps cap without the display link
|
||||
// (the screen still showed every frame for 33.3 ms). A frame the display link paced restarts the beat at its present anyway (nvn_pace_follow), and the screen wait runs only without it
|
||||
{ uint64_t r = atomic_exchange(&g_screen_at, 0); if (r > pc.target) pc.target = r; }
|
||||
uint64_t slot = now; // a frame the display link paced (or nothing did) is shown from its present on, and the beat follows it (nvn_pace_follow)
|
||||
if (o->follow) nvn_pace_follow(&pc, now); else slot += nvn_pace(&pc, now, period);
|
||||
o->pace = pc.target;
|
||||
|
||||
@@ -72,6 +72,19 @@ typedef struct {
|
||||
uint64_t late, paid, ups, downs, failed, probes; double dropped; // statistics for the log
|
||||
} nvn_fstep;
|
||||
|
||||
// A drain of frames standing in the display link's queue in a frame's time (hle_nvn.c fstep_tick, g_fs_drain; nvn_link_drain.h): the acquire waited extra link ticks while the
|
||||
// screen showed every queued frame for its hold, so the part that made the frame longer than its hold is neither a late frame nor time the game owes: it comes out of the
|
||||
// frame's time. (The wait for the screen without the link is not one: there a frame longer than its hold is one the screen showed late.) span: time since the previous frame's
|
||||
// start; hold: the hold the frame had; first: drain in the acquire that started this frame, part of *pacing (its pacing wait); before: drain in later acquires of the previous
|
||||
// frame, in span but not in *pacing. Returns span less the cut; *pacing loses the cut's part in it (the frame's CPU time, span − pacing, keeps what it was, less the later
|
||||
// acquires' wait, which was no work either). All in the same unit (ns).
|
||||
static inline uint64_t nvn_fstep_drain_cut(uint64_t span, uint64_t hold, uint64_t first, uint64_t before, uint64_t *pacing) {
|
||||
if (first > *pacing) first = *pacing;
|
||||
uint64_t over = span > hold ? span - hold : 0, cut = first + before < over ? first + before : over;
|
||||
*pacing -= cut < first ? cut : first;
|
||||
return span - cut;
|
||||
}
|
||||
|
||||
// Whether the cost at the longer hold is the cost that held kmin (a probe without a slowed report)
|
||||
static inline int nvn_fstep_same(const nvn_fstep *s) { return s->cref > 0 && s->cn >= FSTEP_RUN && s->ccur <= FSTEP_SAME * s->cref; }
|
||||
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
// Draining frames that stand in the present queue (pure function, shared by Mac / iOS; unit test tests/t_link_drain.c).
|
||||
// The display-link callback (nvn_mtl.m NvMetalDisplayLinkDelegate) wakes the game's acquire and then takes a frame from the present queue, so a frame the game presents
|
||||
// right after a tick waits for the next one. That wait is under one link tick. After a late frame the acquire returns at once to catch up (mtl_link_wait_ticks), two frames
|
||||
// reach the queue before one tick, the callback shows them in order (one per tick), and from then on every frame waits one tick more than it needs: a standing frame, 33.3 ms
|
||||
// of input lag at 30 fps and 16.7 ms at 60, which never clears while the game keeps up (Ocarina of Time at a 30 fps cap in a window: 115 ms from the game's present to the
|
||||
// screen, 82 ms without the standing frame). On a 60 Hz link that holds each frame for two ticks (a 30 fps target in fixed-rate fullscreen) the frames can also be taken on
|
||||
// the ticks between the acquire's, half a hold more.
|
||||
// The drain: when every frame taken over LINK_DRAIN_SECS waited at least a whole link tick longer than it had to, while the game was waiting for the link in its acquire
|
||||
// (it keeps up with room to spare), the next acquire waits that many ticks more, once. The callback shows the queued frames meanwhile, one per tick as before, so no frame
|
||||
// is dropped or repeated on screen; the game loses those ticks of wall time once. A game that runs slower than the link never waits in its acquire, its queue empties by
|
||||
// itself, and it is left alone: there the standing frame is the slack that keeps a slightly slow game from locking to half the rate (the display link's frames-in-order rule).
|
||||
#pragma once
|
||||
#include <math.h>
|
||||
#include <stdint.h>
|
||||
|
||||
#define LINK_DRAIN_MARGIN 0.002 // seconds a frame keeps in the queue before its tick after a drain: the callback must find it queued (the game presents about 1 ms after a tick)
|
||||
#define LINK_DRAIN_SECS 2.0 // how long the frames must have stood before a drain: a hiccup's catch-up frames are not a standing queue yet
|
||||
#define LINK_DRAIN_TAKES 30 // and at least this many frames taken in a row
|
||||
#define LINK_DRAIN_BLOCKED 0.15 // the acquire must have waited for the link at least this share of a tick (and 2 ms) before each of those frames: the game has room to spare
|
||||
|
||||
typedef struct {
|
||||
int run; // frames taken in a row that stood at least one tick too long with the game waiting
|
||||
double since, min_age; // when the run started (seconds), and the shortest queue time in it
|
||||
uint64_t drains; // drains asked for (statistics for the log)
|
||||
} nvn_link_drain;
|
||||
|
||||
// Whole link ticks a frame that waited `age` seconds in the queue could have been presented later and still be taken on the same tick
|
||||
static inline int nvn_link_drain_spare(double age, double tick) { return tick > 0 && age > LINK_DRAIN_MARGIN ? (int)floor((age - LINK_DRAIN_MARGIN) / tick) : 0; }
|
||||
|
||||
// Once per frame the display-link callback takes. now: the callback's time (seconds); age: how long that frame waited in the present queue (seconds); tick: the link's
|
||||
// period (seconds); blocked: how long the game's last acquire waited for the link (seconds, 0 = it did not wait); ok: 0 when this take says nothing about a standing queue
|
||||
// (frames were dropped on it, the link is rescued, present snapshots run the game ahead on purpose). Returns the link ticks the next acquire should wait more (0 = none).
|
||||
static inline int nvn_link_drain_next(nvn_link_drain *d, double now, double age, double tick, double blocked, int ok) {
|
||||
double need = LINK_DRAIN_BLOCKED * tick > 0.002 ? LINK_DRAIN_BLOCKED * tick : 0.002;
|
||||
if (!ok || nvn_link_drain_spare(age, tick) < 1 || blocked < need) { d->run = 0; return 0; }
|
||||
if (!d->run++) { d->since = now; d->min_age = age; } else if (age < d->min_age) d->min_age = age;
|
||||
if (d->run < LINK_DRAIN_TAKES || now - d->since < LINK_DRAIN_SECS) return 0;
|
||||
int spare = nvn_link_drain_spare(d->min_age, tick); // by the frame that waited least, so none of them would have missed its tick
|
||||
d->run = 0; d->drains++;
|
||||
return spare;
|
||||
}
|
||||
+141
-9
@@ -33,6 +33,7 @@
|
||||
#include "nvn_cover.h"
|
||||
#include "nvn_border.h"
|
||||
#include "nvn_primitive.h"
|
||||
#include "nvn_link_drain.h"
|
||||
#include "nvn_timestamp.h"
|
||||
#include "msl_image.h"
|
||||
#include "dmsh_chain.h" // DMSH_CHAIN: the translation chain version of the B shader library expected by this source tree, one for every game (beside this file, tools/dmsh_chain.py --header)
|
||||
@@ -129,6 +130,11 @@ static pthread_mutex_t g_link_mu = PTHREAD_MUTEX_INITIALIZER;
|
||||
static uint64_t g_link_tick_ns, g_link_tick_n;
|
||||
static uint64_t g_link_dropped;
|
||||
static uint64_t g_link_empty; // Under g_pq_mu: ticks that found no new frame queued (counted here, not as ticks minus presents: presents before the link starts and while it is rescued are not on ticks)
|
||||
// Frames standing in the present queue (nvn_link_drain.h): the callback asks the game's next acquire to wait g_link_drain_req more ticks, once, and mtl_link_wait_ticks does.
|
||||
// g_link_blocked_ns: how long the acquire's last wait for the link blocked (0 = it was behind and did not wait), the callback's evidence that the game has room to spare;
|
||||
// g_link_drain_ns: the time acquires spent on drains since mtl_link_drain_take_ns last asked (pacing, not a late frame: hle_nvn.c fstep_tick); g_link_drained: drains done
|
||||
static nvn_link_drain g_link_drain; // display-link callback thread only
|
||||
static _Atomic int g_link_drain_req; static _Atomic uint64_t g_link_blocked_ns, g_link_drain_ns, g_link_drained;
|
||||
static double g_link_hold_until; static uint64_t g_link_held; // Changed only on the display-link callback thread: the time the previous frame must stay on screen until by its present interval (0 = no hold), and the ticks that took no new frame because of it
|
||||
static int g_pq_inflight; // Under g_pq_mu: number of presents committed to the GPU whose completion callback has not arrived yet
|
||||
static NSMutableArray *g_ext_retire; // Under g_pq_mu: released external textures (mtl_ext_tex_release) waiting for the presents in flight; retired when g_pq_inflight reaches 0
|
||||
@@ -16664,6 +16670,35 @@ typedef struct { uint64_t n; double t; } pres_ent;
|
||||
static pres_ent g_pres[PRING];
|
||||
// Get the actual presentation time of the nth present (returns 0 if not ready, -1 if dropped)
|
||||
double mtl_presented_time(uint64_t n) { pres_ent e = g_pres[n % PRING]; return e.n == n ? e.t : 0; }
|
||||
// The screen's progress, for the acquire's wait without the display link (mtl_present_screen_wait, DM_PRESENT_DEPTH) and the queue-to-screen statistics: by ticket, when the game
|
||||
// queued the present (CACurrentMediaTime, the presentedTime base), and the newest ticket the system has reported shown or dropped (the drawable's presented handler, on a system thread)
|
||||
static double g_pres_tin[PRING];
|
||||
static _Atomic uint64_t g_pres_seen, g_sdw_n, g_sdw_ns, g_sdw_to; // the newest ticket seen; the acquires that waited for the screen, their time, and those that timed out
|
||||
static int g_sdw_depth = -1;
|
||||
static uint64_t g_pres_frm[PRING]; // by ticket: the game frame its present was recorded in (pq_item.frame)
|
||||
static _Atomic uint64_t g_rec_frame, g_seen_frame; // the frame of the game's newest recorded present (mtl_present_recorded, the game's thread) and of the newest present shown or dropped
|
||||
void mtl_present_recorded(uint64_t frame) { uint64_t w = atomic_load(&g_rec_frame); while (frame > w && !atomic_compare_exchange_weak(&g_rec_frame, &w, frame)) {} }
|
||||
static void pres_seen(uint64_t pn, double tt) {
|
||||
uint64_t was = atomic_load(&g_pres_seen);
|
||||
while (pn > was && !atomic_compare_exchange_weak(&g_pres_seen, &was, pn)) {}
|
||||
{ uint64_t fr = g_pres_frm[pn % PRING], w = atomic_load(&g_seen_frame); while (fr > w && !atomic_compare_exchange_weak(&g_seen_frame, &w, fr)) {} }
|
||||
pthread_mutex_lock(&g_pq_mu); pthread_cond_broadcast(&g_pq_cv); pthread_mutex_unlock(&g_pq_mu);
|
||||
double lagms = tt > 0 ? (CACurrentMediaTime() - tt) * 1e3 : -1; // how late the presented handler runs after the frame reached the screen
|
||||
double tin = g_pres_tin[pn % PRING];
|
||||
if (!(tt > 0) || !(tin > 0) || tt < tin) return;
|
||||
static pthread_mutex_t mu = PTHREAD_MUTEX_INITIALIZER; static double lat[300], lag[300]; static int n; static uint64_t n0, ns0, to0;
|
||||
pthread_mutex_lock(&mu);
|
||||
lag[n] = lagms; lat[n++] = (tt - tin) * 1e3;
|
||||
if (n == 300) {
|
||||
for (int i = 1; i < n; i++) { double x = lat[i]; int j = i - 1; while (j >= 0 && lat[j] > x) { lat[j + 1] = lat[j]; j--; } lat[j + 1] = x; }
|
||||
for (int i = 1; i < n; i++) { double x = lag[i]; int j = i - 1; while (j >= 0 && lag[j] > x) { lag[j + 1] = lag[j]; j--; } lag[j + 1] = x; }
|
||||
uint64_t wn = atomic_load(&g_sdw_n), wns = atomic_load(&g_sdw_ns), wto = atomic_load(&g_sdw_to);
|
||||
MLOG("present: game enqueue to screen p50 %.1f ms, p95 %.1f, max %.1f over 300 frames shown (ticket %llu); waits for the screen at acquire (DM_PRESENT_DEPTH %d): %llu, %.2f ms a frame, %llu timed out; presented handlers run %.1f ms (p50) / %.1f (p95) after the frame reached the screen",
|
||||
lat[149], lat[284], lat[299], (unsigned long long)pn, g_sdw_depth, (unsigned long long)(wn - n0), (wns - ns0) / 1e6 / 300, (unsigned long long)(wto - to0), lag[149], lag[284]);
|
||||
n0 = wn; ns0 = wns; to0 = wto; n = 0;
|
||||
}
|
||||
pthread_mutex_unlock(&mu);
|
||||
}
|
||||
// Ring of the display-link tick that took each present (written on the display-link callback thread, read 8 presents later for DM_NVN_TSV, as g_pres): its target display time
|
||||
// (seconds, CACurrentMediaTime base), how long before it the callback ran, the callbacks since the previous present's (1 = no tick without a frame) and the longest interval between them
|
||||
typedef struct { uint64_t n; double target, lead_ms, gap_ms; int ticks; } link_ent;
|
||||
@@ -17232,9 +17267,9 @@ static int present_now(const tex_t *t, double period, uint64_t frame, uint64_t t
|
||||
for (int i = 1; i < 300; i++) { double v = a[i]; int j = i - 1; while (j >= 0 && a[j] > v) { a[j + 1] = a[j]; j--; } a[j + 1] = v; }
|
||||
double b[300]; memcpy(b, e2e, sizeof b);
|
||||
for (int i = 1; i < 300; i++) { double v = b[i]; int j = i - 1; while (j >= 0 && b[j] > v) { b[j + 1] = b[j]; j--; } b[j + 1] = v; }
|
||||
MLOG("display link up to tick %llu: ticks 300, presents %llu, empty ticks %llu (held for the present interval %llu), old frames dropped by merging %llu; submission ahead of target display p50 %.3f ms / min %.3f ms; game enqueue to target display p50 %.3f ms / min %.3f / max %.3f ms",
|
||||
MLOG("display link up to tick %llu: ticks 300, presents %llu, empty ticks %llu (held for the present interval %llu), old frames dropped by merging %llu; submission ahead of target display p50 %.3f ms / min %.3f ms; game enqueue to target display p50 %.3f ms / min %.3f / max %.3f ms; standing frames drained %llu times",
|
||||
(unsigned long long)g_link_tick_n, (unsigned long long)g_present_n, (unsigned long long)g_link_empty, (unsigned long long)g_link_held,
|
||||
(unsigned long long)g_link_dropped, a[149], a[0], b[149], b[0], b[299]);
|
||||
(unsigned long long)g_link_dropped, a[149], a[0], b[149], b[0], b[299], (unsigned long long)atomic_load(&g_link_drained));
|
||||
}
|
||||
}
|
||||
[g_q4 signalDrawable:dr];
|
||||
@@ -17246,6 +17281,7 @@ static int present_now(const tex_t *t, double period, uint64_t frame, uint64_t t
|
||||
[dr addPresentedHandler:^(id<MTLDrawable> d) { // Actual presentation time (the time this frame is really put on screen, CACurrentMediaTime base)
|
||||
CFTimeInterval tt = d.presentedTime;
|
||||
g_pres[pn % PRING] = (pres_ent){pn, tt > 0 ? tt : -1};
|
||||
pres_seen(pn, tt);
|
||||
}];
|
||||
// Each frame is displayed for at least one present period: when the GPU completion time jitters around a 120 Hz refresh boundary, the paired "25 ms + 8.33 ms" stutter no longer appears
|
||||
if (target_ts > 0) [dr present];
|
||||
@@ -17291,6 +17327,25 @@ static uint64_t g_rescue_back_at, g_rescue_back_ns = 3000000000ull, g_rescue_n;
|
||||
// but it is not counted as stuck and no failure is reported; the stall is measured from the later of "the most recent callback / the most recent activation" (A16 logs: 8–17 seconds inactive and 17 seconds in the background were both reported as "stuck in foreground")
|
||||
__attribute__((weak)) int dm_focus_now(void) { return 1; } // The host's hle_oe.c provides the strong definition; when graphics unit tests do not link the host it is treated as always active
|
||||
__attribute__((weak)) uint64_t dm_focus_in_since(void) { return 0; }
|
||||
// DM_PRESENT_DRAIN=1 / 0: whether frames standing in the present queue are drained (nvn_link_drain.h). On by default on the Mac; off on iOS, where it has not been measured
|
||||
static int g_link_drain_on = -1; // -1 = not read yet (file-level so that t_present_rescue can set it)
|
||||
static int link_drain_on(void) {
|
||||
if (g_link_drain_on < 0) {
|
||||
const char *e = getenv("DM_PRESENT_DRAIN"); g_link_drain_on = e ? atoi(e) != 0 : TARGET_OS_OSX;
|
||||
MLOG("display link: frames standing in the present queue are %s (DM_PRESENT_DRAIN)", g_link_drain_on ? "drained: the acquire waits them out once the game has kept up for 2 s" : "left standing");
|
||||
}
|
||||
return g_link_drain_on;
|
||||
}
|
||||
// Once per frame the display-link callback takes (its thread): cb the callback's time, age how long the frame waited in the queue (both seconds), dropped whether older
|
||||
// frames were merged away on this tick. Asks the next acquire for the ticks the queued frames have to spare (g_link_drain_req). Not with present snapshots, which run the
|
||||
// game a frame ahead on purpose, and not on the 120 Hz link: there the system already shows presents late in variable-refresh fullscreen (link_vrr_120) with the queue's
|
||||
// slack in place, and a drain there is unmeasured
|
||||
static void link_drain_note(double cb, double age, int dropped) {
|
||||
if (!link_drain_on()) return;
|
||||
int rate = mtl_link_rate(), ok = !dropped && rate != 120 && !mtl_snap_on();
|
||||
int k = nvn_link_drain_next(&g_link_drain, cb, age, 1.0 / rate, atomic_load(&g_link_blocked_ns) / 1e9, ok);
|
||||
if (k) atomic_store(&g_link_drain_req, k);
|
||||
}
|
||||
@implementation NvMetalDisplayLinkDelegate
|
||||
- (void)metalDisplayLink:(CAMetalDisplayLink *)link needsUpdate:(CAMetalDisplayLinkUpdate *)update {
|
||||
(void)link;
|
||||
@@ -17332,6 +17387,7 @@ __attribute__((weak)) uint64_t dm_focus_in_since(void) { return 0; }
|
||||
g_link_ring[ticket % PRING] = (link_ent){ticket, update.targetPresentationTimestamp, (update.targetPresentationTimestamp - cb) * 1e3, gap_max * 1e3, nticks}; nticks = 0; gap_max = 0;
|
||||
pthread_cond_broadcast(&g_pq_cv);
|
||||
pthread_mutex_unlock(&g_pq_mu);
|
||||
link_drain_note(cb, cb - it.t_in, ticket > first);
|
||||
int submitted;
|
||||
ext_wait(it.ev_val); snap_commit_wait(it.snap_v);
|
||||
@autoreleasepool { submitted = present_now(&it.t, it.period, it.frame, ticket, it.crop, update.drawable, update.targetPresentationTimestamp); mtl_tex_unpin(it.t.serial); }
|
||||
@@ -17381,7 +17437,11 @@ static const char *link_latency_why(void) { return g_present_latency > 0 ? "DM_P
|
||||
// 16.5-25 callbacks a second over stretches of 300 frames, also on frames with under 1 ms of GPU, and each skipped tick kept a frame on screen 66.7 ms (a 180 s walk: 388 and 996
|
||||
// frames over 50 ms; 3-4 in a window, where the same link held 30.0). Why is open (docs/reference/frame-rate.md). The 60 Hz link paces the 30 through the present interval, as it
|
||||
// does interval-2 frames (two ticks per acquire, mtl_link_wait_tick; each frame held for its period, g_link_hold_until): 7 frames over 50 ms on the same walk
|
||||
static int link_30hz(void) { return !front_fullscreen() || front_screen_variable_refresh(); }
|
||||
// In a window the 30 Hz link is kept only while standing frames are not drained (DM_PRESENT_DRAIN=0, iOS) or present snapshots run the game ahead. With the drain a
|
||||
// frame presented right after a tick waits one tick of the link whatever the frame rate, and the drain moves the game onto the 60 Hz ticks between the callback's takes:
|
||||
// 15.5 ms in the queue at 30 fps on the 60 Hz link against 32.2 ms on the 30 Hz one (Ocarina of Time in a window: 65 against 82 ms from the game's present to the screen),
|
||||
// for 60 callbacks a second instead of 30. Without the drain the 60 Hz link gains nothing reliably: the takes stay on the acquire's ticks or not as the last late frame left them
|
||||
static int link_30hz(void) { return front_fullscreen() ? front_screen_variable_refresh() : !link_drain_on() || mtl_snap_on(); }
|
||||
// The 120 Hz link (mode 2, a frame every other tick) in place of the 60 Hz one in fullscreen on a variable-refresh screen whose rate is a multiple of 120 (a ProMotion
|
||||
// screen), unless DM_PRESENT_LINK chose the mode. There, with the 60 Hz link at frame latency 2, the system showed every present one 120 Hz refresh after the link's
|
||||
// target time (@pres_at_ms − @link_target_ms = 8.33 ms) and the link then skipped every other tick (@link_gap_ms 16.7, 33.3, 16.7, …): 40 callbacks a second, so a game
|
||||
@@ -17481,6 +17541,7 @@ static void *present_main(void *arg) {
|
||||
if (ticket > g_pq_done) g_pq_done = ticket;
|
||||
pthread_cond_broadcast(&g_pq_cv);
|
||||
pthread_mutex_unlock(&g_pq_mu);
|
||||
pres_seen(ticket, -1); // never reaches the screen: the screen wait must not wait for it
|
||||
}
|
||||
}
|
||||
return NULL;
|
||||
@@ -17666,6 +17727,8 @@ static uint64_t present_enqueue(const tex_t *t, double period, const int crop[4]
|
||||
pq_item *it = &g_pq[g_pq_in % PQ]; *it = (pq_item){*t, period, atomic_load(&g_cur_frame), {0}, CACurrentMediaTime(), ev_val, ss ? g_snap[slot].ev : 0};
|
||||
if (crop) memcpy(it->crop, crop, sizeof it->crop); // The current frame's state is enqueued with the ticket number, rather than reading the mutable window late on the present thread
|
||||
uint64_t tk = ++g_pq_in;
|
||||
g_pres_tin[tk % PRING] = it->t_in;
|
||||
g_pres_frm[tk % PRING] = it->frame;
|
||||
if (ss) { g_snap[slot].ticket = tk; atomic_fetch_add(&g_snap_next, 1); if (copy) *copy = g_snap[slot].ev; }
|
||||
pthread_cond_broadcast(&g_pq_cv);
|
||||
pthread_mutex_unlock(&g_pq_mu);
|
||||
@@ -17684,6 +17747,50 @@ void mtl_present_progress(uint64_t *queued, uint64_t *done) { pthread_mutex_lock
|
||||
// worker has replayed that present, then ran a frame further ahead of the GPU per ring slot, and one that sizes its
|
||||
// CPU-written per-frame buffers on the swapchain's depth rewrote data a queued frame's draws still read: Xenoblade Chronicles 3's scene came out one flat colour in a
|
||||
// third to a half of the frames (2 slots 32/80, 4 slots 49/80, snapshots off 0/80; LNPANDY/NX2Apple#1117)
|
||||
// Without the display link (DM_PRESENT_LINK=0) the acquire paces the game on the host's own clock (hle_nvn.c: the texture's slot time, nvn_pace), and the present thread holds
|
||||
// each frame on screen for its period (presentAfterMinimumDuration). Nothing ties the two clocks to what the screen really shows: a texture is the game's again once its
|
||||
// present is committed, not shown. At a cap the game holds, both run at the same rate, so each present that reaches the screen late adds a period to the queue for good
|
||||
// (frames waiting in the present queue and in the layer's drawables), until the swapchain and the layer's drawables are full: Ocarina of Time at a 30 fps cap showed its
|
||||
// frames 92-155 ms after queuing them, against 32-45 ms when the game ran slower than the cap. On the Switch the acquire blocks until the screen has let go of the texture.
|
||||
// The acquire now also waits until at most DM_PRESENT_DEPTH (default 1) presents queued are not yet on screen or dropped, as the presented handlers report. 0 is the
|
||||
// Switch's double buffering; a larger depth trades latency for slack. The wait gives up after two periods and then stays off until the handlers report again (a covered
|
||||
// window, a screen asleep or a headless run report rarely or never). DM_PRESENT_SCREEN=0 turns it off (ab with DM_AB). The display link has its own pacing and is left alone
|
||||
// (it drains frames standing in its queue instead, nvn_link_drain.h), and so are present snapshots, which run the game a frame ahead of the screen on purpose and are paced by
|
||||
// their ring (mtl_snap_acquire_wait). The time waited is the frame's pacing for the frame step (hle_nvn.c g_screen_at): a frame it lengthens is one the screen showed late
|
||||
uint64_t mtl_present_screen_wait(double period) {
|
||||
static int mode = -1, silent; static uint64_t silent_seen; // silent: the wait gave up while the newest present seen was silent_seen (0 when the screen has reported none yet)
|
||||
if (mode < 0) {
|
||||
const char *e = getenv("DM_PRESENT_DEPTH"); int d = e && *e ? atoi(e) : 1; g_sdw_depth = d < 0 ? 0 : d > PQ ? PQ : d;
|
||||
mode = sw_mode("DM_PRESENT_SCREEN", 1);
|
||||
MLOG("present: without the display link the acquire waits until at most %d present(s) queued are not yet on screen (DM_PRESENT_DEPTH; DM_PRESENT_SCREEN %s)", g_sdw_depth, mode == 1 ? "on" : mode ? "ab" : "off");
|
||||
}
|
||||
if (!sw_on(mode) || link_on() || g_classic || mtl_snap_on() || atomic_load(&g_present_discard)) return 0;
|
||||
if (!(period > 0)) period = 1.0 / 60;
|
||||
uint64_t t0 = now_ns(); int waited = 0, to = 0;
|
||||
pthread_mutex_lock(&g_pq_mu);
|
||||
// A flag, not the ticket: a screen that has reported no present at all (newest seen 0: a window covered from its first frame, a headless run) is silent too, and with 0 read
|
||||
// as "not silent" every acquire waited the whole two periods, a third of the frame rate for the run
|
||||
if (silent && atomic_load(&g_pres_seen) == silent_seen) { pthread_mutex_unlock(&g_pq_mu); return 0; }
|
||||
silent = 0;
|
||||
struct timespec ts; clock_gettime(CLOCK_REALTIME, &ts); uint64_t tmo = (uint64_t)(2 * period * 1e9);
|
||||
ts.tv_sec += tmo / 1000000000ull; ts.tv_nsec += tmo % 1000000000ull; if (ts.tv_nsec >= 1000000000L) { ts.tv_sec++; ts.tv_nsec -= 1000000000L; }
|
||||
// Counted in the game's presents, not the replay's: g_pq_in grows only when the queue worker replays a present, a variable time after the game recorded it, and against
|
||||
// that stale count the acquire was released early (a short frame) and then held (a long one): the game's present calls ran 25, 25, 48 ms apart at a 30 fps cap while the
|
||||
// replay and the screen were even. A present recorded in game frame f waits until the present of frame f - depth is shown. Without recorded presents: the replay's count
|
||||
for (;;) {
|
||||
uint64_t rf = atomic_load(&g_rec_frame), want, have; int byframe = rf > 0;
|
||||
if (byframe) { want = rf > (uint64_t)g_sdw_depth ? rf - (uint64_t)g_sdw_depth : 0; have = atomic_load(&g_seen_frame); }
|
||||
else { want = g_pq_in > (uint64_t)g_sdw_depth ? g_pq_in - (uint64_t)g_sdw_depth : 0; have = atomic_load(&g_pres_seen); }
|
||||
if (have >= want || atomic_load(&g_present_discard)) break;
|
||||
waited = 1;
|
||||
if (pthread_cond_timedwait(&g_pq_cv, &g_pq_mu, &ts) == ETIMEDOUT) { if ((byframe ? atomic_load(&g_seen_frame) : atomic_load(&g_pres_seen)) < want) { to = 1; silent = 1; silent_seen = atomic_load(&g_pres_seen); } break; }
|
||||
}
|
||||
pthread_mutex_unlock(&g_pq_mu);
|
||||
uint64_t dt = now_ns() - t0;
|
||||
if (waited) { atomic_fetch_add(&g_sdw_n, 1); atomic_fetch_add(&g_sdw_ns, dt); }
|
||||
if (to) { atomic_fetch_add(&g_sdw_to, 1); static int nred; if (nred++ < 3) MLOG("present: the screen reported no frame for %.0f ms while %llu presents wait (newest seen %llu); the acquire stops waiting for the screen until it reports again", 2 * period * 1e3, (unsigned long long)g_pq_in, (unsigned long long)atomic_load(&g_pres_seen)); }
|
||||
return waited ? dt : 0;
|
||||
}
|
||||
void mtl_present_wait_texture(uint64_t tk, uint64_t ev) {
|
||||
if (!ev) { mtl_present_wait(tk); return; }
|
||||
if (atomic_load(&g_present_discard) || g_snap_ev.signaledValue >= ev) return;
|
||||
@@ -17751,19 +17858,44 @@ int mtl_link_wait_tick(int vsyncs, uint64_t timeout_ns) {
|
||||
void mtl_link_mode_set(int mode) { pthread_mutex_lock(&g_pq_mu); g_dm_present_link = mode; pthread_mutex_unlock(&g_pq_mu); } // 120 fps follows the screen: link_sync applies it
|
||||
int mtl_link_rate(void) { return g_link_mode == 3 ? 30 : g_link_mode == 2 ? 120 : 60; }
|
||||
// The same wait counted in the display link's own ticks: one per frame for a frame rate as high as the link's (present_interval display at DM_PRESENT_HZ=120 on a 120 Hz link)
|
||||
// The absolute time (CLOCK_REALTIME, as pthread_cond_timedwait takes it) ns nanoseconds from now
|
||||
static struct timespec link_deadline(uint64_t ns) {
|
||||
struct timespec ts; clock_gettime(CLOCK_REALTIME, &ts);
|
||||
ts.tv_sec += ns / 1000000000ull; ts.tv_nsec += ns % 1000000000ull;
|
||||
if (ts.tv_nsec >= 1000000000L) { ts.tv_sec++; ts.tv_nsec -= 1000000000L; }
|
||||
return ts;
|
||||
}
|
||||
int mtl_link_wait_ticks(int ticks, uint64_t timeout_ns) {
|
||||
if (!mtl_link_active()) return 0;
|
||||
static uint64_t started_tick; // Display-link tick number when the previous frame started work (only the game's present thread calls this function)
|
||||
const uint64_t step = ticks < 1 ? 1 : (uint64_t)ticks;
|
||||
// A drain the callback asked for (nvn_link_drain.h) is taken by this wait or not at all: a wait that finds its tick already passed is a game that fell behind since
|
||||
int drain = atomic_exchange(&g_link_drain_req, 0);
|
||||
pthread_mutex_lock(&g_link_mu);
|
||||
if (g_link_tick_n >= started_tick + step) { started_tick = g_link_tick_n; pthread_mutex_unlock(&g_link_mu); return 1; }
|
||||
struct timespec ts; clock_gettime(CLOCK_REALTIME, &ts);
|
||||
ts.tv_sec += timeout_ns / 1000000000ull; ts.tv_nsec += timeout_ns % 1000000000ull;
|
||||
if (ts.tv_nsec >= 1000000000L) { ts.tv_sec++; ts.tv_nsec -= 1000000000L; }
|
||||
while (g_link_tick_n < started_tick + step) if (pthread_cond_timedwait(&g_link_cv, &g_link_mu, &ts) == ETIMEDOUT) { pthread_mutex_unlock(&g_link_mu); return 0; }
|
||||
if (g_link_tick_n >= started_tick + step) { started_tick = g_link_tick_n; pthread_mutex_unlock(&g_link_mu); atomic_store(&g_link_blocked_ns, 0); return 1; }
|
||||
uint64_t w0 = now_ns();
|
||||
struct timespec ts = link_deadline(timeout_ns);
|
||||
while (g_link_tick_n < started_tick + step) if (pthread_cond_timedwait(&g_link_cv, &g_link_mu, &ts) == ETIMEDOUT) { pthread_mutex_unlock(&g_link_mu); atomic_store(&g_link_blocked_ns, 0); return 0; }
|
||||
uint64_t w1 = now_ns(), drained = 0;
|
||||
atomic_store(&g_link_blocked_ns, w1 - w0);
|
||||
if (drain > 0) { // the standing frames go to the screen on these ticks; a link that goes silent meanwhile ends the drain after two tick periods each
|
||||
const uint64_t until = g_link_tick_n + (uint64_t)drain;
|
||||
ts = link_deadline((uint64_t)drain * 2000000000ull / (uint64_t)mtl_link_rate());
|
||||
while (g_link_tick_n < until) if (pthread_cond_timedwait(&g_link_cv, &g_link_mu, &ts) == ETIMEDOUT) break;
|
||||
drained = now_ns() - w1;
|
||||
}
|
||||
started_tick = g_link_tick_n;
|
||||
pthread_mutex_unlock(&g_link_mu); return 1;
|
||||
pthread_mutex_unlock(&g_link_mu);
|
||||
if (drain > 0) {
|
||||
atomic_fetch_add(&g_link_drain_ns, drained);
|
||||
uint64_t n = atomic_fetch_add(&g_link_drained, 1) + 1;
|
||||
if (n <= 20) MLOG("display link: frames stood in the present queue while the game kept up, the acquire waited %d more tick%s (%.1f ms) to let them out (drain #%llu, frame %llu%s)",
|
||||
drain, drain == 1 ? "" : "s", drained / 1e6, (unsigned long long)n, (unsigned long long)atomic_load(&g_cur_frame), n == 20 ? "; further drains only counted" : "");
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
// The time acquires spent draining standing frames since the last call (nanoseconds): the caller counts it as pacing, not as a frame that took longer
|
||||
uint64_t mtl_link_drain_take_ns(void) { return atomic_exchange(&g_link_drain_ns, 0); }
|
||||
|
||||
// The display's vsync for vi::GetDisplayVsyncEvent (hle_sdk16.c): returns 1 at the first display-link tick of the next 60 Hz vsync (120 Hz at 120 fps, nvn_vsync_hz) after *seen (the tick count it last returned, updated),
|
||||
// 0 when the link does not run, runs at 30 Hz (power saving: the 60 Hz event cannot come from it) or gives no tick within the timeout; the caller then keeps its own clock
|
||||
|
||||
@@ -311,6 +311,7 @@ int mtl_warm_wait(int timeout_ms);
|
||||
int mtl_link_active(void);
|
||||
int mtl_link_wait_tick(int vsyncs, uint64_t timeout_ns); // vsyncs = the game's present interval
|
||||
int mtl_link_wait_ticks(int ticks, uint64_t timeout_ns); // the same in the display link's own ticks
|
||||
uint64_t mtl_link_drain_take_ns(void); // nanoseconds those waits spent letting standing frames out of the present queue since the last call (nvn_link_drain.h)
|
||||
int mtl_link_rate(void); // the display link's rate: 120, 60 or 30 Hz
|
||||
void mtl_link_mode_set(int mode); // the display link's pacing mode (DM_PRESENT_LINK's values), applied at the next present
|
||||
double mtl_presented_time(uint64_t n);
|
||||
|
||||
@@ -255,7 +255,8 @@ void nvn_queue_submit(queue_t *q,int count,const uint64_t *handles) {
|
||||
uint64_t nvn_queue_present(queue_t *q,const tex_t *t,double period,const int crop[4]) {
|
||||
nvn_cap_queue(q->serial,0);
|
||||
pthread_once(&nq_once,nq_start); nq_job *j=calloc(1,sizeof *j); if(!j) die("queue present allocation failed");
|
||||
j->receipt=nq_new(); j->frame=dm_nvn_frame_count(); nq_node *n=nq_append(j,NQ_PRESENT);
|
||||
j->receipt=nq_new(); j->frame=dm_nvn_frame_count(); { void mtl_present_recorded(uint64_t); mtl_present_recorded(j->frame); } // the game's own present count, for the screen wait (nvn_mtl.m)
|
||||
nq_node *n=nq_append(j,NQ_PRESENT);
|
||||
n->texture=*t; mtl_tex_pin(t->serial); n->period=period; if(crop) memcpy(n->crop,crop,sizeof n->crop);
|
||||
pthread_mutex_lock(&nq_mu); j->receipt->refs++; uint64_t ticket=(uintptr_t)j->receipt;
|
||||
nq_enqueue(nq_get(q),j); pthread_mutex_unlock(&nq_mu); return ticket;
|
||||
|
||||
@@ -92,6 +92,8 @@ t_fstep: t_fstep.c ../nvn/nvn_fstep.h
|
||||
clang -O1 -Wall -o $@ t_fstep.c
|
||||
t_thread_rt: t_thread_rt.c ../nvn/nvn_rt.h
|
||||
clang -O1 -Wall -o $@ t_thread_rt.c
|
||||
t_link_drain: t_link_drain.c ../nvn/nvn_link_drain.h
|
||||
clang -O1 -Wall -o $@ t_link_drain.c
|
||||
t_thermal: t_thermal.c $(MTL_T_DEP)
|
||||
clang $(CFLAGS) -fobjc-arc -o $@ t_thermal.c $(MTL_T_SRC) ../nvn/nvn_mtl.m $(FW)
|
||||
t_thermal_tsan: t_thermal.c $(MTL_T_DEP)
|
||||
@@ -235,6 +237,8 @@ check_t_present_snap: t_present_snap
|
||||
DM_NVN_ENC_THREAD=1 MTL_DEBUG_LAYER=1 ./t_present_snap resize
|
||||
DM_NVN_ENC_THREAD=0 MTL_DEBUG_LAYER=1 ./t_present_snap resize
|
||||
DM_NVN_ENC_THREAD=0 MTL_DEBUG_LAYER=1 ./t_present_snap queued
|
||||
DM_PRESENT_LINK=0 MTL_DEBUG_LAYER=1 ./t_present_snap screen
|
||||
DM_PRESENT_LINK=0 MTL_DEBUG_LAYER=1 ./t_present_snap screen_snap
|
||||
DM_NVN_ENC_THREAD=1 MTL_DEBUG_LAYER=1 ./t_present_snap queued
|
||||
DM_NVN_ENC_THREAD=0 MTL_DEBUG_LAYER=1 ./t_present_snap ticket
|
||||
DM_NVN_ENC_THREAD=1 MTL_DEBUG_LAYER=1 ./t_present_snap ticket
|
||||
|
||||
@@ -438,6 +438,15 @@ int main(void) {
|
||||
check(first_len == want[c] && m.s.k == 2 && m.s.failed == 1, b);
|
||||
}
|
||||
}
|
||||
{ // A drain of standing frames (nvn_fstep_drain_cut), in ms against a 16.7 ms hold
|
||||
uint64_t pw = 20; check(nvn_fstep_drain_cut(33, 17, 16, 0, &pw) == 17 && pw == 4, "a drain of one tick: the frame shows its hold, the pacing wait loses the tick");
|
||||
pw = 10; check(nvn_fstep_drain_cut(17, 17, 6, 0, &pw) == 17 && pw == 10, "a drain inside the hold is pacing: nothing cut");
|
||||
pw = 10; check(nvn_fstep_drain_cut(30, 17, 6, 0, &pw) == 24 && pw == 4, "a late frame keeps its lateness beyond the drain");
|
||||
pw = 12; check(nvn_fstep_drain_cut(34, 33, 5, 0, &pw) == 33 && pw == 11, "only the part past the hold is cut (hold 2)");
|
||||
pw = 2; check(nvn_fstep_drain_cut(33, 17, 0, 16, &pw) == 17 && pw == 2, "a drain in a later acquire of the previous frame: the time, not the pacing wait");
|
||||
pw = 3; check(nvn_fstep_drain_cut(40, 17, 9, 0, &pw) == 37 && pw == 0, "a drain counted no larger than the pacing wait it was part of");
|
||||
pw = 0; check(nvn_fstep_drain_cut(0, 17, 0, 5, &pw) == 0, "the first frame (no previous start): nothing to cut");
|
||||
}
|
||||
printf("== %d checks, %d failed ==\n", checks, fail);
|
||||
return fail != 0;
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
// Unit test of the present queue's drain decision (../nvn/nvn_link_drain.h): which sequences of frames taken by the display-link callback ask the next acquire to wait
|
||||
// more ticks, and which leave the queue alone. Pure: no Metal, no clock; the times are the ones measured on Ocarina of Time (the game presents 1.15 ms after a tick).
|
||||
#include "../nvn/nvn_link_drain.h"
|
||||
#include <stdio.h>
|
||||
|
||||
static int checks, failed;
|
||||
#define CHECK(c, label) do { checks++; if (!(c)) { failed++; printf("FAIL: %s\n", label); } } while (0)
|
||||
|
||||
// Feed n frames taken one frame period apart, all with the same queue time and acquire wait; returns the first drain asked for (0 = none) and its frame in *at
|
||||
static int feed(nvn_link_drain *d, double *now, int n, double period, double age, double tick, double blocked, int ok, int *at) {
|
||||
for (int i = 0; i < n; i++) {
|
||||
*now += period;
|
||||
int k = nvn_link_drain_next(d, *now, age, tick, blocked, ok);
|
||||
if (k) { if (at) *at = i; return k; }
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
int main(void) {
|
||||
const double T30 = 1.0 / 30, T60 = 1.0 / 60, W = 0.00115;
|
||||
nvn_link_drain d = {0}; double now = 100; int at = -1;
|
||||
|
||||
// The spare ticks of a queue time
|
||||
CHECK(nvn_link_drain_spare(T30 - W, T30) == 0, "one 30 Hz tick less the present's delay: nothing to spare");
|
||||
CHECK(nvn_link_drain_spare(2 * T30 - W, T30) == 1, "a standing frame on the 30 Hz link: one tick");
|
||||
CHECK(nvn_link_drain_spare(2 * T60 - W, T60) == 1, "a standing frame on the 60 Hz link: one tick");
|
||||
CHECK(nvn_link_drain_spare(3 * T60 - W, T60) == 2, "a 33 ms hold on the 60 Hz link taken off the acquire's ticks, with a standing frame: two ticks");
|
||||
CHECK(nvn_link_drain_spare(T60 + 0.001, T60) == 0, "a frame that would land within the margin of its tick is not moved");
|
||||
CHECK(nvn_link_drain_spare(0.01, 0) == 0, "no tick period: nothing");
|
||||
|
||||
// A game on time with no standing frame is never drained
|
||||
CHECK(feed(&d, &now, 600, T30, T30 - W, T30, T30 - 0.005, 1, NULL) == 0 && d.drains == 0, "30 fps on time, one tick in the queue: no drain");
|
||||
|
||||
// The standing frame at 30 fps: one tick, after 2 s
|
||||
int k = feed(&d, &now, 600, T30, 2 * T30 - W, T30, T30 - 0.005, 1, &at);
|
||||
CHECK(k == 1, "a frame standing on the 30 Hz link: the acquire waits one tick more");
|
||||
CHECK(at >= 59 && at <= 61, "the drain comes after 2 s of standing frames, not before");
|
||||
CHECK(d.drains == 1 && d.run == 0, "the drain is counted and the run starts again");
|
||||
CHECK(feed(&d, &now, 600, T30, T30 - W, T30, T30 - 0.005, 1, NULL) == 0, "after the drain the frames wait one tick: no further drain");
|
||||
|
||||
// 60 fps: the frame count is reached before the 2 s
|
||||
d = (nvn_link_drain){0};
|
||||
k = feed(&d, &now, 600, T60, 2 * T60 - W, T60, T60 - 0.004, 1, &at);
|
||||
CHECK(k == 1 && at >= 119 && at <= 121, "a frame standing on the 60 Hz link: one tick after 2 s");
|
||||
|
||||
// A slow frame rate reaches 2 s before 30 frames: the frame count holds it back
|
||||
d = (nvn_link_drain){0};
|
||||
k = feed(&d, &now, 100, 0.1, 2 * T30 - W, T30, 0.02, 1, &at);
|
||||
CHECK(k == 1 && at == LINK_DRAIN_TAKES - 1, "at least 30 frames in a row whatever the time");
|
||||
|
||||
// The 60 Hz link holding frames 33 ms, taken off the acquire's ticks with a standing frame (fixed-rate fullscreen at 30 fps)
|
||||
d = (nvn_link_drain){0};
|
||||
CHECK(feed(&d, &now, 600, T30, 3 * T60 - W, T60, 2 * T60 - 0.005, 1, NULL) == 2, "two ticks of the 60 Hz link");
|
||||
|
||||
// The shortest queue time of the run decides
|
||||
d = (nvn_link_drain){0};
|
||||
feed(&d, &now, 40, T30, 3 * T30 - W, T30, 0.02, 1, NULL);
|
||||
feed(&d, &now, 1, T30, 2 * T30 - W, T30, 0.02, 1, NULL);
|
||||
CHECK(feed(&d, &now, 600, T30, 3 * T30 - W, T30, 0.02, 1, NULL) == 1, "one frame of the run waited only one tick too long: one tick, not two");
|
||||
|
||||
// A game that does not wait in its acquire keeps its standing frame (frames of 16-17.5 ms at 60 fps: the queue is its slack)
|
||||
d = (nvn_link_drain){0};
|
||||
CHECK(feed(&d, &now, 600, T60, 2 * T60 - W, T60, 0, 1, NULL) == 0, "the game never waited for the link: no drain");
|
||||
CHECK(feed(&d, &now, 600, T60, 2 * T60 - W, T60, 0.001, 1, NULL) == 0, "a 1 ms wait is not room to spare");
|
||||
CHECK(feed(&d, &now, 600, T30, 2 * T30 - W, T30, 0.004, 1, NULL) == 0, "4 ms of a 33 ms tick is not room to spare");
|
||||
|
||||
// One frame without room, an emptied queue or a take that does not count starts the run again
|
||||
d = (nvn_link_drain){0};
|
||||
for (int i = 0; i < 20; i++) {
|
||||
CHECK(feed(&d, &now, 50, T30, 2 * T30 - W, T30, 0.02, 1, NULL) == 0, "50 standing frames are under 2 s");
|
||||
int why = i % 3;
|
||||
nvn_link_drain_next(&d, now += T30, why == 0 ? T30 - W : 2 * T30 - W, T30, why == 1 ? 0 : 0.02, why != 2);
|
||||
CHECK(d.run == 0, why == 0 ? "a frame taken on its first tick ends the run" : why == 1 ? "a frame the game did not wait before ends the run" : "a take that does not count ends the run");
|
||||
}
|
||||
CHECK(d.drains == 0, "interrupted runs never drain");
|
||||
CHECK(feed(&d, &now, 600, T30, 2 * T30 - W, T30, 0.02, 0, NULL) == 0, "takes that do not count (present snapshots, rescue) never drain");
|
||||
|
||||
printf("t_link_drain: %d checks, %d failed\n", checks, failed);
|
||||
return failed != 0;
|
||||
}
|
||||
@@ -152,6 +152,19 @@ int main(int argc, char **argv) { @autoreleasepool {
|
||||
CHECK(g_link_tick_n == tick && test_now - start == 5000000ull, "timeout reaches its deadline without inventing ticks");
|
||||
test_silent = 0;
|
||||
CHECK(mtl_link_wait_ticks(2, 10000000ull) && g_link_tick_n - tick == 2, "ticks resume from the last successful wait after timeout");
|
||||
// A drain of standing frames the display-link callback asked for (nvn_link_drain.h): one wait takes the extra ticks, once, and reports them as pacing
|
||||
atomic_store(&g_link_drain_req, 1); tick = g_link_tick_n;
|
||||
CHECK(mtl_link_wait_ticks(1, 100000000ull) && g_link_tick_n - tick == 2, "a drain request makes one wait a tick longer");
|
||||
CHECK(atomic_load(&g_link_drained) == 1 && !atomic_load(&g_link_drain_req), "the drain is counted and its request used up");
|
||||
(void)mtl_link_drain_take_ns();
|
||||
CHECK(mtl_link_drain_take_ns() == 0, "the drain's time is handed out once");
|
||||
tick = g_link_tick_n;
|
||||
CHECK(mtl_link_wait_ticks(1, 100000000ull) && g_link_tick_n - tick == 1, "the wait after a drain is one tick again");
|
||||
atomic_store(&g_link_drain_req, 2); tick = g_link_tick_n;
|
||||
CHECK(mtl_link_wait_ticks(1, 100000000ull) && g_link_tick_n - tick == 3 && atomic_load(&g_link_drained) == 2, "a drain of two ticks");
|
||||
atomic_store(&g_link_drain_req, 1); g_link_tick_n += 4; waits = test_waits;
|
||||
CHECK(mtl_link_wait_ticks(1, 100000000ull) && test_waits == waits, "a game that fell behind does not wait for a drain");
|
||||
CHECK(atomic_load(&g_link_drained) == 2 && !atomic_load(&g_link_drain_req) && atomic_load(&g_link_blocked_ns) == 0, "and the request is dropped, with no acquire wait reported");
|
||||
pid_t pid; int st = 1; extern char **environ; // the snapshot cases in a process of their own (mtl_snap_on is decided once)
|
||||
CHECK(!posix_spawn(&pid, argv[0], NULL, NULL, (char *[]){argv[0], "snap", NULL}, environ) && waitpid(pid, &st, 0) == pid && WIFEXITED(st) && !WEXITSTATUS(st), "the snapshot cases pass");
|
||||
printf("t_link_ticks: %d checks, %d failed\n", checks, failed); return failed != 0;
|
||||
|
||||
@@ -137,11 +137,17 @@ static void latency(void) { // Only variable-refresh fullscreen needs the late
|
||||
static void thirty(void) { // A 30 fps target runs the link at 30 Hz, except in fullscreen on a fixed-rate screen, where it stays at 60 Hz and the present interval paces the 30.
|
||||
reset(); test_fullscreen = 0; test_variable_refresh = 0; test_game_fps = 30;
|
||||
SilentDisplayLink *link = [SilentDisplayLink new]; g_link = link; g_link_started = 1;
|
||||
g_link_drain_on = 0; // standing frames not drained (DM_PRESENT_DRAIN=0, iOS): a window keeps the 30 Hz link
|
||||
link_sync(); CHECK("a window at 30 fps takes the 30 Hz link", g_link_mode == 3 && link.preferredFrameRateRange.preferred == 30 && mtl_link_rate() == 30);
|
||||
test_fullscreen = 1; link_sync(); CHECK("fullscreen on a fixed-rate screen at 30 fps keeps the 60 Hz link", g_link_mode == 1 && link.preferredFrameRateRange.preferred == 60 && mtl_link_rate() == 60);
|
||||
test_variable_refresh = 1; link_sync(); CHECK("fullscreen on a variable-refresh screen at 30 fps takes the 30 Hz link", g_link_mode == 3 && link.preferredFrameRateRange.preferred == 30);
|
||||
test_variable_refresh = 0; link_sync(); CHECK("back on a fixed-rate screen: the 60 Hz link again", g_link_mode == 1 && link.preferredFrameRateRange.preferred == 60);
|
||||
test_fullscreen = 0; link_sync(); CHECK("leaving fullscreen: the 30 Hz link again", g_link_mode == 3 && link.preferredFrameRateRange.preferred == 30);
|
||||
g_link_drain_on = 1; // with the drain a window at 30 fps keeps the 60 Hz link, where a frame waits half as long for its tick; fullscreen is as before
|
||||
link_sync(); CHECK("with the drain a window at 30 fps keeps the 60 Hz link", g_link_mode == 1 && link.preferredFrameRateRange.preferred == 60 && mtl_link_rate() == 60);
|
||||
test_fullscreen = 1; test_variable_refresh = 1; link_sync(); CHECK("with the drain variable-refresh fullscreen at 30 fps still takes the 30 Hz link", g_link_mode == 3);
|
||||
test_variable_refresh = 0; link_sync(); CHECK("with the drain fixed-rate fullscreen at 30 fps keeps the 60 Hz link", g_link_mode == 1);
|
||||
test_fullscreen = 0; link_sync(); CHECK("with the drain, back in a window: the 60 Hz link", g_link_mode == 1 && link.preferredFrameRateRange.preferred == 60);
|
||||
test_game_fps = 60; link_sync(); CHECK("60 fps in a window: the 60 Hz link", g_link_mode == 1 && link.preferredFrameRateRange.preferred == 60);
|
||||
g_link = nil; g_link_started = 0;
|
||||
}
|
||||
|
||||
@@ -243,10 +243,65 @@ static void queued_case(void) {
|
||||
h_nvnWindowFinalize((NVNwindow *)&win); h_nvnQueueFinish(&fixture_queue);
|
||||
h_nvnCommandBufferFinalize(&command); h_nvnEventFinalize(&event); h_nvnMemoryPoolFinalize(&pool); free(memory);
|
||||
}
|
||||
// The acquire's wait for the screen without the display link (mtl_present_screen_wait, DM_PRESENT_DEPTH 1): presents queued against the newest one the presented handlers reported
|
||||
static void *screen_report_later(void *arg) { usleep(20000); pres_seen((uint64_t)(uintptr_t)arg, -1); return NULL; }
|
||||
static void screen_case(void) {
|
||||
const double per = 0.02; // timeout 2 periods = 40 ms
|
||||
pthread_mutex_lock(&g_pq_mu); uint64_t base = g_pq_in; pthread_mutex_unlock(&g_pq_mu);
|
||||
// A screen that has reported no present at all (newest seen 0: a window covered from its first frame, a headless run): one timeout, then no more waits
|
||||
if (!atomic_load(&g_pres_seen)) {
|
||||
pthread_mutex_lock(&g_pq_mu); g_pq_in = base + 3; pthread_mutex_unlock(&g_pq_mu);
|
||||
uint64_t to0 = atomic_load(&g_sdw_to), t0 = now_ns(), w = mtl_present_screen_wait(per), dt = now_ns() - t0;
|
||||
CHECK("screen: no report ever, the first wait times out after two periods", w > 0 && dt >= 38000000ull && atomic_load(&g_sdw_to) == to0 + 1);
|
||||
int fast = 1;
|
||||
for (int i = 0; i < 3; i++) { t0 = now_ns(); w = mtl_present_screen_wait(per); fast &= w == 0 && now_ns() - t0 < 5000000ull; }
|
||||
CHECK("screen: no report ever, then no wait while it stays silent (newest seen 0)", fast);
|
||||
pthread_mutex_lock(&g_pq_mu); g_pq_in = base; pthread_mutex_unlock(&g_pq_mu);
|
||||
pres_seen(base + 1, -1); base++; // the screen's first report ends the silence
|
||||
pthread_mutex_lock(&g_pq_mu); g_pq_in = base; pthread_mutex_unlock(&g_pq_mu);
|
||||
}
|
||||
pres_seen(base, -1);
|
||||
pthread_mutex_lock(&g_pq_mu); g_pq_in = base + 1; pthread_mutex_unlock(&g_pq_mu);
|
||||
uint64_t t0 = now_ns(); uint64_t w = mtl_present_screen_wait(per);
|
||||
CHECK("screen: one present not yet shown, depth 1: no wait", w == 0 && now_ns() - t0 < 5000000ull && g_sdw_depth == 1);
|
||||
pthread_mutex_lock(&g_pq_mu); g_pq_in = base + 3; pthread_mutex_unlock(&g_pq_mu);
|
||||
pthread_t th; pthread_create(&th, NULL, screen_report_later, (void *)(uintptr_t)(base + 2));
|
||||
t0 = now_ns(); w = mtl_present_screen_wait(per); uint64_t dt = now_ns() - t0; pthread_join(th, NULL);
|
||||
CHECK("screen: three queued waits until the screen reports the second", w > 0 && dt >= 15000000ull && dt < 38000000ull);
|
||||
pthread_mutex_lock(&g_pq_mu); g_pq_in = base + 5; pthread_mutex_unlock(&g_pq_mu);
|
||||
uint64_t to0 = atomic_load(&g_sdw_to); t0 = now_ns(); w = mtl_present_screen_wait(per); dt = now_ns() - t0;
|
||||
CHECK("screen: a silent screen times out after two periods", w > 0 && dt >= 38000000ull && dt < 80000000ull && atomic_load(&g_sdw_to) == to0 + 1);
|
||||
t0 = now_ns(); w = mtl_present_screen_wait(per);
|
||||
CHECK("screen: then no wait while the screen stays silent", w == 0 && now_ns() - t0 < 5000000ull);
|
||||
pthread_create(&th, NULL, screen_report_later, (void *)(uintptr_t)(base + 3)); pthread_join(th, NULL);
|
||||
t0 = now_ns(); w = mtl_present_screen_wait(per); dt = now_ns() - t0;
|
||||
CHECK("screen: a new report brings the wait back", w > 0 && dt >= 38000000ull);
|
||||
pres_seen(base + 5, -1);
|
||||
t0 = now_ns(); w = mtl_present_screen_wait(per);
|
||||
CHECK("screen: all shown, no wait", w == 0 && now_ns() - t0 < 5000000ull);
|
||||
// counted in the game's presents: the game recorded frame 1002's present while the replay has queued only up to frame 1000's (a stale g_pq_in would release at once)
|
||||
pthread_mutex_lock(&g_pq_mu); g_pq_in = base + 10; pthread_mutex_unlock(&g_pq_mu);
|
||||
g_pres_frm[(base + 10) % PRING] = 1000; g_pres_frm[(base + 11) % PRING] = 1001;
|
||||
pres_seen(base + 10, -1); mtl_present_recorded(1002);
|
||||
pthread_create(&th, NULL, screen_report_later, (void *)(uintptr_t)(base + 11));
|
||||
t0 = now_ns(); w = mtl_present_screen_wait(per); dt = now_ns() - t0; pthread_join(th, NULL);
|
||||
CHECK("screen: counted in the game's presents, waits for frame 1001's present although the replay's count is caught up", w > 0 && dt >= 15000000ull && dt < 38000000ull && atomic_load(&g_seen_frame) == 1001);
|
||||
t0 = now_ns(); w = mtl_present_screen_wait(per);
|
||||
CHECK("screen: frame 1001 shown, frame 1002 recorded: no wait at depth 1", w == 0 && now_ns() - t0 < 5000000ull);
|
||||
atomic_store(&g_rec_frame, 0);
|
||||
pthread_mutex_lock(&g_pq_mu); g_pq_in = base; pthread_mutex_unlock(&g_pq_mu);
|
||||
}
|
||||
// With present snapshots the game runs a frame ahead of the screen on purpose and their ring paces it: the screen wait stays off, as the display link's drain does
|
||||
static void screen_snap_case(void) {
|
||||
pthread_mutex_lock(&g_pq_mu); uint64_t base = g_pq_in; g_pq_in = base + 3; pthread_mutex_unlock(&g_pq_mu);
|
||||
uint64_t t0 = now_ns(), w = mtl_present_screen_wait(0.02);
|
||||
CHECK("screen: with present snapshots, three queued and none shown: no wait", mtl_snap_on() && w == 0 && now_ns() - t0 < 5000000ull);
|
||||
pthread_mutex_lock(&g_pq_mu); g_pq_in = base; pthread_mutex_unlock(&g_pq_mu);
|
||||
}
|
||||
int main(int argc, char **argv) { @autoreleasepool {
|
||||
alarm(15); setbuf(stdout, NULL);
|
||||
if (argc != 2) return 2;
|
||||
setenv("DM_PRESENT_SNAP", "1", 1); setenv("DM_PRESENT_HZ", "0", 1);
|
||||
setenv("DM_PRESENT_SNAP", strcmp(argv[1], "screen") ? "1" : "0", 1); setenv("DM_PRESENT_HZ", "0", 1); // the screen wait is off with snapshots (screen_snap)
|
||||
mtl_init();
|
||||
NVNdeviceBuilder db = {0}; h_nvnDeviceBuilderSetDefaults(&db); CHECK("fixture device initialized", h_nvnDeviceInitialize(&fixture_device, &db));
|
||||
NVNqueueBuilder qb = {0}; h_nvnQueueBuilderSetDefaults(&qb); h_nvnQueueBuilderSetDevice(&qb, &fixture_device);
|
||||
@@ -257,6 +312,8 @@ int main(int argc, char **argv) { @autoreleasepool {
|
||||
else if (!strcmp(argv[1], "resize")) resize_case();
|
||||
else if (!strcmp(argv[1], "queued")) queued_case();
|
||||
else if (!strcmp(argv[1], "ticket")) ticket_case();
|
||||
else if (!strcmp(argv[1], "screen")) screen_case();
|
||||
else if (!strcmp(argv[1], "screen_snap")) screen_snap_case();
|
||||
else return 2;
|
||||
printf("present snapshots: %d checks, %d failed\n", checks, failed); return failed != 0;
|
||||
} }
|
||||
@@ -556,6 +556,7 @@ One line per symptom in the [subsystem references](../reference/): what you see
|
||||
- an Unreal Engine game holds 30 fps with spare CPU and GPU time and asks for present interval 2; `present_interval display` alone does not help, as the engine's game thread sleeps out its own frame limit. → [Unreal's frame limit and present interval, found by name](../reference/frame-rate.md#unreals-frame-limit-and-present-interval-found-by-name)
|
||||
- an Unreal Engine game with `fps_target 60` asks for present interval 1 (`main: Unreal rhi.SyncInterval … 2 → 1 vsyncs`), and its menus reach 60, but its gameplay holds 30.0 fps with spare CPU and GPU time; the game sets no `t.MaxFPS`. → [Unreal's fixed frame rate, found by its reflection entry](../reference/frame-rate.md#unreals-fixed-frame-rate-found-by-its-reflection-entry)
|
||||
- a Frostbite game holds 30 fps with spare CPU and GPU time. Raising only the frame limit and the present interval gives 60 frames a second with the game at half speed (the match clock at 3.6 game seconds a second instead of 7.5). → [Frostbite's simulation rate, found by name](../reference/frame-rate.md#frostbites-simulation-rate-found-by-name)
|
||||
- with `DM_PRESENT_LINK=0`, at a frame cap the game holds, a frame reaches the screen 3–5 periods after the game queues it, and the lag steps up after hitches and stays: Ocarina of Time at a 30 fps cap, 92–155 ms from the game's enqueue to the screen (p50; p95 within 1–4 ms of it in each 600-frame window), against 32–45 ms when the game runs slower than its cap. → [Frames pile up for the screen at a cap the game holds, without the display link](../reference/frame-rate.md#frames-pile-up-for-the-screen-at-a-cap-the-game-holds-without-the-display-link)
|
||||
- the app is active and the game keeps running, but the picture freezes while display-link callbacks stop; the log repeatedly drops queued frames. → [Present thread rescues a silent display link](../reference/frame-rate.md#present-thread-rescues-a-silent-display-link)
|
||||
- `[longframe]` lines of 40–180 ms with no new pipelines, a short submit and normal GPU time, which read like CPU hitches in the game: single frames of 60–100 ms, or bursts of 5–12 frames, one of 140–180 ms and the rest about 40 ms. → [Long frames a test run makes itself](../reference/frame-rate.md#long-frames-a-test-run-makes-itself)
|
||||
- with the display link driving presents, a presented frame comes out black when three presents are on the GPU at once, or two after a dropped frame; on an M6 the same reuse also logs `[RED] display command buffer error` with `kIOGPUCommandBufferCallbackErrorPageFault`. → [A present command allocator is reused only after its own present completes](../reference/frame-rate.md#a-present-command-allocator-is-reused-only-after-its-own-present-completes)
|
||||
@@ -579,6 +580,7 @@ One line per symptom in the [subsystem references](../reference/): what you see
|
||||
- the game freezes for 0.5 s to half a minute, then carries on, at a moment the display link goes silent (a long frame, a screenshot, the window covered); `DM_NVN_TSV` shows `@wait_ms` growing frame by frame to seconds before it. → [The fallback pacer slept a lead the display link built up](../reference/frame-rate.md#the-fallback-pacer-slept-a-lead-the-display-link-built-up)
|
||||
- on a MacBook Air M2's fixed 60 Hz built-in display, the reporter measured about 50 ms from the game's present call to on-screen presentation with the display link, at both requested frame latencies 1 and 2, versus 29 ms with `DM_PRESENT_LINK=0`. After loading, all three runs held 60 fps with 0.3% of on-screen intervals outside 16.7 ± 2 ms and no frame-step changes. → [Fixed-rate display-link delay remains at latency 1](../reference/frame-rate.md#fixed-rate-display-link-delay-remains-at-latency-1)
|
||||
- at a 30 fps target, in fullscreen on a fixed 60 Hz screen, frames stay on screen 66.7 ms, often many in a row; in a window a late frame stays 50 ms. The `display link up to tick` lines count 300 ticks per 300 presents, but over 12-18 s instead of 10. → [The 30 Hz display link in fullscreen on a fixed-rate screen](../reference/frame-rate.md#the-30-hz-display-link-in-fullscreen-on-a-fixed-rate-screen)
|
||||
- input lag of one frame more than the display link needs, from the first late frame on and for the rest of the run: the `display link up to tick` line's `game enqueue to target display p50` sits one link tick above its value before the hiccup (60 fps in a window: 65.4 ms, then 82.0 ms; a 30 fps cap in a window: 115.4 ms from the first 300 frames on), with no dropped and no empty ticks. → [A frame standing in the present queue after a late frame](../reference/frame-rate.md#a-frame-standing-in-the-present-queue-after-a-late-frame)
|
||||
- autorelease work takes a measurable share of replay time, with temporary arena-buffer ownership traffic a few times per draw. → [Arena buffer ownership on allocation](../reference/frame-rate.md#arena-buffer-ownership-on-allocation)
|
||||
- a game runs at about 10 fps with little GPU work: the submit thread waits for a command allocator (`mtl_sub_begin` → `mtl_wait_at`), the GPU sits idle between encoders for hundreds of ms (`DM_NVN_GPUPROF`), the Metal 4 `SubmissionQueue` thread spends nearly all its time in `iokit_user_client_trap` (almost all system time), and the `memory up to frame` line shows a residency set of 10,000 objects or more. → [Dedicated c1 constants as slices of a bank](../reference/frame-rate.md#dedicated-c1-constants-as-slices-of-a-bank)
|
||||
- the submit thread waits for the GPU at the start of a submission (`mtl_sub_begin` → `mtl_wait_at`), many times a frame, in a game that makes many small submissions a frame; the `translation detail` line's `GPU waits so far` climbs with all 8 allocator pools in use. → [One command allocator for each of a frame's submissions](../reference/frame-rate.md#one-command-allocator-for-each-of-a-frames-submissions)
|
||||
|
||||
@@ -280,11 +280,14 @@ DM_PHONE_MOTION switch On iOS, whether the phone's own device motion drives play
|
||||
DM_PICTURE_FIT player `fill` scales the 16:9 picture on the iPhone and iPad until it covers the screen in landscape and crops the edges (a portrait or tabletop split and a TV stay fitted); `fit` or unset, the largest 16:9 rectangle with black bars. Launcher and in-game menu setting
|
||||
DM_PREEMPT switch `0` / `1` overrides the profile's `core_preempt`: also check already-runnable higher-priority peers on the caller's core after every thread SVC
|
||||
DM_PRELOAD diagnostic Set: on the Mac, runs the host's early background loading (`dm_host_preload_start`) as the iOS app does, to exercise that path
|
||||
DM_PRESENT_DEPTH switch `=<n>` (default 1): without the display link (`DM_PRESENT_LINK=0`), the acquire waits until at most n presents queued are not yet on screen or dropped, as the drawables' presented handlers report, so a frame cap the game holds no longer piles frames up in the present queue and the layer's drawables (not with present snapshots); `0` is the Switch's double buffering, which a Mac holds only below the screen's rate (about 40 fps at most at a 60 fps cap). Each 300 shown frames the log gives the time from the game's enqueue to the screen (`present: game enqueue to screen`) and these waits
|
||||
DM_PRESENT_DRAIN switch `1` / `0`: whether frames standing in the display link's present queue are drained (the acquire waits them out once, after the game has kept up for 2 s; no frame is dropped), and whether a 30 fps target keeps the 60 Hz display link in a window, where the drain halves a frame's wait for its tick; default on on the Mac, off on iOS
|
||||
DM_PRESENT_FIFO switch `0` makes the display link take the newest queued frame each tick, as before; by default it shows frames in order, at most one tick behind
|
||||
DM_PRESENT_HZ switch `=<N>`: the frequency of presentation pacing (default 60); `0` means no frame limit and is for performance profiling only
|
||||
DM_PRESENT_INTERVAL switch `display` presents one frame per display-link tick whatever interval the game sets; `game` follows the game's present interval (default: the profile's `present_interval`)
|
||||
DM_PRESENT_LATENCY switch `=1` or `2`: overrides the display link's preferred frame latency for every screen and window mode; larger positive values use 2 (default 2 in variable-refresh fullscreen, 1 otherwise)
|
||||
DM_PRESENT_LINK switch Present pacing: `0` acquires the drawable itself, `1` (the default) presents on a 60 Hz display link, `2` uses a 120 Hz display link with a frame every other tick. Unset, a 60 fps game in fullscreen on a variable-refresh screen that keeps its variable mode (no fixed-rate mode, or `DM_SCREEN_MATCH=0`) at a multiple of 120 Hz takes the 120 Hz link of `2`; a value set here holds in every window and screen mode
|
||||
DM_PRESENT_SCREEN switch `0` turns off the acquire's wait for the screen of `DM_PRESENT_DEPTH` (`ab` with `DM_AB`); default on
|
||||
DM_PRESENT_SNAP player `=<n>`: present snapshots, a ring of n host textures (2 to 4; `1` = 2) the presents are copied to so the game's swapchain texture is free at once; `0` off (default: the profile's `present_snap`)
|
||||
DM_PRESENT_UPSCALE player `metalfx` scales a picture smaller than its rectangle on the screen through MetalFX's spatial scaler; `off` (the default) scales it bilinearly
|
||||
DM_PREV_PROGRAM switch What `oe::GetPreviousProgramIndex` answers (default -1, started from HOME); `oe::ExecuteProgram` sets it for the program it starts; a relaunch removes it
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 19 and column 104.
|
@@ -257,6 +257,16 @@ Frame pacing: the host's frame step, engine frame limiters, present intervals an
|
||||
|
||||
## Present interval and display rate
|
||||
|
||||
### Frames pile up for the screen at a cap the game holds, without the display link
|
||||
|
||||
- **Symptom:** with `DM_PRESENT_LINK=0`, at a frame cap the game holds, a frame reaches the screen 3–5 periods after the game queues it, and the lag steps up after hitches and stays: Ocarina of Time at a 30 fps cap, 92–155 ms from the game's enqueue to the screen (p50; p95 within 1–4 ms of it in each 600-frame window), against 32–45 ms when the game runs slower than its cap.
|
||||
- **Cause:** two clocks at the same rate with nothing between them. The acquire paces the game on the host's own clock (the texture's slot time from `nvn_pace`, `hle_nvn.c`), and a texture is the game's again once its present is committed to the GPU (`g_pq_done`), not once it is on screen. The present thread holds each frame for its period (`presentAfterMinimumDuration`). A present that reaches the screen late shifts every later one, while the game keeps queuing at the cap, so each late present adds a period of queue for good, until the swapchain, the present queue and the layer's drawables are full. When the game is slower than the cap, the screen outruns it and the queue stays empty. The display link has its own form of this: [A frame standing in the present queue after a late frame](#a-frame-standing-in-the-present-queue-after-a-late-frame).
|
||||
- **Fix:** the acquire also waits until the game's present of `DM_PRESENT_DEPTH` (default 1) frames back is on screen or dropped, as the drawables' presented handlers report (`mtl_present_screen_wait`, `nvn_mtl.m`). It counts the game's own presents (the frame of its newest present recorded in the NVN queue, `mtl_present_recorded`), not the presents the queue worker has replayed: that count lags the game by a varying amount, and against it the acquire was released early and then held, so the game's present calls ran 25, 25, 48 ms apart at a 30 fps cap while the screen showed every frame for 33.3 ms. The wait is the frame's pacing for the frame step, unlike the display link's drain: at a cap the game holds it waits on nearly every frame, and a frame it lengthens past its hold is one the screen showed late, which the frame step must count and pay back. Taken out of the frame's time as a drain is, it threw those missed refreshes away: Mario Kart World without the link at the 60 setting (M4 Pro, ProMotion window, a 40 ms hitch every 600 frames) ran 0.983–0.992 of real time over 1,800-present windows, against 1.000 counted as pacing. The present after an acquire the wait released starts the pacer (`nvn_pace`) from that release, so the pacer keeps the screen's phase instead of paying the wait back with short frames. Not with present snapshots, which run the game a frame ahead on purpose and are paced by their ring. Depth 1 is what the Switch does for a game with three swapchain textures (the acquire blocks until the screen lets go of the texture it hands out), the count the games checked here use. `0` is the Switch's double buffering, and a Mac cannot hold it at 60 fps: a present reaches the screen about 24 ms after the game queues it (M4 Pro, ProMotion screen, window or fullscreen), so a game that waits for its own last frame before starting the next runs at most about 40 fps (Cuphead at 60 fps: 40.0 fps, 24 ms from enqueue to screen, against 60 fps and 33 ms at depth 1; Mario Kart World at the 60 setting: the frame step stuck at hold 2, 28.7–29.4 fps and 0.965–0.973 of real time). It holds where the game's work plus that path fits the period, as Cuphead at a 30 fps cap (30 fps, 32 against 66 ms), but not Mario Kart World at hold 2. A depth that drops to 0 only while that fits would need trials whose failures show as dropped frames, for a gain only below the screen's rate on this path, which the display link replaces by default: not done. A larger depth only caps the queue higher (depth 2: about 90 ms at 30 fps, and the uneven present calls stayed). The wait gives up after two periods and stays off until the handlers report again (a covered window, a screen asleep, a headless run), also when they have reported nothing yet: the first version marked the silence with the newest ticket seen, 0 there, which read as not silent, so a screen that never reported held every acquire two periods. `DM_PRESENT_SCREEN=0` turns it off. Every 300 shown frames the log gives `present: game enqueue to screen` p50 / p95 / max, the waits, and how late the presented handlers run (0.5 ms on the M2).
|
||||
- **Measured** (M2 MacBook Air, macOS 27.0, fullscreen, 700 frames a run, one run each): at the 30 fps cap, game enqueue to screen p50 56.5–65.2 ms against 108.6–149.4, frame time p50 / p95 33.33 / 33.64 against 33.34 / 33.54; at the 60 setting, where the route runs about 40 fps, p95 34.0–38.5 ms against up to 78.8, frame time 22.61 / 28.45 against 22.52 / 27.42.
|
||||
- **Check:** `make -C dm/gfx/tests check_t_present_snap` (`screen`: a screen that never reported, no wait at depth, a wait that ends with the report, the timeout and its silence, the report that brings the wait back, and the wait counted in the game's presents while the replay's count has caught up; `screen_snap`: no wait with present snapshots);
|
||||
- **Found on:** [The Legend of Zelda: Ocarina of Time](../../dm/games/0400486024DEC000/README.md) (M2 MacBook Air, macOS 27.0, fullscreen, 30 fps cap).
|
||||
- **Checked on** an M4 Pro MacBook Pro (ProMotion screen, macOS 27.2), 40 s title-screen runs with a 40 ms hitch every 600 frames, game enqueue to screen p50 with the wait off → on: [Cuphead](../../dm/games/0100A5C00D162000/README.md) at 60 fps in a window 91 → 33 ms, at a 30 fps cap in a window 92 → 66 ms, at 60 fps in fullscreen switched to fixed 60 Hz 60 → 33 ms, 33 ms in variable-refresh fullscreen (`DM_SCREEN_MATCH=0`) and 53 ms at a 30 fps cap in fullscreen, every run at its cap with no timeout; [Fire Emblem: Three Houses](../../dm/games/010055D009F78000/README.md) menus at 60 fps, 24–43 → 24–31 ms. In the Cuphead runs the wait held each frame 16.5 ms at 60 fps and 25 ms at 30 fps: it is the pacing. One fullscreen start gave up once before the screen had reported a frame (newest seen 0), the case the silence flag covers.
|
||||
|
||||
### Present thread rescues a silent display link
|
||||
|
||||
- **Symptom:** the app is active and the game keeps running, but the picture freezes while display-link callbacks stop; the log repeatedly drops queued frames.
|
||||
@@ -454,11 +464,23 @@ Frame pacing: the host's frame step, engine frame limiters, present intervals an
|
||||
|
||||
- **Symptom:** at a 30 fps target, in fullscreen on a fixed 60 Hz screen, frames stay on screen 66.7 ms, often many in a row; in a window a late frame stays 50 ms. The `display link up to tick` lines count 300 ticks per 300 presents, but over 12-18 s instead of 10.
|
||||
- **Cause:** at a 30 fps target `link_sync` runs the display link at 30 Hz, in a window and in fullscreen alike: on a 60 Hz screen `link_range` takes 30 Hz with no virtual ticks, and `front_screen_match` changes nothing. In fullscreen, at frame latency 1, the system calls back 32.8 ms before the target display time, one tick of that link (about 50 ms in a window). There the link skipped ticks: over two walks it called back 16.5-25.4 times a second in 8 of the 30 windows of 300 presents; in one run also in 48 of the first 58 frames, with 0.3-1.2 ms of GPU each, and in 222 frames in a row with a GPU span of 24-40 ms and no wait for a sync, a texture or the present queue. A skipped tick keeps the frame on screen a whole 33.3 ms more, and the game, paced by the ticks (`mtl_link_wait_tick`), presents 66.7 ms apart too. In a window the same link called back 30.0 times a second. Why the system skips ticks there is **open**; it resembles the late presents of [frame latency 2](#frame-latency-2-for-the-display-link-in-fullscreen).
|
||||
- **Fix:** `link_30hz` (`nvn_mtl.m`): in fullscreen on a fixed-rate screen (`front_fullscreen`, not `front_screen_variable_refresh`) the link stays at 60 Hz at a 30 fps target. The present interval paces the 30, as it does interval-2 frames on the 60 Hz link: the acquire waits two ticks and the callback keeps each frame on screen for its period (`g_link_hold_until`). A frame that misses its refresh shows 16.7 ms later. Windows, variable-refresh fullscreen and iOS keep the 30 Hz link.
|
||||
- **Fix:** `link_30hz` (`nvn_mtl.m`): in fullscreen on a fixed-rate screen (`front_fullscreen`, not `front_screen_variable_refresh`) the link stays at 60 Hz at a 30 fps target. The present interval paces the 30, as it does interval-2 frames on the 60 Hz link: the acquire waits two ticks and the callback keeps each frame on screen for its period (`g_link_hold_until`). A frame that misses its refresh shows 16.7 ms later. Variable-refresh fullscreen and iOS keep the 30 Hz link; a window keeps it only while standing frames are not drained ([A frame standing in the present queue after a late frame](#a-frame-standing-in-the-present-queue-after-a-late-frame)).
|
||||
- **Found on:** [The Legend of Zelda: Ocarina of Time](../../dm/games/0400486024DEC000/README.md) on a MacBook Air M4 (60 Hz built-in screen, macOS 27.2) at `DM_FPS_TARGET=30`, with LeonardoBai12's frame-delta change, which gives `main` the frame-step state page that applies the cap. On its walk in fullscreen (180 s of scripted stick pushes outside Link's house): 24.2 and 27.7 fps, frame p99 71.5 and 69.1 ms, 996 and 388 frames over 50 ms in two runs before; 29.7 fps, p99 38.4 ms and 7 over 50 ms after, with the link at 57-60 callbacks a second, against 29.7 fps, p99 38.4 ms and 3 over 50 ms in a window. The median time from the game's present to the target display time went from 91 to 76 ms (109 in a window).
|
||||
- **Check:** `make -C dm/gfx/tests GAME=<id> check_t_present_rescue` (`thirty`: the link's mode and range at 30 fps in a window, in fixed-rate and variable-refresh fullscreen, and back).
|
||||
- **Not checked:** variable-refresh fullscreen at 30 fps, external fixed-rate screens, other games at a 30 fps target, and the power cost of 60 callbacks a second instead of 30.
|
||||
|
||||
### A frame standing in the present queue after a late frame
|
||||
|
||||
- **Symptom:** input lag of one frame more than the display link needs, from the first late frame on and for the rest of the run: the `display link up to tick` line's `game enqueue to target display p50` sits one link tick above its value before the hiccup (60 fps in a window: 65.4 ms, then 82.0 ms; a 30 fps cap in a window: 115.4 ms from the first 300 frames on), with no dropped and no empty ticks.
|
||||
- **Cause:** the display-link callback wakes the acquire (`mtl_link_wait_ticks`) and then takes a frame from the present queue, so a frame presented right after a tick (Ocarina of Time: 1.15 ms after it) waits for the next tick. After one late frame the acquire returns at once to catch up, two frames reach the queue before one tick, and the callback shows them in order, one per tick ([PR #31](https://github.com/seedds/nxnative/pull/31)'s rule, which keeps a slightly slow game from dropping frames). A game that keeps up then adds one frame per tick and the callback takes one: the second frame stands in the queue for good. On the 60 Hz link holding frames 33 ms (a 30 fps target in fixed-rate fullscreen) the frames were also taken on the ticks between the acquire's: three ticks in the queue.
|
||||
- **Fix:** `nvn_link_drain.h` (`nvn_link_drain_next`, called by the callback through `link_drain_note` in `nvn_mtl.m`): when every frame taken over 2 s (and at least 30 frames) waited a whole link tick or more longer than it had to, and the acquire had waited for the link before each (at least 15% of a tick and 2 ms: the game has room to spare), the next acquire waits those ticks more, once (`mtl_link_wait_ticks`). The callback shows the queued frames meanwhile, so nothing is dropped or repeated on screen; the game loses the ticks of wall time once. The frame step takes the drain out of the frame's time and of its pacing wait as far as it made the frame longer than its hold (`nvn_fstep_drain_cut` in `nvn_fstep.h`, from `fstep_tick` in `hle_nvn.c` with `mtl_link_drain_take_ns`), so it is neither a late frame nor debt; the `frame step: game time` line counts the frames it shortened. The wait for the screen without the link is not cut so ([Frames pile up for the screen at a cap the game holds, without the display link](#frames-pile-up-for-the-screen-at-a-cap-the-game-holds-without-the-display-link)): there a frame past its hold is a refresh the screen missed. A game that does not wait in its acquire keeps its standing frame. Not with present snapshots (they run the game ahead on purpose) and not on the 120 Hz link. `DM_PRESENT_DRAIN=0` turns it off; it is off by default on iOS, where it has not been measured.
|
||||
- **Found on:** [The Legend of Zelda: Ocarina of Time](../../dm/games/0400486024DEC000/README.md) (Switch 2) on a MacBook Pro M2 Pro (ProMotion screen), title screen (the `display link up to tick` line), 55 s runs, the same host with the drain on and off. Game enqueue to target display, p50: a 30 fps cap in a window 115.4 → 82.1 ms (one drain of 1 tick at frame 168); 60 fps in a window with `DM_TEST_PRESENT_LAG=600,40` 65.4 ms in every window of 300 frames, a drain about 2 s after each forced hiccup (before: 82.0 ms from the first hiccup on); a 30 fps cap in fullscreen (the screen switched to fixed 60 Hz) 82.1 → 48.8 ms (drains of 2, 1 and 1 ticks in the first 224 frames). No frames dropped by merging after the start, every present on its target (`display-link target to on screen` p50 0.02 ms), no frame step change.
|
||||
- **The link's rate at a 30 fps target:** with the drain, `link_30hz` (`nvn_mtl.m`) keeps the 60 Hz link in a window too (the 30 Hz link stays in variable-refresh fullscreen, with `DM_PRESENT_DRAIN=0`, with present snapshots and on iOS). A frame presented right after a tick waits one tick of the link, 33 ms on the 30 Hz link; on the 60 Hz link each frame is held two ticks, and the drain moves the game onto the ticks between the callback's takes, 15.5 ms in the queue. Same game and screen, a 30 fps cap in a window, 55 s runs: 82.0 → 65.4 ms (one drain of 2 ticks, or two of 1, in the first 230 frames; no frames dropped, every present on its target), and 115.4 ms on the 30 Hz link with `DM_PRESENT_DRAIN=0` as before; fullscreen unchanged at 48.8 ms. The cost is 60 callbacks a second instead of 30, most of them finding no frame to take (`empty ticks` in the `display link up to tick` line); its power cost was not measured.
|
||||
- **Check:** `t_present_rescue` (`thirty`: the link's mode at 30 fps in a window with and without the drain, and in both kinds of fullscreen); `make -C dm/gfx/tests t_link_drain && dm/gfx/tests/t_link_drain` (the decision: standing frames at 30 and 60 Hz, the 33 ms hold on the 60 Hz link, a game with no room, interrupted runs); `t_link_ticks` (one wait takes the extra ticks once, a game that fell behind drops the request); `t_fstep` (the drain's cut).
|
||||
- **Note:** the tick a frame still waits (33 ms at 30 fps) and the system's own delay in a window (49.85 ms from the callback to the screen at frame latency 1, HDR and SDR alike; 33.2 ms in fullscreen on the fixed 60 Hz mode) are not changed by this.
|
||||
- **Checked on** an M4 Pro MacBook Pro (ProMotion screen, macOS 27.2), 40 s title-screen runs with a 40 ms hitch every 600 frames (`DM_TEST_PRESENT_LAG=600,40`), game enqueue to target display p50 with `DM_PRESENT_DRAIN=0` → default: [Cuphead](../../dm/games/0100A5C00D162000/README.md) at 60 fps in a window 83 → 66 ms (a drain about 2 s after each hitch), at a 30 fps cap in a window 116 ms on the 30 Hz link → 66 ms on the 60 Hz one, at 60 fps in fullscreen switched to fixed 60 Hz 83 → 66 ms, at a 30 fps cap there 66 ms; in variable-refresh fullscreen (`DM_SCREEN_MATCH=0`) the 120 Hz link took 60 fps with no drain (50 ms), and the 30 Hz link at a 30 fps cap drained once in 40 s (116 ms, then 149 ms until the drain: the game ran 28.7–29.9 fps there, so the acquire rarely had room); [Fire Emblem: Three Houses](../../dm/games/010055D009F78000/README.md) menus at 60 fps 66–81 → 63–66 ms (15 drains in 130 s); [Mario Kart World](../../dm/games/0400C3F00006E000/README.md) title at the 60 setting 74–77 → 60–77 ms, game time 0.997–0.998 of real time against 1.000 (4–6 drains of one vsync each per 1,800 presents, taken out of the frame step), the same late frames and frame step changes.
|
||||
- **Not checked:** iOS; a game under load near its frame time with the drain (Mario Kart World's title has hitches of its own); a fixed-rate screen in a window; external screens.
|
||||
|
||||
## CPU cost and pacing
|
||||
|
||||
### Arena buffer ownership on allocation
|
||||
|
||||
Reference in new issue
Block a user