diff --git a/app/src/main/cpp/waylandcomp/src/compositor.c b/app/src/main/cpp/waylandcomp/src/compositor.c index ff1a33ed2..12d6b6d64 100644 --- a/app/src/main/cpp/waylandcomp/src/compositor.c +++ b/app/src/main/cpp/waylandcomp/src/compositor.c @@ -263,9 +263,11 @@ static struct wl_event_source *g_render_idle, *g_frame_timer; static int g_dirty; static int64_t g_dirty_since_ns; +volatile int g_render_on_commit = 1; +static int64_t g_rendered_tick_ns; #define PACE_BUFFERS 32 static struct { - unsigned ticks, ticks_late_2ms, renders, null_attaches, reattaches, presented, replaced, undrawn, distinct; + unsigned ticks, ticks_late_2ms, renders, commit_renders, null_attaches, reattaches, presented, replaced, undrawn, distinct; int64_t tick_late_ns, tick_late_max_ns, wait_ns, wait_max_ns; const void *buffers[PACE_BUFFERS]; uint64_t game_frames_seen; @@ -327,6 +329,7 @@ static struct { } g_perf; static void schedule_render(void); +static void on_commit_idle(void *data); static int64_t now_ns(void) { struct timespec ts; clock_gettime(CLOCK_MONOTONIC, &ts); @@ -2132,6 +2135,7 @@ static void render_scene(void) { g_dirty_since_ns = 0; } g_dirty = 0; + g_rendered_tick_ns = g_tick_vsync_ns; g_hud_fresh = 0; g_hdr_unimported = NULL; wl_list_for_each(s, &g_surfaces, link) s->drawn = 0; @@ -2296,11 +2300,22 @@ static int on_fallback_timer(void *data) { return 0; } +/* A new frame is drawn when it arrives instead of at the next screen tick, at most once per refresh, + while frames go straight back to the game (no compositor limit), without streaming or frame generation. */ +static int render_on_commit(void) { + return g_render_on_commit && g_release_unpaced && !g_render_idle && g_rendered_tick_ns != g_tick_vsync_ns && + !atomic_load(&g_stream_on) && !vkp_framegen_active(); +} + static void schedule_render(void) { if (!g_dirty && !g_dirty_since_ns) g_dirty_since_ns = now_ns(); g_dirty = 1; if (!g_display) return; - if (g_last_vsync_ns && now_ns() - g_last_vsync_ns < 100000000LL) return; + if (g_last_vsync_ns && now_ns() - g_last_vsync_ns < 100000000LL) { + if (render_on_commit()) + g_render_idle = wl_event_loop_add_idle(wl_display_get_event_loop(g_display), on_commit_idle, NULL); + return; + } if (g_fallback_armed) return; if (!g_fallback_timer) g_fallback_timer = wl_event_loop_add_timer(wl_display_get_event_loop(g_display), @@ -2314,6 +2329,13 @@ static int scene_waits_for_game(int64_t now) { return g_hud_surface && !g_hud_fresh && now - g_hud_last_ns < 100000000LL && vkp_framegen_active(); } +static void on_commit_idle(void *data) { + g_render_idle = NULL; + if (!g_dirty || g_rendered_tick_ns == g_tick_vsync_ns || scene_waits_for_game(now_ns())) return; + g_pace.commit_renders++; + render_scene(); +} + static void on_vsync(int64_t frame_time_ns) { int64_t now = now_ns(); g_perf.ticks++; @@ -3440,13 +3462,13 @@ static int on_stats_timer(void *data) { if (g_pace.ticks || g_pace.renders || game || g_pace.reattaches || g_pace.null_attaches || g_pace.distinct || g_pace.presented || g_pace.replaced || g_pace.undrawn) { droiddeck_log("pacing", "last 10 s: tick reaches compositor %.2f/%.2f ms late (%u ticks, %u over 2 ms) | " - "new frame waits %.2f/%.2f ms to be drawn (%u scenes) | %llu game frames, %u re-attached after an " + "new frame waits %.2f/%.2f ms to be drawn (%u scenes, %u on arrival) | %llu game frames, %u re-attached after an " "empty attach, %u empty attaches, %u distinct buffers | feedback %u shown, %u replaced before drawing, " "%u not drawn", g_pace.ticks ? (double)g_pace.tick_late_ns / 1e6 / g_pace.ticks : 0.0, (double)g_pace.tick_late_max_ns / 1e6, g_pace.ticks, g_pace.ticks_late_2ms, g_pace.renders ? (double)g_pace.wait_ns / 1e6 / g_pace.renders : 0.0, (double)g_pace.wait_max_ns / 1e6, - g_pace.renders, (unsigned long long)game, g_pace.reattaches, g_pace.null_attaches, g_pace.distinct, + g_pace.renders, g_pace.commit_renders, (unsigned long long)game, g_pace.reattaches, g_pace.null_attaches, g_pace.distinct, g_pace.presented, g_pace.replaced, g_pace.undrawn); } { diff --git a/app/src/main/cpp/waylandcomp/src/waylandcomp_jni.c b/app/src/main/cpp/waylandcomp/src/waylandcomp_jni.c index 675d4ac2c..fad36f282 100644 --- a/app/src/main/cpp/waylandcomp/src/waylandcomp_jni.c +++ b/app/src/main/cpp/waylandcomp/src/waylandcomp_jni.c @@ -36,6 +36,7 @@ extern void droiddeck_wayland_output_resized(void); extern void droiddeck_wayland_set_output_refresh_rate(int mhz); extern volatile int g_fps_limit; extern volatile int g_release_unpaced; +extern volatile int g_render_on_commit; extern volatile int g_hide_shell; extern volatile int g_zero_copy; extern volatile unsigned g_zero_copy_last; @@ -587,6 +588,12 @@ Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetLookName(JNIEnv * free(s); } +JNIEXPORT void JNICALL +Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetRenderOnCommit(JNIEnv *env, jclass clazz, jboolean on) { + g_render_on_commit = on ? 1 : 0; + __android_log_print(ANDROID_LOG_INFO, TAG, "render on commit %s", on ? "on" : "off"); +} + JNIEXPORT void JNICALL Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetFpsLimit(JNIEnv *env, jclass clazz, jint fps) { g_fps_limit = fps > 0 ? fps : 0; diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt index 77601e3a3..3c48bcc33 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt @@ -603,6 +603,7 @@ object SessionPrefs { fun mangoapp(context: Context): Boolean = prefs(context).getBoolean("mangoapp", true) fun vsyncThread(context: Context): Boolean = prefs(context).getBoolean("vsyncThread", true) + fun renderOnCommit(context: Context): Boolean = prefs(context).getBoolean("renderOnCommit", true) fun setMangoapp(context: Context, on: Boolean) { prefs(context).edit().putBoolean("mangoapp", on).apply() } fun zinkLazy(context: Context): Boolean = prefs(context).getBoolean("zinkLazy", true) diff --git a/app/src/main/java/com/droiddeck/launcher/wayland/CompositorHost.kt b/app/src/main/java/com/droiddeck/launcher/wayland/CompositorHost.kt index fcf57b951..ea06879fa 100644 --- a/app/src/main/java/com/droiddeck/launcher/wayland/CompositorHost.kt +++ b/app/src/main/java/com/droiddeck/launcher/wayland/CompositorHost.kt @@ -53,6 +53,7 @@ object CompositorHost { fpsLimit: Int, ): Boolean { ownVsyncThread = SessionPrefs.vsyncThread(context) + WaylandCompositor.nativeSetRenderOnCommit(SessionPrefs.renderOnCommit(context)) pace(refreshHz, fpsLimit) if (!SessionState.running) WaylandCompositor.nativeSetOutputSize(outputWidth, outputHeight) if (started) { diff --git a/app/src/main/java/com/droiddeck/launcher/wayland/WaylandCompositor.java b/app/src/main/java/com/droiddeck/launcher/wayland/WaylandCompositor.java index 206b18280..7aefad573 100644 --- a/app/src/main/java/com/droiddeck/launcher/wayland/WaylandCompositor.java +++ b/app/src/main/java/com/droiddeck/launcher/wayland/WaylandCompositor.java @@ -284,6 +284,8 @@ public final class WaylandCompositor { public static native void nativeSetFpsLimit(int fps); + public static native void nativeSetRenderOnCommit(boolean on); + public static native void nativeSetGpuTurbo(boolean on); public static native int nativeRaisePriority(int tid, int nice); diff --git a/tools/gamescope/PATCHES.md b/tools/gamescope/PATCHES.md index 0d7956456..a57c3bc82 100644 --- a/tools/gamescope/PATCHES.md +++ b/tools/gamescope/PATCHES.md @@ -181,3 +181,21 @@ The nested Wayland backend's input thread reads the host display, but steamcompm does not watch that file descriptor, so buffer releases and presentation feedback queued by that read could wait up to one refresh for steamcompmgr's next poll. The input thread now wakes steamcompmgr after each read. + +## 0123 commit: fence lifetime fixes from upstream + +Backport of upstream commits 0efe47c and 666c52b by Matthew Schwartz (ValveSoftware/gamescope). +Pending commits share ownership of their completion list with the Xwayland context, so a late +fence signal can no longer append to a list freed with the context; and a commit being destroyed +no longer hands the image waiter a new reference to itself. Both touch the code 0124 changes. + +## 0124 commit: mark a finished frame done at import + +Every game frame took two passes of steamcompmgr's loop: the import duplicated the buffer's +fence and handed the commit to the image waiter (epoll add), then the waiter thread saw the fence +signalled, removed and closed it and woke steamcompmgr again to handle the finished commit. +`update_wayland_res` now polls the fence without waiting first. A frame that is already finished +is marked done at once - no duplicate fence, no epoll add or delete, no waiter wake - and the main +loop handles it in the same pass, after the import (FIFO commits still wait for a vblank). The +`commit_ready_check` convar (default on, `gamescopectl commit_ready_check 0`) turns it off; the +`xwm` log counts fences ready at import and waited for, every 10 s. diff --git a/tools/gamescope/patches/0123-commit-fence-lifetime-upstream.patch b/tools/gamescope/patches/0123-commit-fence-lifetime-upstream.patch new file mode 100644 index 000000000..75e93b68a --- /dev/null +++ b/tools/gamescope/patches/0123-commit-fence-lifetime-upstream.patch @@ -0,0 +1,157 @@ +diff --git a/src/commit.cpp b/src/commit.cpp +index c9d0001..f2e0f0c 100644 +--- a/src/commit.cpp ++++ b/src/commit.cpp +@@ -105,14 +105,15 @@ bool commit_t::CloseFenceInternal() + if ( m_nCommitFence < 0 ) + return false; + +- // Will automatically remove from epoll! +- g_ImageWaiter.RemoveWaitable( this ); ++ // Do not recreate an Rc after deletion has started. ++ if ( HasLiveReferences() ) ++ g_ImageWaiter.RemoveWaitable( this ); + close( m_nCommitFence ); + m_nCommitFence = -1; + return true; + } + +-void commit_t::SetFence( int nFence, bool bMangoNudge, uint32_t uMangoMsgType, CommitDoneList_t *pDoneCommits ) ++void commit_t::SetFence( int nFence, bool bMangoNudge, uint32_t uMangoMsgType, const std::shared_ptr &pDoneCommits ) + { + std::unique_lock lock( m_WaitableCommitStateMutex ); + CloseFenceInternal(); +diff --git a/src/commit.h b/src/commit.h +index 20f881d..8603a9a 100644 +--- a/src/commit.h ++++ b/src/commit.h +@@ -1,6 +1,7 @@ + #include "steamcompmgr_shared.hpp" + #include "Utils/NonCopyable.h" + ++#include + #include + #include "main.hpp" + #include "rendervulkan.hpp" +@@ -34,7 +35,7 @@ struct commit_t final : public gamescope::RcObject, public gamescope::IWaitable, + + // Returns true if we had a fence that was closed. + bool CloseFenceInternal(); +- void SetFence( int nFence, bool bMangoNudge, uint32_t uMangoMsgType, CommitDoneList_t *pDoneCommits ); ++ void SetFence( int nFence, bool bMangoNudge, uint32_t uMangoMsgType, const std::shared_ptr &pDoneCommits ); + + bool ShouldPreemptivelyUpscale( GamescopeUpscaleFilter eFilter, GamescopeUpscaleScaler eScaler ); + +@@ -81,5 +82,5 @@ struct commit_t final : public gamescope::RcObject, public gamescope::IWaitable, + bool m_bMangoNudge = false; + // Typed mangoapp stream to nudge, 0 for none, never the legacy type. + uint32_t m_uMangoMsgType = 0; +- CommitDoneList_t *m_pDoneCommits = nullptr; // I hate this +-}; +\ No newline at end of file ++ std::shared_ptr m_pDoneCommits; // I hate this ++}; +diff --git a/src/steamcompmgr.cpp b/src/steamcompmgr.cpp +index 5fb9086..22aa907 100644 +--- a/src/steamcompmgr.cpp ++++ b/src/steamcompmgr.cpp +@@ -932,7 +932,7 @@ constexpr const T& clamp( const T& x, const T& min, const T& max ) + + extern bool g_bForceRelativeMouse; + +-CommitDoneList_t g_steamcompmgr_xdg_done_commits; ++std::shared_ptr g_steamcompmgr_xdg_done_commits = std::make_shared(); + + + static std::mutex s_KeysToCloseMutex; +@@ -8073,7 +8073,7 @@ bool handle_done_commit( steamcompmgr_win_t *w, xwayland_ctx_t *ctx, uint64_t co + // TODO: Merge these two functions. + void handle_done_commits_xwayland( xwayland_ctx_t *ctx, bool vblank, uint64_t vblank_idx ) + { +- std::lock_guard lock( ctx->doneCommits.listCommitsDoneLock ); ++ std::lock_guard lock( ctx->doneCommits->listCommitsDoneLock ); + + uint64_t next_refresh_time = g_SteamCompMgrVBlankTime.schedule.ulTargetVBlank; + +@@ -8090,7 +8090,7 @@ void handle_done_commits_xwayland( xwayland_ctx_t *ctx, bool vblank, uint64_t vb + uint64_t now = get_time_in_nanos(); + + // very fast loop yes +- for ( auto& entry : ctx->doneCommits.listCommitsDone ) ++ for ( auto& entry : ctx->doneCommits->listCommitsDone ) + { + steamcompmgr_win_t *entry_win = nullptr; + for ( steamcompmgr_win_t *w = ctx->list; w; w = w->xwayland().next ) +@@ -8130,12 +8130,12 @@ void handle_done_commits_xwayland( xwayland_ctx_t *ctx, bool vblank, uint64_t vb + } + } + +- ctx->doneCommits.listCommitsDone.swap( commits_before_their_time ); ++ ctx->doneCommits->listCommitsDone.swap( commits_before_their_time ); + } + + void handle_done_commits_xdg( bool vblank, uint64_t vblank_idx ) + { +- std::lock_guard lock( g_steamcompmgr_xdg_done_commits.listCommitsDoneLock ); ++ std::lock_guard lock( g_steamcompmgr_xdg_done_commits->listCommitsDoneLock ); + + uint64_t next_refresh_time = g_SteamCompMgrVBlankTime.schedule.ulTargetVBlank; + +@@ -8152,7 +8152,7 @@ void handle_done_commits_xdg( bool vblank, uint64_t vblank_idx ) + uint64_t now = get_time_in_nanos(); + + // very fast loop yes +- for ( auto& entry : g_steamcompmgr_xdg_done_commits.listCommitsDone ) ++ for ( auto& entry : g_steamcompmgr_xdg_done_commits->listCommitsDone ) + { + steamcompmgr_win_t *entry_win = nullptr; + for (const auto& xdg_win : g_steamcompmgr_xdg_wins) +@@ -8192,7 +8192,7 @@ void handle_done_commits_xdg( bool vblank, uint64_t vblank_idx ) + } + } + +- g_steamcompmgr_xdg_done_commits.listCommitsDone.swap( commits_before_their_time ); ++ g_steamcompmgr_xdg_done_commits->listCommitsDone.swap( commits_before_their_time ); + } + + gamescope::ConVar cv_mangoapp_use_output_timing{ "mangoapp_use_output_timing", true }; +@@ -8359,7 +8359,7 @@ static TempUpscaleImage_t *GetTempUpscaleImage( global_focus_t *pFocus, uint32_t + + gamescope::ConVar cv_surface_update_force_only_current_surface( "surface_update_force_only_current_surface", false, "Force updates to apply only to the current surface, ignoring commits for other surfaces." ); + +-void update_wayland_res(CommitDoneList_t *doneCommits, steamcompmgr_win_t *w, ResListEntry_t& reslistentry) ++void update_wayland_res(const std::shared_ptr &doneCommits, steamcompmgr_win_t *w, ResListEntry_t& reslistentry) + { + struct wlr_buffer *buf = reslistentry.buf; + +@@ -8632,7 +8632,7 @@ void check_new_xwayland_res(xwayland_ctx_t *ctx) + for ( uint32_t i = 0; i < tmp_queue.size(); i++ ) + { + steamcompmgr_win_t *w = find_win( ctx, tmp_queue[ i ].surf ); +- update_wayland_res( &ctx->doneCommits, w, tmp_queue[ i ]); ++ update_wayland_res( ctx->doneCommits, w, tmp_queue[ i ]); + } + } + +@@ -8645,7 +8645,7 @@ void check_new_xdg_res() + { + if ( xdg_win->xdg().surface.main_surface == tmp_queue[ i ].surf ) + { +- update_wayland_res( &g_steamcompmgr_xdg_done_commits, xdg_win.get(), tmp_queue[ i ] ); ++ update_wayland_res( g_steamcompmgr_xdg_done_commits, xdg_win.get(), tmp_queue[ i ] ); + break; + } + } +diff --git a/src/xwayland_ctx.hpp b/src/xwayland_ctx.hpp +index 81910a1..3a75650 100644 +--- a/src/xwayland_ctx.hpp ++++ b/src/xwayland_ctx.hpp +@@ -92,7 +92,7 @@ struct xwayland_ctx_t final : public gamescope::IWaitable + + std::unique_ptr cursor; + +- CommitDoneList_t doneCommits; ++ std::shared_ptr doneCommits = std::make_shared(); + + double accum_x = 0.0; + double accum_y = 0.0; diff --git a/tools/gamescope/patches/0124-commit-done-at-import.patch b/tools/gamescope/patches/0124-commit-done-at-import.patch new file mode 100644 index 000000000..9ac818e4e --- /dev/null +++ b/tools/gamescope/patches/0124-commit-done-at-import.patch @@ -0,0 +1,103 @@ +diff --git a/src/steamcompmgr.cpp b/src/steamcompmgr.cpp +index 22aa907..0aef598 100644 +--- a/src/steamcompmgr.cpp ++++ b/src/steamcompmgr.cpp +@@ -8359,6 +8359,33 @@ static TempUpscaleImage_t *GetTempUpscaleImage( global_focus_t *pFocus, uint32_t + + gamescope::ConVar cv_surface_update_force_only_current_surface( "surface_update_force_only_current_surface", false, "Force updates to apply only to the current surface, ignoring commits for other surfaces." ); + ++gamescope::ConVar cv_commit_ready_check( "commit_ready_check", true, "Check a new commit's fence at import; a finished frame is marked done in the same pass instead of through the image waiter." ); ++ ++// Set when update_wayland_res marks a commit done itself, so the main loop handles it in the same pass. ++static bool s_bXwaylandCommitsDoneAtImport = false; ++static bool s_bXdgCommitsDoneAtImport = false; ++ ++static bool commit_fence_ready_now( int nFd ) ++{ ++ struct pollfd pfd = { .fd = nFd, .events = POLLIN, .revents = 0 }; ++ return poll( &pfd, 1, 0 ) == 1 && ( pfd.revents & POLLIN ); ++} ++ ++static void note_commit_fence( bool bReadyAtImport ) ++{ ++ static uint64_t s_ulReady = 0, s_ulWaited = 0, s_ulLastLog = 0; ++ ( bReadyAtImport ? s_ulReady : s_ulWaited )++; ++ uint64_t now = get_time_in_nanos(); ++ if ( !s_ulLastLog ) ++ s_ulLastLog = now; ++ if ( now - s_ulLastLog >= 10'000'000'000ul ) ++ { ++ xwm_log.infof( "commit fences, last 10 s: %lu ready at import, %lu waited for", s_ulReady, s_ulWaited ); ++ s_ulReady = s_ulWaited = 0; ++ s_ulLastLog = now; ++ } ++} ++ + void update_wayland_res(const std::shared_ptr &doneCommits, steamcompmgr_win_t *w, ResListEntry_t& reslistentry) + { + struct wlr_buffer *buf = reslistentry.buf; +@@ -8602,7 +8629,11 @@ void update_wayland_res(const std::shared_ptr &doneCommits, st + struct wlr_dmabuf_attributes dmabuf = {0}; + if ( wlr_buffer_get_dmabuf( buf, &dmabuf ) ) + { +- fence = dup( dmabuf.fd[0] ); ++ // A finished buffer needs no fence of its own. ++ if ( cv_commit_ready_check && commit_fence_ready_now( dmabuf.fd[0] ) ) ++ bKnownReady = true; ++ else ++ fence = dup( dmabuf.fd[0] ); + } + else + { +@@ -8610,11 +8641,22 @@ void update_wayland_res(const std::shared_ptr &doneCommits, st + } + } + ++ if ( cv_commit_ready_check ) ++ { ++ if ( !bKnownReady && fence >= 0 && commit_fence_ready_now( fence ) ) ++ bKnownReady = true; ++ note_commit_fence( bKnownReady ); ++ } ++ + gpuvis_trace_printf( "pushing wait for commit %lu win %lx", newCommit->commitID, w->type == steamcompmgr_win_type_t::XWAYLAND ? w->xwayland().id : 0 ); + { + newCommit->SetFence( fence, mango_nudge, uMangoMsgType, doneCommits ); + if ( bKnownReady ) ++ { + newCommit->Signal(); ++ if ( cv_commit_ready_check ) ++ ( w->type == steamcompmgr_win_type_t::XWAYLAND ? s_bXwaylandCommitsDoneAtImport : s_bXdgCommitsDoneAtImport ) = true; ++ } + else + g_ImageWaiter.AddWaitable( newCommit.get() ); + } +@@ -9400,6 +9442,13 @@ void steamcompmgr_check_xdg(bool vblank, uint64_t vblank_idx) + } + + check_new_xdg_res(); ++ ++ // Commits marked done at import: handle them now rather than on the next wake. FIFO commits still wait for a vblank. ++ if ( s_bXdgCommitsDoneAtImport ) ++ { ++ s_bXdgCommitsDoneAtImport = false; ++ handle_done_commits_xdg( false, vblank_idx ); ++ } + } + + void update_edid_prop() +@@ -10512,6 +10561,14 @@ steamcompmgr_main(int argc, char **argv) + gamescope_xwayland_server_t *server = NULL; + for (size_t i = 0; (server = wlserver_get_xwayland_server(i)); i++) + check_new_xwayland_res(server->ctx.get()); ++ ++ // Commits marked done at import: handle them now rather than on the next wake. FIFO commits still wait for a vblank. ++ if ( s_bXwaylandCommitsDoneAtImport ) ++ { ++ s_bXwaylandCommitsDoneAtImport = false; ++ for (size_t i = 0; (server = wlserver_get_xwayland_server(i)); i++) ++ handle_done_commits_xwayland(server->ctx.get(), false, vblank_idx); ++ } + } + + diff --git a/tools/tests/test_render_on_commit.py b/tools/tests/test_render_on_commit.py new file mode 100644 index 000000000..4fe9f84a3 --- /dev/null +++ b/tools/tests/test_render_on_commit.py @@ -0,0 +1,148 @@ +import os +from pathlib import Path +import shutil +import subprocess +import sys +import tempfile +import unittest + +from test_output_refresh import SOURCE, extract_function + + +PREAMBLE = r''' +#include +#include +#include +#include + +struct wl_event_source { int armed; }; +static struct wl_event_source idle_source, timer_source; +static void (*idle_func)(void *); +static int idles_added, timers_armed, renders, window_requests, effects_changes, pose_changes; +static int64_t clock_ns; +static int g_display_storage; +static void *g_display = &g_display_storage; +static struct wl_event_source *g_render_idle, *g_fallback_timer; +static int g_fallback_armed, g_dirty, g_hud_fresh, framegen; +static void *g_hud_surface; +static int64_t g_dirty_since_ns, g_last_vsync_ns, g_tick_vsync_ns, g_hud_last_ns, g_rendered_tick_ns; +static int64_t g_refresh_ns = 16666667; +volatile int g_render_on_commit = 1; +volatile int g_release_unpaced = 1; +static atomic_int g_stream_on; +static struct { unsigned ticks, ticks_late_2ms, commit_renders; int64_t tick_late_ns, tick_late_max_ns; } g_pace; +static struct { unsigned ticks; } g_perf; +static int64_t now_ns(void) { return clock_ns; } +static void *wl_display_get_event_loop(void *display) { return display; } +static struct wl_event_source *wl_event_loop_add_idle(void *loop, void (*func)(void *), void *data) { + idles_added++; idle_func = func; return &idle_source; +} +static struct wl_event_source *wl_event_loop_add_timer(void *loop, int (*func)(void *), void *data) { return &timer_source; } +static int wl_event_source_timer_update(struct wl_event_source *source, int ms) { timers_armed++; return 0; } +static int vkp_framegen_active(void) { return framegen; } +static int vkp_apply_window_request(void) { return window_requests; } +static int vkp_effects_sync(void) { return effects_changes; } +static int vkp_cardboard_pose_changed(void) { return pose_changes; } +static void render_scene(void) { renders++; g_dirty = 0; g_dirty_since_ns = 0; g_rendered_tick_ns = g_tick_vsync_ns; } +static int on_fallback_timer(void *data) { return 0; } +static void on_commit_idle(void *data); +''' + +CHECKS = r''' +static void run_idle(void) { + void (*func)(void *) = idle_func; + idle_func = NULL; + if (func) func(NULL); +} + +static void tick(int64_t t) { clock_ns = t; on_vsync(t); } + +int main(void) { + const int64_t refresh = 6944444; + int64_t t = 1000000000LL; + tick(t); + assert(renders == 0); + + /* a new frame is drawn when it arrives */ + clock_ns += 2000000; + schedule_render(); + assert(idles_added == 1 && renders == 0); + run_idle(); + assert(renders == 1 && g_pace.commit_renders == 1 && g_render_idle == NULL); + + /* a second frame in the same refresh waits for the tick */ + clock_ns += 1000000; + schedule_render(); + assert(idles_added == 1); + tick(t += refresh); + assert(renders == 2 && g_pace.commit_renders == 1); + + /* when the tick comes first, the queued draw does nothing */ + tick(t += refresh); + assert(renders == 2); + clock_ns += 1000000; + schedule_render(); + assert(idles_added == 2); + tick(t += refresh); + assert(renders == 3); + run_idle(); + assert(renders == 3 && g_pace.commit_renders == 1); + + /* paced output, frame generation, the switch off and streaming keep drawing on the tick */ + for (int c = 0; c < 4; c++) { + tick(t += refresh); + if (c == 0) g_release_unpaced = 0; + if (c == 1) framegen = 1; + if (c == 2) g_render_on_commit = 0; + if (c == 3) atomic_store(&g_stream_on, 1); + clock_ns += 1000000; + schedule_render(); + assert(idles_added == 2); + g_release_unpaced = 1; framegen = 0; g_render_on_commit = 1; atomic_store(&g_stream_on, 0); + tick(t += refresh); + assert(renders == 4 + c); + } + + tick(t += refresh); + clock_ns += 1000000; + schedule_render(); + assert(idles_added == 3); + run_idle(); + assert(renders == 8 && g_pace.commit_renders == 2); + + /* without screen ticks the fallback timer still draws */ + clock_ns += 200000000LL; + schedule_render(); + assert(idles_added == 3 && g_fallback_armed == 1 && timers_armed == 1); + puts("PASS"); + return 0; +} +''' + + +@unittest.skipUnless(sys.platform.startswith('linux'), 'needs a Linux host compiler') +class RenderOnCommitTest(unittest.TestCase): + def test_a_new_frame_is_drawn_on_arrival_at_most_once_per_refresh(self): + compiler = shutil.which(os.environ.get('CC', 'cc')) + if compiler is None: + self.skipTest('A host C compiler is required') + source = SOURCE.read_text() + render = extract_function(source, 'render_scene') + self.assertIn('g_rendered_tick_ns = g_tick_vsync_ns;', render) + functions = ('render_on_commit', 'schedule_render', 'scene_waits_for_game', 'on_commit_idle', 'on_vsync') + harness = PREAMBLE + '\n'.join(extract_function(source, name) for name in functions) + CHECKS + with tempfile.TemporaryDirectory(prefix='droiddeck-render-on-commit-') as folder: + path = Path(folder) + (path / 'commit.c').write_text(harness) + binary = path / 'commit-test' + build = subprocess.run([compiler, '-std=c11', '-Wall', '-Wextra', '-Werror', + '-Wno-unused-parameter', '-Wno-unused-function', '-O2', + str(path / 'commit.c'), '-o', str(binary)], capture_output=True, text=True) + self.assertEqual(0, build.returncode, build.stderr) + result = subprocess.run([str(binary)], capture_output=True, text=True, timeout=10) + self.assertEqual(0, result.returncode, result.stderr) + self.assertEqual('PASS', result.stdout.strip()) + + +if __name__ == '__main__': + unittest.main()