mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-11-21 05:46:03 +00:00
feat(display): zero-copy presentation toggle and compositor display buffers (#2905)
* feat(display): zero-copy presentation toggle and compositor display buffers Adds a Zero-copy presentation switch under Steam Settings, Display, Session Display (on by default), and a display-buffer allocator in the compositor: a Vulkan driver that states displayBuffers asks it for the memory of the images it exports, so frames presented through the nested compositor are gralloc buffers that go on the display layer without a copy. Compressed buffers are offered only where the device's allocator matches the layout the drivers render to; everything else stays on the copy path. The private buffer protocol is renamed to droiddeck-ahb-v1. * fix(display): zero-copy frames keep the full refresh rate Two buffers set on the game layer inside one refresh replaced each other, and a frame that slipped into the next refresh made the compositor hold and drop the on-time frame behind it. The layer now queues buffers, and a refresh takes a second frame when the one before it took none. The pacing tool no longer counts its dump time in the frame rate. * Keep cropped scenes on the display layer and pace layer frames evenly Accept any in-bounds source crop for the display layer and map the draw geometry the same way the copy path does. Time layer frames against the display's frame timeline, and when the game's rate is a steady whole fraction of the refresh rate show each frame a fixed number of refreshes after the last so uneven arrivals no longer reach the screen. * List zero-copy in the settings map * Hold display buffers until the display releases them A buffer the game or gamescope rendered straight into went back to its client as soon as the next one was latched, with the display's release fence attached to the dma-buf. The KGSL driver does not wait on that fence, so the client could draw into a buffer the panel was still reading. Display buffers now wait for the release fence before the release event, and gamescope composites only into output images the host has released. * Keep the game picture copy-free when an overlay has no display layer When the display cannot give a second layer of its own to an overlay, the compositor tells gamescope how many planes it can show directly. gamescope then composes its overlays into the game picture, which still reaches the display without a copy. * feat(session): the panel refresh rate follows the session's frame rate The session learns the panel's refresh rates and reports the refresh rate and frame rate it wants. The panel moves to the highest rate the frame rate divides evenly, frame generation counts at its output rate, and a panel whose rate the system holds offers only that rate. * feat(session): the panel follows a frame rate the game holds on its own The compositor reports the game's frame rate once a second. A rate that holds for three seconds and divides a panel rate becomes the content rate when neither the app's limit nor the session's limiter is setting the pace, so a game capped in its own settings gets a panel rate its frames divide into. A rate that was dropped has to hold twice as long before it is used again. * Show generated frames on the game's display layer With frame generation on, the game's own frames stay on their display layer untouched and each generated frame is placed on the same layer between them, timed across the game's frame interval. The compositor pass is kept when effects, HDR routing or a cursor need it, or when the panel cannot show the multiplied rate. * Keep scaling, generated frames and HDR on the display layer A scaler or frame generation with zero-copy on now draws once into the display layer instead of falling back to the copied surface. HDR output goes to the layer when the panel supports it; on a panel without HDR the picture is tone-mapped on the same path, and the toggle is labelled to match what the panel can do. * Spread a frame limit the refresh rate does not divide evenly across refreshes * Cover the spare-tick and panel-rate paths in the compositor source tests * Pin the gamescope build with the display-plane, release, refresh and limiter patches * Give the layer and terminal-caller harnesses the black fill state they compile against * feat(display): switch HDR during a session without restarting the app The compositor now offers HDR whenever the device can present it, and the HDR setting only decides whether the session uses it. Both HDR switches set gamescope's hdr_enabled, the compositor's HDR output and zero-copy for the running session. gamescope patch 0139 lets hdr_enabled change after start. The 'Restart the app to apply.' hint is removed from every locale. * Remake the output images in the new format when HDR is switched during a session * Pin the gamescope build that switches HDR during a session * Apply a saved HDR opt-out at session start and keep HDR retries with their session * Serialise the HDR output switch with the gate opening * feat(display): keep the client's HDR setting and the session's in step The session publishes its HDR state with the other device controls and the client helper applies it to the client's own display setting. A change made in the client is reported back and goes through the same switch the drawer and Session Display use, so all three always show one value. * fix(desktop): keep the display-buffer socket when the runtime directory is cleared The desktop launcher removed everything in the runtime directory except the compositor's Wayland socket, which took the display-buffer socket with it, so no desktop program could ask for display buffers and every frame was copied. * fix(display): the client's HDR setting follows the session in every client mode The bridge only ran when a variable nothing sets was present, so the client's HDR setting and the session's never met. It now runs whenever the session publishes an HDR state, and a client that has no such setting is asked again only every ten seconds. * fix(display): harden display-buffer hand-off, layer fallbacks and HDR sync - Stop closing a buffer handle's descriptor the allocator still owns, and free an allocation whose reply could not be sent. - Rebuild the advertised buffer formats when zero-copy is switched during a session. - Fall back to the copy path when a layer buffer cannot be allocated, and hide the game layer when it is skipped for a frame. - Keep a release fence that has not signalled instead of rendering into a buffer the display still reads. - Ignore a refresh-target reset from a client that does not own the target. - Restart the content-rate measurement after a pause, clear it when the game stops, and lengthen engagement only for a rate that was released before. - Compare colour conversions by their values, and read padded cursor buffers at their row width. - Use the running session's mode for the HDR and zero-copy settings, probe the display before screen effects are pushed, retry a held panel mode, and ignore callbacks after the activity is destroyed. - Write a newer HDR value while an earlier write is settling, and reapply the value after the bridge is reinstalled.
This commit is contained in:
1 parent
f29f72d5d9
commit
4349563fd1
101 files changed
+3927
-624
No files matched your search
+1
-1
@@ -412,10 +412,10 @@ def pacing(adb: str, serial: str, seconds: float) -> dict:
|
||||
try:
|
||||
time.sleep(seconds)
|
||||
dump = run_adb(adb, serial, *timestats, "-dump", timeout=60)
|
||||
elapsed = time.monotonic() - started
|
||||
except ControlError as exc:
|
||||
raise ControlError(str(exc), "PACING_FAILED") from exc
|
||||
finally:
|
||||
elapsed = time.monotonic() - started
|
||||
try:
|
||||
disabled = run_adb(adb, serial, *timestats, "-disable").returncode == 0
|
||||
except ControlError:
|
||||
|
||||
@@ -358,3 +358,51 @@ and clears the held flag. wlroots counts repeated presses of one button and send
|
||||
reaches zero, so a second finger touching before the first lifted left the button pressed in the seat for good: the
|
||||
game saw a held click, and later taps only raised and lowered the count. A finger now presses the button only when no
|
||||
earlier finger holds it. `tools/tests/test_gamescope_touch_click.py` compiles the rule from this patch.
|
||||
|
||||
## 0135 Wayland backend: a limit on the planes handed to the host
|
||||
|
||||
`wayland_overlay_planes` says how many planes above the base one the host compositor shows without composing them
|
||||
itself. With more layers than that, gamescope composites them into one picture, as it already does for a scaler or
|
||||
`composite_force`. -1, the default, keeps every layer on its own plane. The app sets it while a host that shows the
|
||||
game picture directly cannot give an overlay a display layer of its own, so the overlay is drawn into the game
|
||||
picture here and the frame still reaches the display without a copy.
|
||||
|
||||
## 0136 rendervulkan, Wayland backend: composite only into output images the host has released
|
||||
|
||||
The composite output images were used in a fixed rotation of three, with no check that the host compositor had
|
||||
released the one about to be written. A host that puts the buffer on the display itself, without copying it, was
|
||||
still reading that image when the next composite wrote into it. A backend framebuffer now says whether the host
|
||||
holds it, the Wayland backend answers from the buffer's release event, and the composite takes the next image the
|
||||
host does not hold. Backends that are not a session get five images instead of three, so one is free while the
|
||||
host holds two and the last and deferred pictures stay intact. Session backends keep three images and their order.
|
||||
|
||||
## 0137 Wayland backend: the host's refresh rates and the app's target
|
||||
|
||||
A nested session had one refresh rate, the host's, so Steam offered no refresh control and a frame limit never moved
|
||||
the display. The backend binds the host's `droiddeck_refresh_v1`, takes the list of rates the host display can switch
|
||||
between and returns it as the connector's dynamic refresh rates, so the rates reach Steam with the rest of the
|
||||
display state and are sent again when the list changes. On every present it tells the host the refresh rate the
|
||||
frame limit resolves to and the limit itself; the host switches its display and the new rate comes back through
|
||||
`wl_output`, which the nested refresh already follows. A host without the global leaves all of this as it was.
|
||||
|
||||
## 0138 Frame limiter: a limit the refresh rate does not divide is spread evenly
|
||||
|
||||
The limiter held a window for a whole number of refreshes, the refresh rate divided by the limit and rounded down. A
|
||||
limit of 45 or 40 on a 60 Hz display rounded to one refresh per frame, so the limit did nothing, and each frame was
|
||||
timed from the moment the previous one was shown, so a late frame pushed every frame after it. The limited cycle is
|
||||
now the exact time between frames at the limit, and each window keeps the time its next frame is due on that line.
|
||||
A frame is released on the refresh nearest its due time: 45 on 60 Hz shows frames for one, one and two refreshes in
|
||||
turn, 40 for one and two, and a limit that divides the refresh rate is paced as before. A frame that arrives most of a
|
||||
refresh late, or more than a refresh early, starts the line again from that frame, so a stall is not followed by a
|
||||
burst. `tools/tests/test_gamescope_limiter_cadence.py` compiles the two rules from this patch and runs them across
|
||||
refresh rates and limits.
|
||||
|
||||
## 0139 HDR output can be switched while a session runs
|
||||
|
||||
The Wayland backend read `hdr_enabled` once, when the host compositor described its output, and kept the answer: a
|
||||
session started with HDR off told its clients the display had no HDR for as long as it ran, and its environment
|
||||
carried `DXVK_HDR=0`. Whether the display can show HDR now comes from the host's output description alone, and
|
||||
`hdr_enabled` decides only whether HDR is used, so setting it during a session takes effect on the next frame in
|
||||
either direction. The 10-bit output format is chosen only while HDR is enabled, so an SDR session keeps the 8-bit
|
||||
output it had, and the output images are made again in the other format when the setting changes. On a display that can show HDR, a session that starts with HDR off leaves `DXVK_HDR` unset instead of
|
||||
forcing it to 0, so a game started after HDR is switched on finds it.
|
||||
@@ -0,0 +1,20 @@
|
||||
diff --git a/src/Backends/WaylandBackend.cpp b/src/Backends/WaylandBackend.cpp
|
||||
index 372fc08..fe38c7d 100644
|
||||
--- a/src/Backends/WaylandBackend.cpp
|
||||
+++ b/src/Backends/WaylandBackend.cpp
|
||||
@@ -126,6 +126,7 @@ namespace gamescope
|
||||
gamescope::ConVar<bool> cv_wayland_mouse_warp_without_keyboard_focus( "wayland_mouse_warp_without_keyboard_focus", true, "Should we only forward mouse warps to the app when we have keyboard focus?" );
|
||||
gamescope::ConVar<bool> cv_wayland_mouse_relmotion_without_keyboard_focus( "wayland_mouse_relmotion_without_keyboard_focus", false, "Should we only forward mouse relative motion to the app when we have keyboard focus?" );
|
||||
gamescope::ConVar<bool> cv_wayland_use_modifiers( "wayland_use_modifiers", true, "Use DMA-BUF modifiers?" );
|
||||
+ gamescope::ConVar<int> cv_wayland_overlay_planes( "wayland_overlay_planes", -1, "How many planes above the base one the host shows without composing them itself; more are composited here into one. -1 for no limit." );
|
||||
|
||||
gamescope::ConVar<float> cv_wayland_hdr10_saturation_scale( "wayland_hdr10_saturation_scale", 1.0, "Saturation scale for HDR10 content by gamut expansion. 1.0 - 1.2 is a good range to play with." );
|
||||
|
||||
@@ -1102,6 +1103,7 @@ namespace gamescope
|
||||
eLayer0Filter == GamescopeUpscaleFilter::PIXEL ) && !bLayer0ScreenSize;
|
||||
|
||||
bNeedsFullComposite |= cv_composite_force;
|
||||
+ bNeedsFullComposite |= cv_wayland_overlay_planes >= 0 && pFrameInfo->layers.count() > 1 + cv_wayland_overlay_planes;
|
||||
bNeedsFullComposite |= pFrameInfo->useFSRLayer0;
|
||||
bNeedsFullComposite |= pFrameInfo->useNISLayer0;
|
||||
bNeedsFullComposite |= pFrameInfo->useSGSRLayer0;
|
||||
@@ -0,0 +1,218 @@
|
||||
diff --git a/src/Backends/WaylandBackend.cpp b/src/Backends/WaylandBackend.cpp
|
||||
index fe38c7d..be99e6d 100644
|
||||
--- a/src/Backends/WaylandBackend.cpp
|
||||
+++ b/src/Backends/WaylandBackend.cpp
|
||||
@@ -503,6 +503,8 @@ namespace gamescope
|
||||
wl_buffer *GetHostBuffer() const { return m_pHostBuffer; }
|
||||
wlr_buffer *GetClientBuffer() const { return m_pClientBuffer; }
|
||||
|
||||
+ bool HeldByHost() const override { return m_bCompositorAcquired; }
|
||||
+
|
||||
void Wayland_Buffer_Release( wl_buffer *pBuffer );
|
||||
static const wl_buffer_listener s_BufferListener;
|
||||
|
||||
diff --git a/src/backend.h b/src/backend.h
|
||||
index fbfa7c7..30b42ca 100644
|
||||
--- a/src/backend.h
|
||||
+++ b/src/backend.h
|
||||
@@ -288,6 +288,8 @@ namespace gamescope
|
||||
virtual void SetReleasePoint( std::shared_ptr<CReleaseTimelinePoint> pReleasePoint ) = 0;
|
||||
|
||||
virtual IBackendFb *EnsureImported() = 0;
|
||||
+
|
||||
+ virtual bool HeldByHost() const { return false; }
|
||||
};
|
||||
|
||||
class IBackendPlane
|
||||
diff --git a/src/rendervulkan.cpp b/src/rendervulkan.cpp
|
||||
index 0835bfe..42cc9c4 100644
|
||||
--- a/src/rendervulkan.cpp
|
||||
+++ b/src/rendervulkan.cpp
|
||||
@@ -3644,15 +3644,12 @@ static bool vulkan_make_output_images( VulkanOutput_t *pOutput )
|
||||
outputImageflags.bSampled = true; // for pipewire blits
|
||||
outputImageflags.bOutputImage = true;
|
||||
|
||||
- pOutput->outputImages.resize(3); // extra image for partial composition.
|
||||
- pOutput->outputImagesPartialOverlay.resize(3);
|
||||
+ const uint32_t uImageCount = GetBackend()->IsSessionBased() ? 3u : 5u;
|
||||
|
||||
- pOutput->outputImages[0] = nullptr;
|
||||
- pOutput->outputImages[1] = nullptr;
|
||||
- pOutput->outputImages[2] = nullptr;
|
||||
- pOutput->outputImagesPartialOverlay[0] = nullptr;
|
||||
- pOutput->outputImagesPartialOverlay[1] = nullptr;
|
||||
- pOutput->outputImagesPartialOverlay[2] = nullptr;
|
||||
+ pOutput->outputImages.clear();
|
||||
+ pOutput->outputImagesPartialOverlay.clear();
|
||||
+ pOutput->outputImages.resize( uImageCount );
|
||||
+ pOutput->outputImagesPartialOverlay.resize( uImageCount );
|
||||
|
||||
uint32_t uDRMFormat = pOutput->uOutputFormat;
|
||||
|
||||
@@ -3662,28 +3659,14 @@ static bool vulkan_make_output_images( VulkanOutput_t *pOutput )
|
||||
if ( g_uOutputRotation & 1u )
|
||||
std::swap( uOutputWidth, uOutputHeight );
|
||||
|
||||
- pOutput->outputImages[0] = new CVulkanTexture();
|
||||
- bool bSuccess = pOutput->outputImages[0]->BInit( uOutputWidth, uOutputHeight, 1u, uDRMFormat, outputImageflags );
|
||||
- if ( bSuccess != true )
|
||||
- {
|
||||
- vk_log.errorf( "failed to allocate buffer for KMS" );
|
||||
- return false;
|
||||
- }
|
||||
-
|
||||
- pOutput->outputImages[1] = new CVulkanTexture();
|
||||
- bSuccess = pOutput->outputImages[1]->BInit( uOutputWidth, uOutputHeight, 1u, uDRMFormat, outputImageflags );
|
||||
- if ( bSuccess != true )
|
||||
+ for ( uint32_t i = 0; i < uImageCount; i++ )
|
||||
{
|
||||
- vk_log.errorf( "failed to allocate buffer for KMS" );
|
||||
- return false;
|
||||
- }
|
||||
-
|
||||
- pOutput->outputImages[2] = new CVulkanTexture();
|
||||
- bSuccess = pOutput->outputImages[2]->BInit( uOutputWidth, uOutputHeight, 1u, uDRMFormat, outputImageflags );
|
||||
- if ( bSuccess != true )
|
||||
- {
|
||||
- vk_log.errorf( "failed to allocate buffer for KMS" );
|
||||
- return false;
|
||||
+ pOutput->outputImages[i] = new CVulkanTexture();
|
||||
+ if ( !pOutput->outputImages[i]->BInit( uOutputWidth, uOutputHeight, 1u, uDRMFormat, outputImageflags ) )
|
||||
+ {
|
||||
+ vk_log.errorf( "failed to allocate buffer for KMS" );
|
||||
+ return false;
|
||||
+ }
|
||||
}
|
||||
|
||||
// Oh no.
|
||||
@@ -3696,28 +3679,14 @@ static bool vulkan_make_output_images( VulkanOutput_t *pOutput )
|
||||
{
|
||||
uint32_t uPartialDRMFormat = pOutput->uOutputFormatOverlay;
|
||||
|
||||
- pOutput->outputImagesPartialOverlay[0] = new CVulkanTexture();
|
||||
- bool bSuccess = pOutput->outputImagesPartialOverlay[0]->BInit( uOutputWidth, uOutputHeight, 1u, uPartialDRMFormat, outputImageflags, nullptr, 0, 0, pOutput->outputImages[0].get() );
|
||||
- if ( bSuccess != true )
|
||||
- {
|
||||
- vk_log.errorf( "failed to allocate buffer for KMS" );
|
||||
- return false;
|
||||
- }
|
||||
-
|
||||
- pOutput->outputImagesPartialOverlay[1] = new CVulkanTexture();
|
||||
- bSuccess = pOutput->outputImagesPartialOverlay[1]->BInit( uOutputWidth, uOutputHeight, 1u, uPartialDRMFormat, outputImageflags, nullptr, 0, 0, pOutput->outputImages[1].get() );
|
||||
- if ( bSuccess != true )
|
||||
+ for ( uint32_t i = 0; i < uImageCount; i++ )
|
||||
{
|
||||
- vk_log.errorf( "failed to allocate buffer for KMS" );
|
||||
- return false;
|
||||
- }
|
||||
-
|
||||
- pOutput->outputImagesPartialOverlay[2] = new CVulkanTexture();
|
||||
- bSuccess = pOutput->outputImagesPartialOverlay[2]->BInit( uOutputWidth, uOutputHeight, 1u, uPartialDRMFormat, outputImageflags, nullptr, 0, 0, pOutput->outputImages[2].get() );
|
||||
- if ( bSuccess != true )
|
||||
- {
|
||||
- vk_log.errorf( "failed to allocate buffer for KMS" );
|
||||
- return false;
|
||||
+ pOutput->outputImagesPartialOverlay[i] = new CVulkanTexture();
|
||||
+ if ( !pOutput->outputImagesPartialOverlay[i]->BInit( uOutputWidth, uOutputHeight, 1u, uPartialDRMFormat, outputImageflags, nullptr, 0, 0, pOutput->outputImages[i].get() ) )
|
||||
+ {
|
||||
+ vk_log.errorf( "failed to allocate buffer for KMS" );
|
||||
+ return false;
|
||||
+ }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3755,6 +3724,8 @@ bool vulkan_remake_output_images()
|
||||
g_device.waitIdle();
|
||||
|
||||
pOutput->nOutImage = 0;
|
||||
+ pOutput->nLastOutImage = 0;
|
||||
+ pOutput->nDeferredOutImage = 0;
|
||||
|
||||
// Delete screenshot/capture textures to be remade if needed
|
||||
for (auto& pScreenshotTexture : pOutput->pScreenshotTextures)
|
||||
@@ -4604,6 +4575,30 @@ namespace
|
||||
|
||||
ReshadeEffectPipeline *g_pLastReshadeEffect = nullptr;
|
||||
|
||||
+static bool vulkan_output_image_held( uint32_t nImage )
|
||||
+{
|
||||
+ for ( const auto &pImage : { g_output.outputImages[ nImage ], g_output.outputImagesPartialOverlay[ nImage ] } )
|
||||
+ {
|
||||
+ if ( pImage != nullptr && pImage->GetBackendFb() != nullptr && pImage->GetBackendFb()->HeldByHost() )
|
||||
+ return true;
|
||||
+ }
|
||||
+ return false;
|
||||
+}
|
||||
+
|
||||
+static uint32_t vulkan_free_output_image( uint32_t nFirst )
|
||||
+{
|
||||
+ const uint32_t uCount = g_output.outputImages.size();
|
||||
+ for ( uint32_t i = 0; i < uCount; i++ )
|
||||
+ {
|
||||
+ const uint32_t nImage = ( nFirst + i ) % uCount;
|
||||
+ if ( uCount > 3 && ( nImage == g_output.nLastOutImage || nImage == g_output.nDeferredOutImage ) )
|
||||
+ continue;
|
||||
+ if ( !vulkan_output_image_held( nImage ) )
|
||||
+ return nImage;
|
||||
+ }
|
||||
+ return nFirst;
|
||||
+}
|
||||
+
|
||||
std::optional<uint64_t> vulkan_composite( struct FrameInfo_t *frameInfo, gamescope::Rc<CVulkanTexture> pPipewireTexture, bool partial, gamescope::Rc<CVulkanTexture> pOutputOverride, bool increment, std::unique_ptr<CVulkanCmdBuffer> pInCommandBuffer )
|
||||
{
|
||||
EOTF outputTF = frameInfo->outputEncodingEOTF;
|
||||
@@ -4643,6 +4638,9 @@ std::optional<uint64_t> vulkan_composite( struct FrameInfo_t *frameInfo, gamesco
|
||||
if ( !pOutputOverride && !vulkan_ensure_output_images() )
|
||||
return std::nullopt;
|
||||
|
||||
+ if ( !pOutputOverride && !GetBackend()->UsesVulkanSwapchain() )
|
||||
+ g_output.nOutImage = vulkan_free_output_image( g_output.nOutImage );
|
||||
+
|
||||
gamescope::Rc<CVulkanTexture> compositeImage;
|
||||
if ( pOutputOverride )
|
||||
compositeImage = pOutputOverride;
|
||||
@@ -4877,7 +4875,9 @@ std::optional<uint64_t> vulkan_composite( struct FrameInfo_t *frameInfo, gamesco
|
||||
|
||||
if ( !GetBackend()->UsesVulkanSwapchain() && pOutputOverride == nullptr && increment )
|
||||
{
|
||||
- g_output.nOutImage = ( g_output.nOutImage + 1 ) % 3;
|
||||
+ g_output.nDeferredOutImage = g_output.nLastOutImage;
|
||||
+ g_output.nLastOutImage = g_output.nOutImage;
|
||||
+ g_output.nOutImage = ( g_output.nOutImage + 1 ) % g_output.outputImages.size();
|
||||
}
|
||||
|
||||
return sequence;
|
||||
@@ -4931,19 +4931,7 @@ bool vulkan_format_supports_features(VkFormat format, VkFormatFeatureFlags featu
|
||||
|
||||
gamescope::Rc<CVulkanTexture> vulkan_get_last_output_image( bool partial, bool defer )
|
||||
{
|
||||
- // Get previous image ( +2 )
|
||||
- // 1 2 3
|
||||
- // |
|
||||
- // |
|
||||
- uint32_t nRegularImage = ( g_output.nOutImage + 2 ) % 3;
|
||||
-
|
||||
- // Get previous previous image ( +1 )
|
||||
- // 1 2 3
|
||||
- // |
|
||||
- // |
|
||||
- uint32_t nDeferredImage = ( g_output.nOutImage + 1 ) % 3;
|
||||
-
|
||||
- uint32_t nOutImage = defer ? nDeferredImage : nRegularImage;
|
||||
+ uint32_t nOutImage = defer ? g_output.nDeferredOutImage : g_output.nLastOutImage;
|
||||
|
||||
if ( partial )
|
||||
{
|
||||
diff --git a/src/rendervulkan.hpp b/src/rendervulkan.hpp
|
||||
index e0ede11..8ae3b71 100644
|
||||
--- a/src/rendervulkan.hpp
|
||||
+++ b/src/rendervulkan.hpp
|
||||
@@ -591,6 +591,8 @@ struct VulkanOutput_t
|
||||
std::vector<gamescope::OwningRc<CVulkanTexture>> presentationImages;
|
||||
|
||||
uint32_t nOutImage; // swapchain index in nested mode, or ping/pong between two RTs
|
||||
+ uint32_t nLastOutImage = 0;
|
||||
+ uint32_t nDeferredOutImage = 0;
|
||||
std::vector<gamescope::OwningRc<CVulkanTexture>> outputImages;
|
||||
std::vector<gamescope::OwningRc<CVulkanTexture>> outputImagesPartialOverlay;
|
||||
gamescope::OwningRc<CVulkanTexture> temporaryHackyBlankImage;
|
||||
@@ -0,0 +1,293 @@
|
||||
diff --git a/protocol/droiddeck-refresh-v1.xml b/protocol/droiddeck-refresh-v1.xml
|
||||
new file mode 100644
|
||||
index 0000000..c4464a0
|
||||
--- /dev/null
|
||||
+++ b/protocol/droiddeck-refresh-v1.xml
|
||||
@@ -0,0 +1,81 @@
|
||||
+<?xml version="1.0" encoding="UTF-8"?>
|
||||
+<protocol name="droiddeck_refresh_v1">
|
||||
+ <copyright>
|
||||
+ Copyright 2026 DroidDeck contributors
|
||||
+
|
||||
+ Permission is hereby granted, free of charge, to any person obtaining a
|
||||
+ copy of this software and associated documentation files (the "Software"),
|
||||
+ to deal in the Software without restriction, including without limitation
|
||||
+ the rights to use, copy, modify, merge, publish, distribute, sublicense,
|
||||
+ and/or sell copies of the Software, and to permit persons to whom the
|
||||
+ Software is furnished to do so, subject to the following conditions:
|
||||
+
|
||||
+ The above copyright notice and this permission notice (including the next
|
||||
+ paragraph) shall be included in all copies or substantial portions of the
|
||||
+ Software.
|
||||
+
|
||||
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
|
||||
+ THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
+ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
||||
+ DEALINGS IN THE SOFTWARE.
|
||||
+ </copyright>
|
||||
+
|
||||
+ <interface name="droiddeck_refresh_v1" version="1">
|
||||
+ <description summary="panel refresh rates a nested compositor may ask for">
|
||||
+ A nested compositor paces its clients against the refresh rate of the
|
||||
+ panel it is shown on. When its clients are held to a frame rate the
|
||||
+ panel's current rate does not divide evenly, frames are shown for an
|
||||
+ uneven number of refreshes. This interface lets the nested compositor
|
||||
+ see every refresh rate the panel can run at its current size and ask
|
||||
+ for the one that suits the frame rate it is pacing to.
|
||||
+
|
||||
+ On bind the compositor sends one rate event per refresh rate, lowest
|
||||
+ first, followed by done. The list is sent again, in full, whenever it
|
||||
+ changes (a different panel, or a limit the user placed on the panel's
|
||||
+ rate). The rate the panel is running at is still reported the standard
|
||||
+ way, through wl_output.mode.
|
||||
+
|
||||
+ A request is a preference, not a guarantee: the user, the platform or
|
||||
+ another output mirroring the panel may hold the panel at another rate.
|
||||
+ The client reads the result from wl_output.mode.
|
||||
+ </description>
|
||||
+
|
||||
+ <request name="destroy" type="destructor">
|
||||
+ <description summary="destroy the object">
|
||||
+ The preference set through this object is dropped.
|
||||
+ </description>
|
||||
+ </request>
|
||||
+
|
||||
+ <request name="set_target">
|
||||
+ <description summary="ask for a refresh rate">
|
||||
+ refresh is the panel rate the client would like, in Hz, taken from
|
||||
+ the advertised list; 0 withdraws the preference. frame_rate is the
|
||||
+ frame rate the client holds its content to, in frames per second, or
|
||||
+ 0 when the content is not held to a rate. The compositor may multiply
|
||||
+ the content's frame rate itself (generated frames); when it does, it
|
||||
+ picks the advertised rate that the multiplied frame rate divides
|
||||
+ evenly instead of the requested one.
|
||||
+ </description>
|
||||
+ <arg name="refresh" type="uint" summary="wanted panel refresh rate in Hz, 0 for none"/>
|
||||
+ <arg name="frame_rate" type="uint" summary="content frame rate in frames per second, 0 for unpaced"/>
|
||||
+ </request>
|
||||
+
|
||||
+ <event name="rate">
|
||||
+ <description summary="a refresh rate the panel can run">
|
||||
+ Sent once per rate, lowest first, in Hz rounded to the nearest whole
|
||||
+ number.
|
||||
+ </description>
|
||||
+ <arg name="refresh" type="uint" summary="panel refresh rate in Hz"/>
|
||||
+ </event>
|
||||
+
|
||||
+ <event name="done">
|
||||
+ <description summary="the list of rates is complete">
|
||||
+ Ends a list of rate events. The rates received since the previous
|
||||
+ done replace the earlier list.
|
||||
+ </description>
|
||||
+ </event>
|
||||
+ </interface>
|
||||
+</protocol>
|
||||
diff --git a/protocol/meson.build b/protocol/meson.build
|
||||
index cf8fbd1..71fe31b 100644
|
||||
--- a/protocol/meson.build
|
||||
+++ b/protocol/meson.build
|
||||
@@ -43,6 +43,8 @@ protocols = [
|
||||
'gamescope-private.xml',
|
||||
'gamescope-action-binding.xml',
|
||||
|
||||
+ 'droiddeck-refresh-v1.xml',
|
||||
+
|
||||
# wlroots protocols
|
||||
'wlr-layer-shell-unstable-v1.xml',
|
||||
]
|
||||
diff --git a/src/Backends/WaylandBackend.cpp b/src/Backends/WaylandBackend.cpp
|
||||
index be99e6d..9862641 100644
|
||||
--- a/src/Backends/WaylandBackend.cpp
|
||||
+++ b/src/Backends/WaylandBackend.cpp
|
||||
@@ -38,6 +38,7 @@
|
||||
#include <primary-selection-unstable-v1-client-protocol.h>
|
||||
#include <fractional-scale-v1-client-protocol.h>
|
||||
#include <xdg-toplevel-icon-v1-client-protocol.h>
|
||||
+#include <droiddeck-refresh-v1-client-protocol.h>
|
||||
#include "wlr_end.hpp"
|
||||
|
||||
#include "drm_include.h"
|
||||
@@ -705,6 +706,10 @@ namespace gamescope
|
||||
virtual bool UsesVulkanSwapchain() const override;
|
||||
|
||||
virtual bool IsSessionBased() const override;
|
||||
+ virtual bool HackTemporarySetDynamicRefresh( int nRefresh ) override;
|
||||
+
|
||||
+ std::span<const uint32_t> GetHostRefreshRates() const;
|
||||
+ void SyncHostRefreshTarget();
|
||||
virtual bool SupportsExplicitSync() const override;
|
||||
|
||||
virtual bool IsPaused() const override;
|
||||
@@ -778,6 +783,10 @@ namespace gamescope
|
||||
void Wayland_Output_Geometry( wl_output *pOutput, int32_t nX, int32_t nY, int32_t nPhysicalWidth, int32_t nPhysicalHeight, int32_t nSubpixel, const char *pMake, const char *pModel, int32_t nTransform );
|
||||
void Wayland_Output_Mode( wl_output *pOutput, uint32_t uFlags, int32_t nWidth, int32_t nHeight, int32_t nRefresh );
|
||||
void Wayland_Output_Done( wl_output *pOutput );
|
||||
+
|
||||
+ void Wayland_Refresh_Rate( droiddeck_refresh_v1 *pRefresh, uint32_t uRefresh );
|
||||
+ void Wayland_Refresh_Done( droiddeck_refresh_v1 *pRefresh );
|
||||
+ static const droiddeck_refresh_v1_listener s_RefreshListener;
|
||||
void Wayland_Output_Scale( wl_output *pOutput, int32_t nFactor );
|
||||
void Wayland_Output_Name( wl_output *pOutput, const char *pName );
|
||||
void Wayland_Output_Description( wl_output *pOutput, const char *pDescription );
|
||||
@@ -829,6 +838,12 @@ namespace gamescope
|
||||
OwningRc<CWaylandFb> m_pOwnedBlackFb;
|
||||
OwningRc<CVulkanTexture> m_pBlackTexture;
|
||||
wp_presentation *m_pPresentation = nullptr;
|
||||
+ droiddeck_refresh_v1 *m_pHostRefresh = nullptr;
|
||||
+ std::array<uint32_t, 16> m_HostRefreshRates{};
|
||||
+ std::atomic<uint32_t> m_uHostRefreshRateCount = { 0 };
|
||||
+ std::vector<uint32_t> m_PendingHostRefreshRates;
|
||||
+ int m_nSentHostRefresh = 0;
|
||||
+ int m_nSentHostFrameRate = 0;
|
||||
frog_color_management_factory_v1 *m_pFrogColorMgmtFactory = nullptr;
|
||||
wp_color_manager_v1 *m_pWPColorManager = nullptr;
|
||||
wp_image_description_v1 *m_pWPImageDescriptions[ GamescopeAppTextureColorspace_Count ]{};
|
||||
@@ -890,6 +905,11 @@ namespace gamescope
|
||||
.global = WAYLAND_USERDATA_TO_THIS( CWaylandBackend, Wayland_Registry_Global ),
|
||||
.global_remove = WAYLAND_NULL(),
|
||||
};
|
||||
+ const droiddeck_refresh_v1_listener CWaylandBackend::s_RefreshListener =
|
||||
+ {
|
||||
+ .rate = WAYLAND_USERDATA_TO_THIS( CWaylandBackend, Wayland_Refresh_Rate ),
|
||||
+ .done = WAYLAND_USERDATA_TO_THIS( CWaylandBackend, Wayland_Refresh_Done ),
|
||||
+ };
|
||||
const wl_output_listener CWaylandBackend::s_OutputListener =
|
||||
{
|
||||
.geometry = WAYLAND_USERDATA_TO_THIS( CWaylandBackend, Wayland_Output_Geometry ),
|
||||
@@ -1087,6 +1107,7 @@ namespace gamescope
|
||||
{
|
||||
droiddeck::frame_trace::Record( droiddeck::frame_trace::Event::OutputPresent );
|
||||
UpdateFullscreenState();
|
||||
+ m_pBackend->SyncHostRefreshTarget();
|
||||
|
||||
bool bNeedsFullComposite = false;
|
||||
|
||||
@@ -1244,7 +1265,7 @@ namespace gamescope
|
||||
}
|
||||
std::span<const uint32_t> CWaylandConnector::GetValidDynamicRefreshRates() const
|
||||
{
|
||||
- return std::span<const uint32_t>{};
|
||||
+ return m_pBackend->GetHostRefreshRates();
|
||||
}
|
||||
|
||||
void CWaylandConnector::GetNativeColorimetry(
|
||||
@@ -2396,6 +2417,52 @@ namespace gamescope
|
||||
return false;
|
||||
}
|
||||
|
||||
+ std::span<const uint32_t> CWaylandBackend::GetHostRefreshRates() const
|
||||
+ {
|
||||
+ const uint32_t uCount = m_uHostRefreshRateCount;
|
||||
+ if ( uCount < 2 )
|
||||
+ return std::span<const uint32_t>{};
|
||||
+ return std::span<const uint32_t>{ m_HostRefreshRates.data(), uCount };
|
||||
+ }
|
||||
+
|
||||
+ bool CWaylandBackend::HackTemporarySetDynamicRefresh( int nRefresh )
|
||||
+ {
|
||||
+ if ( !m_pHostRefresh )
|
||||
+ return false;
|
||||
+ SyncHostRefreshTarget();
|
||||
+ return true;
|
||||
+ }
|
||||
+
|
||||
+ void CWaylandBackend::SyncHostRefreshTarget()
|
||||
+ {
|
||||
+ if ( !m_pHostRefresh )
|
||||
+ return;
|
||||
+ const int nFrameRate = steamcompmgr_get_app_target_fps();
|
||||
+ const int nRefresh = steamcompmgr_get_app_dynamic_refresh();
|
||||
+ if ( nRefresh == m_nSentHostRefresh && nFrameRate == m_nSentHostFrameRate )
|
||||
+ return;
|
||||
+ xdg_log.infof( "Asking the host for %dhz at %dfps", nRefresh, nFrameRate );
|
||||
+ droiddeck_refresh_v1_set_target( m_pHostRefresh, nRefresh, nFrameRate );
|
||||
+ m_nSentHostRefresh = nRefresh;
|
||||
+ m_nSentHostFrameRate = nFrameRate;
|
||||
+ }
|
||||
+
|
||||
+ void CWaylandBackend::Wayland_Refresh_Rate( droiddeck_refresh_v1 *pRefresh, uint32_t uRefresh )
|
||||
+ {
|
||||
+ m_PendingHostRefreshRates.push_back( uRefresh );
|
||||
+ }
|
||||
+ void CWaylandBackend::Wayland_Refresh_Done( droiddeck_refresh_v1 *pRefresh )
|
||||
+ {
|
||||
+ std::sort( m_PendingHostRefreshRates.begin(), m_PendingHostRefreshRates.end() );
|
||||
+ const uint32_t uCount = std::min<size_t>( m_PendingHostRefreshRates.size(), m_HostRefreshRates.size() );
|
||||
+ m_uHostRefreshRateCount = 0;
|
||||
+ std::copy_n( m_PendingHostRefreshRates.begin(), uCount, m_HostRefreshRates.begin() );
|
||||
+ m_uHostRefreshRateCount = uCount;
|
||||
+ m_PendingHostRefreshRates.clear();
|
||||
+ steamcompmgr_display_rates_changed();
|
||||
+ force_repaint();
|
||||
+ }
|
||||
+
|
||||
bool CWaylandBackend::SupportsExplicitSync() const
|
||||
{
|
||||
// GAMESCOPE_DISABLE_EXPLICIT_SYNC=1: a kernel without DRM_IOCTL_SYNCOBJ_EVENTFD (before
|
||||
@@ -2647,6 +2714,11 @@ namespace gamescope
|
||||
wl_output_add_listener( pOutput , &s_OutputListener, this );
|
||||
m_pOutputs.emplace( std::make_pair<struct wl_output *, WaylandOutputInfo>( std::move( pOutput ), WaylandOutputInfo{} ) );
|
||||
}
|
||||
+ else if ( !strcmp( pInterface, droiddeck_refresh_v1_interface.name ) )
|
||||
+ {
|
||||
+ m_pHostRefresh = (droiddeck_refresh_v1 *)wl_registry_bind( pRegistry, uName, &droiddeck_refresh_v1_interface, 1u );
|
||||
+ droiddeck_refresh_v1_add_listener( m_pHostRefresh, &s_RefreshListener, this );
|
||||
+ }
|
||||
else if ( !strcmp( pInterface, frog_color_management_factory_v1_interface.name ) )
|
||||
{
|
||||
m_pFrogColorMgmtFactory = (frog_color_management_factory_v1 *)wl_registry_bind( pRegistry, uName, &frog_color_management_factory_v1_interface, 1u );
|
||||
diff --git a/src/steamcompmgr.cpp b/src/steamcompmgr.cpp
|
||||
index 38b304b..d7d11b3 100644
|
||||
--- a/src/steamcompmgr.cpp
|
||||
+++ b/src/steamcompmgr.cpp
|
||||
@@ -1229,6 +1229,25 @@ static int g_nCombinedAppRefreshCycleOverride[gamescope::GAMESCOPE_SCREEN_TYPE_C
|
||||
bool g_nCombinedAppRefreshCycleChangeRefresh[gamescope::GAMESCOPE_SCREEN_TYPE_COUNT] = { true, true };
|
||||
bool g_nCombinedAppRefreshCycleChangeFPS[gamescope::GAMESCOPE_SCREEN_TYPE_COUNT] = { true, true };
|
||||
|
||||
+int steamcompmgr_get_app_target_fps()
|
||||
+{
|
||||
+ return g_nSteamCompMgrTargetFPS;
|
||||
+}
|
||||
+
|
||||
+int steamcompmgr_get_app_dynamic_refresh()
|
||||
+{
|
||||
+ if ( !GetBackend()->GetCurrentConnector() )
|
||||
+ return 0;
|
||||
+ return g_nDynamicRefreshRate[ GetBackend()->GetCurrentConnector()->GetScreenType() ];
|
||||
+}
|
||||
+
|
||||
+static std::atomic<bool> g_bDisplayRatesChanged = { false };
|
||||
+
|
||||
+void steamcompmgr_display_rates_changed()
|
||||
+{
|
||||
+ g_bDisplayRatesChanged = true;
|
||||
+}
|
||||
+
|
||||
static void _update_app_target_refresh_cycle()
|
||||
{
|
||||
if ( !GetBackend()->GetCurrentConnector() )
|
||||
@@ -9703,7 +9722,8 @@ void update_vrr_atoms(xwayland_ctx_t *root_ctx, bool force, bool* needs_flush =
|
||||
*needs_flush = true;
|
||||
}
|
||||
|
||||
- if ( g_nOutputRefresh != g_nCurrentRefreshRate_CachedValue || force )
|
||||
+ const bool bDisplayRatesChanged = g_bDisplayRatesChanged.exchange( false );
|
||||
+ if ( g_nOutputRefresh != g_nCurrentRefreshRate_CachedValue || bDisplayRatesChanged || force )
|
||||
{
|
||||
int32_t nRefresh = gamescope::ConvertmHzToHz( g_nOutputRefresh );
|
||||
XChangeProperty(root_ctx->dpy, root_ctx->root, root_ctx->atoms.gamescopeDisplayRefreshRateFeedback, XA_CARDINAL, 32, PropModeReplace,
|
||||
diff --git a/src/steamcompmgr.hpp b/src/steamcompmgr.hpp
|
||||
index ff54d8e..9e0bb79 100644
|
||||
--- a/src/steamcompmgr.hpp
|
||||
+++ b/src/steamcompmgr.hpp
|
||||
@@ -202,4 +202,7 @@ MouseCursor *steamcompmgr_get_server_cursor(uint32_t serverId);
|
||||
|
||||
extern gamescope::ConVar<bool> cv_tearing_enabled;
|
||||
|
||||
+extern int steamcompmgr_get_app_target_fps();
|
||||
+extern int steamcompmgr_get_app_dynamic_refresh();
|
||||
+extern void steamcompmgr_display_rates_changed();
|
||||
extern void steamcompmgr_set_app_refresh_cycle_override( gamescope::GamescopeScreenType type, int override_fps, bool change_refresh, bool change_fps_cap );
|
||||
@@ -0,0 +1,67 @@
|
||||
diff --git a/src/steamcompmgr.cpp b/src/steamcompmgr.cpp
|
||||
index d7d11b3..cfec551 100644
|
||||
--- a/src/steamcompmgr.cpp
|
||||
+++ b/src/steamcompmgr.cpp
|
||||
@@ -7188,6 +7188,19 @@ init_runtime_info()
|
||||
update_runtime_info();
|
||||
}
|
||||
|
||||
+static uint64_t limiter_latch_target( uint64_t ulPreviousTarget, uint64_t ulLatched, uint64_t ulLimitedCycle, uint64_t ulRefreshCycle )
|
||||
+{
|
||||
+ const uint64_t ulTarget = ulPreviousTarget + ulLimitedCycle;
|
||||
+ const bool bLate = ulTarget + ulRefreshCycle * 3 / 4 < ulLatched;
|
||||
+ const bool bEarly = ulTarget > ulLatched + ulRefreshCycle;
|
||||
+ return ( bLate || bEarly ) ? ulLatched : ulTarget;
|
||||
+}
|
||||
+
|
||||
+static bool limiter_holds_vblank( uint64_t ulTarget, uint64_t ulNow, uint64_t ulLimitedCycle, uint64_t ulRefreshCycle )
|
||||
+{
|
||||
+ return ulNow + ulRefreshCycle / 2 < ulTarget + ulLimitedCycle;
|
||||
+}
|
||||
+
|
||||
static void
|
||||
steamcompmgr_flush_frame_done( steamcompmgr_win_t *w )
|
||||
{
|
||||
@@ -7206,6 +7219,9 @@ steamcompmgr_flush_frame_done( steamcompmgr_win_t *w )
|
||||
|
||||
w->last_commit_first_latch_time = timespec_to_nanos(now);
|
||||
|
||||
+ w->limiter_latch_target_time = limiter_latch_target( w->limiter_latch_target_time, w->last_commit_first_latch_time,
|
||||
+ g_SteamCompMgrLimitedAppRefreshCycle, g_SteamCompMgrAppRefreshCycle );
|
||||
+
|
||||
// Acknowledge commit once.
|
||||
wlserver_lock();
|
||||
|
||||
@@ -7258,8 +7274,7 @@ static bool steamcompmgr_should_vblank_window( bool bShouldLimitFPS, uint64_t vb
|
||||
{
|
||||
if ( w && now )
|
||||
{
|
||||
- uint64_t schedule = w->last_commit_first_latch_time + g_SteamCompMgrLimitedAppRefreshCycle;
|
||||
- if ( now + g_SteamCompMgrAppRefreshCycle / 2 < schedule )
|
||||
+ if ( limiter_holds_vblank( w->limiter_latch_target_time, now, g_SteamCompMgrLimitedAppRefreshCycle, g_SteamCompMgrAppRefreshCycle ) )
|
||||
bSendCallback = false;
|
||||
}
|
||||
else
|
||||
@@ -11047,9 +11062,7 @@ steamcompmgr_main(int argc, char **argv)
|
||||
}
|
||||
else
|
||||
{
|
||||
- int nVblankDivisor = nRealRefreshHz / nTargetFPS;
|
||||
-
|
||||
- g_SteamCompMgrLimitedAppRefreshCycle = g_SteamCompMgrAppRefreshCycle * nVblankDivisor;
|
||||
+ g_SteamCompMgrLimitedAppRefreshCycle = g_SteamCompMgrAppRefreshCycle * nRealRefreshHz / nTargetFPS;
|
||||
}
|
||||
}
|
||||
}
|
||||
diff --git a/src/steamcompmgr_shared.hpp b/src/steamcompmgr_shared.hpp
|
||||
index 0fcc80b..3c74d62 100644
|
||||
--- a/src/steamcompmgr_shared.hpp
|
||||
+++ b/src/steamcompmgr_shared.hpp
|
||||
@@ -146,6 +146,7 @@ struct steamcompmgr_win_t {
|
||||
bool outdatedInteractiveFocus = false;
|
||||
|
||||
uint64_t last_commit_first_latch_time = 0;
|
||||
+ uint64_t limiter_latch_target_time = 0;
|
||||
uint64_t last_commit_present_time = 0;
|
||||
|
||||
bool hasHwndStyle = false;
|
||||
@@ -0,0 +1,54 @@
|
||||
diff --git a/src/Backends/WaylandBackend.cpp b/src/Backends/WaylandBackend.cpp
|
||||
index 9862641..e9d2923 100644
|
||||
--- a/src/Backends/WaylandBackend.cpp
|
||||
+++ b/src/Backends/WaylandBackend.cpp
|
||||
@@ -1972,7 +1972,7 @@ namespace gamescope
|
||||
{
|
||||
auto *pHDRInfo = &m_pConnector->m_HDRInfo;
|
||||
if (m_pBackend->SupportsColorManagement()) {
|
||||
- pHDRInfo->bExposeHDRSupport = ( cv_hdr_enabled && m_pConnector->m_uMaxTargetLuminance > m_pConnector->m_uReferenceLuminance );
|
||||
+ pHDRInfo->bExposeHDRSupport = ( m_pConnector->m_uMaxTargetLuminance > m_pConnector->m_uReferenceLuminance );
|
||||
pHDRInfo->eOutputEncodingEOTF = pHDRInfo->bExposeHDRSupport ? EOTF_PQ : EOTF_Gamma22;
|
||||
}
|
||||
|
||||
@@ -2282,7 +2282,7 @@ namespace gamescope
|
||||
|
||||
assert( u8BitFormat != DRM_FORMAT_INVALID );
|
||||
|
||||
- *pPrimaryPlaneFormat = u10BitFormat != DRM_FORMAT_INVALID ? u10BitFormat : u8BitFormat;
|
||||
+ *pPrimaryPlaneFormat = ( cv_hdr_enabled && u10BitFormat != DRM_FORMAT_INVALID ) ? u10BitFormat : u8BitFormat;
|
||||
*pOverlayPlaneFormat = u8BitFormat;
|
||||
}
|
||||
|
||||
@@ -2493,13 +2493,17 @@ namespace gamescope
|
||||
|
||||
// XXX: We should do this a better way that handles per-window and appid stuff
|
||||
// down the line
|
||||
- if ( cv_hdr_enabled && GetCurrentConnector()->GetHDRInfo().bExposeHDRSupport )
|
||||
+ if ( !GetCurrentConnector()->GetHDRInfo().bExposeHDRSupport )
|
||||
+ {
|
||||
+ setenv( "DXVK_HDR", "0", true );
|
||||
+ }
|
||||
+ else if ( cv_hdr_enabled )
|
||||
{
|
||||
setenv( "DXVK_HDR", "1", true );
|
||||
}
|
||||
else
|
||||
{
|
||||
- setenv( "DXVK_HDR", "0", true );
|
||||
+ unsetenv( "DXVK_HDR" );
|
||||
}
|
||||
|
||||
WritePatchedEdid( GetCurrentConnector()->GetRawEDID(), GetCurrentConnector()->GetHDRInfo(), false );
|
||||
diff --git a/src/rendervulkan.cpp b/src/rendervulkan.cpp
|
||||
index 42cc9c4..d0d21f0 100644
|
||||
--- a/src/rendervulkan.cpp
|
||||
+++ b/src/rendervulkan.cpp
|
||||
@@ -3735,6 +3735,7 @@ bool vulkan_remake_output_images()
|
||||
|
||||
if ( vulkan_defer_output_images() )
|
||||
{
|
||||
+ GetBackend()->GetPreferredOutputFormat( &pOutput->uOutputFormat, &pOutput->uOutputFormatOverlay );
|
||||
pOutput->outputImages.clear();
|
||||
pOutput->outputImagesPartialOverlay.clear();
|
||||
pOutput->temporaryHackyBlankImage = vulkan_create_debug_blank_texture();
|
||||
@@ -1,3 +1,3 @@
|
||||
GAMESCOPE_REPO=Droid-Deck/DroidDeck-Components
|
||||
GAMESCOPE_TAG=gamescope-3.16.29-p23
|
||||
GAMESCOPE_SHA256=f5f2b8f658234ad2910a1be53c238188db7e7b2a9079f8cc5fa9ea006bebbe7e
|
||||
GAMESCOPE_TAG=gamescope-3.16.29-zerocopy-8df683f1-qa
|
||||
GAMESCOPE_SHA256=609198c39b125094a65e1703ffcfd6538e88c9784a1a6596bf673f2e5dc7af80
|
||||
@@ -24,7 +24,7 @@ if [ -n "${DD_DEBUG_DIR:-}" ]; then
|
||||
exec >>"$DD_DEBUG_DIR/desktop.log" 2>&1
|
||||
echo "== droiddeck-desktop $(date -u '+%Y-%m-%d %H:%M:%S UTC') ${DD_WIDTH:-1280}x${DD_HEIGHT:-720}"
|
||||
fi
|
||||
find "$XDG_RUNTIME_DIR" -mindepth 1 -maxdepth 1 ! -name 'wayland-0*' ! -name 'keymap.xkb' -exec rm -rf {} + 2>/dev/null
|
||||
find "$XDG_RUNTIME_DIR" -mindepth 1 -maxdepth 1 ! -name 'wayland-0*' ! -name 'keymap.xkb' ! -name 'droiddeck-display-buffers' -exec rm -rf {} + 2>/dev/null
|
||||
chmod 700 "$XDG_RUNTIME_DIR" 2>/dev/null
|
||||
mkdir -p /tmp/.X11-unix /tmp/.ICE-unix && chmod 1777 /tmp/.X11-unix /tmp/.ICE-unix 2>/dev/null
|
||||
export DD_DESKTOP=1
|
||||
|
||||
@@ -66,19 +66,32 @@ BRIGHTNESS_JS = r"""
|
||||
""".replace("__BINDING__", BRIGHTNESS_BINDING)
|
||||
|
||||
|
||||
def control_request(name, text, directory):
|
||||
path = os.path.join(directory, name)
|
||||
with open(path + ".tmp", "w") as target:
|
||||
target.write(text + "\n")
|
||||
os.replace(path + ".tmp", path)
|
||||
|
||||
|
||||
def brightness_request(payload, directory=CONTROLS_DIR):
|
||||
try:
|
||||
value = float(payload)
|
||||
if not math.isfinite(value) or not 0 <= value <= 1:
|
||||
return
|
||||
path = os.path.join(directory, "brightness.request")
|
||||
with open(path + ".tmp", "w") as target:
|
||||
target.write(str(value) + "\n")
|
||||
os.replace(path + ".tmp", path)
|
||||
control_request("brightness.request", str(value), directory)
|
||||
except (ValueError, TypeError, OSError):
|
||||
return
|
||||
|
||||
|
||||
def hdr_request(payload, directory=CONTROLS_DIR):
|
||||
if payload not in ("0", "1"):
|
||||
return
|
||||
try:
|
||||
control_request("hdr.request", payload, directory)
|
||||
except OSError:
|
||||
return
|
||||
|
||||
|
||||
INSTALL_JS = r"""
|
||||
(() => {
|
||||
if (window.__droiddeckCompat) return "present";
|
||||
@@ -256,6 +269,49 @@ TOUR_JS = r"""
|
||||
return "off";
|
||||
})()
|
||||
"""
|
||||
SET_SETTING_JS = r"""(field, value) => {
|
||||
const bytes = [];
|
||||
for (let n of [field * 8, value]) {
|
||||
while (n > 127) { bytes.push((n & 127) | 128); n = Math.floor(n / 128); }
|
||||
bytes.push(n);
|
||||
}
|
||||
return SteamClient.Settings.SetSetting(btoa(String.fromCharCode(...bytes)));
|
||||
}"""
|
||||
HDR_BINDING = "droiddeckHdrChanged"
|
||||
HDR_JS = r"""
|
||||
(() => {
|
||||
if (window.__droiddeckHdr) return "present";
|
||||
const settings = window.settingsStore;
|
||||
if (typeof settings?.clientSettings?.gamescope_hdr_enabled !== "boolean" ||
|
||||
typeof SteamClient.Settings?.SetSetting !== "function") return "unavailable";
|
||||
const write = __SET_SETTING__;
|
||||
const HOLD_MS = 3000;
|
||||
const self = { known: settings.clientSettings.gamescope_hdr_enabled, pending: null, until: 0 };
|
||||
self.set = value => {
|
||||
if (typeof value !== "boolean") return true;
|
||||
self.known = value;
|
||||
if (settings.clientSettings.gamescope_hdr_enabled === value && self.pending === null) return true;
|
||||
self.pending = value;
|
||||
self.until = performance.now() + HOLD_MS;
|
||||
write(21015, value ? 1 : 0);
|
||||
return true;
|
||||
};
|
||||
self.check = () => {
|
||||
const value = settings.clientSettings.gamescope_hdr_enabled;
|
||||
if (typeof value !== "boolean") return;
|
||||
if (self.pending !== null) {
|
||||
if (value !== self.pending && performance.now() < self.until) return;
|
||||
self.pending = null;
|
||||
}
|
||||
if (value === self.known) return;
|
||||
self.known = value;
|
||||
if (typeof window.__BINDING__ === "function") window.__BINDING__(value ? "1" : "0");
|
||||
};
|
||||
self.interval = setInterval(self.check, 500);
|
||||
window.__droiddeckHdr = self;
|
||||
return "installed";
|
||||
})()
|
||||
""".replace("__BINDING__", HDR_BINDING).replace("__SET_SETTING__", SET_SETTING_JS)
|
||||
FRAME_LIMIT_JS = r"""
|
||||
(() => {
|
||||
if (window.__droiddeckFrameLimit) return "present";
|
||||
@@ -281,14 +337,7 @@ FRAME_LIMIT_JS = r"""
|
||||
}
|
||||
if (!service || !settings?.clientSettings || typeof SteamClient.Settings?.SetSetting !== "function") return "unavailable";
|
||||
const self = { timer: null };
|
||||
const write = value => {
|
||||
const bytes = [];
|
||||
for (let n of [21002 * 8, value]) {
|
||||
while (n > 127) { bytes.push((n & 127) | 128); n = Math.floor(n / 128); }
|
||||
bytes.push(n);
|
||||
}
|
||||
return SteamClient.Settings.SetSetting(btoa(String.fromCharCode(...bytes)));
|
||||
};
|
||||
const write = value => (__SET_SETTING__)(21002, value);
|
||||
self.check = async () => {
|
||||
let rates;
|
||||
try {
|
||||
@@ -316,7 +365,7 @@ FRAME_LIMIT_JS = r"""
|
||||
window.__droiddeckFrameLimit = self;
|
||||
return "installed";
|
||||
})()
|
||||
"""
|
||||
""".replace("__SET_SETTING__", SET_SETTING_JS)
|
||||
WINDOW_BINDING = "droiddeckWindowAction"
|
||||
WINDOW_TARGET = "createflags=18"
|
||||
WINDOW_MOVES = {"nw": 0, "n": 1, "ne": 2, "e": 3, "se": 4, "s": 5, "sw": 6, "w": 7, "move": 8}
|
||||
@@ -923,6 +972,9 @@ class Helper:
|
||||
self.controls_installed = False
|
||||
self.frame_limit_state = None
|
||||
self.frame_limit_retry = 0
|
||||
self.hdr_state = None
|
||||
self.hdr_installed = False
|
||||
self.hdr_retry = 0
|
||||
self.windows = {}
|
||||
self.windows_retry = 0
|
||||
|
||||
@@ -983,6 +1035,29 @@ class Helper:
|
||||
except (Closed, OSError, ValueError):
|
||||
del self.windows[ident]
|
||||
|
||||
def sync_hdr(self):
|
||||
try:
|
||||
with open(os.path.join(CONTROLS_DIR, "state.json")) as source:
|
||||
value = json.load(source).get("hdr")
|
||||
if not isinstance(value, bool):
|
||||
return
|
||||
if not self.hdr_installed:
|
||||
if time.monotonic() < self.hdr_retry:
|
||||
return
|
||||
self.page.call("Runtime.addBinding", {"name": HDR_BINDING})
|
||||
self.hdr_installed = self.page.evaluate(HDR_JS) in ("installed", "present")
|
||||
if not self.hdr_installed:
|
||||
self.hdr_retry = time.monotonic() + 10
|
||||
return
|
||||
if value != self.hdr_state:
|
||||
if self.page.evaluate("window.__droiddeckHdr ? window.__droiddeckHdr.set(%s) : false" % json.dumps(value)) is True:
|
||||
self.hdr_state = value
|
||||
else:
|
||||
self.hdr_state = None
|
||||
self.hdr_installed = False
|
||||
except (OSError, ValueError, TypeError, AttributeError):
|
||||
pass
|
||||
|
||||
def sync_frame_limit(self):
|
||||
if self.frame_limit_state in ("installed", "present") or time.monotonic() < self.frame_limit_retry:
|
||||
return
|
||||
@@ -1095,6 +1170,9 @@ class Helper:
|
||||
self.controls_installed = False
|
||||
self.frame_limit_state = None
|
||||
self.frame_limit_retry = 0
|
||||
self.hdr_state = None
|
||||
self.hdr_installed = False
|
||||
self.hdr_retry = 0
|
||||
self.sync_controls()
|
||||
return True
|
||||
|
||||
@@ -1231,6 +1309,8 @@ class Helper:
|
||||
for e in events:
|
||||
if called(e, BRIGHTNESS_BINDING):
|
||||
brightness_request(e.get("params", {}).get("payload"))
|
||||
if called(e, HDR_BINDING):
|
||||
hdr_request(e.get("params", {}).get("payload"))
|
||||
if called(e, FILE_BINDING) and isinstance(e.get("params", {}).get("payload"), str):
|
||||
self.open_chooser(e["params"]["payload"])
|
||||
return events
|
||||
@@ -1260,6 +1340,7 @@ class Helper:
|
||||
while True:
|
||||
self.sync_controls()
|
||||
self.sync_frame_limit()
|
||||
self.sync_hdr()
|
||||
self.sync_windows()
|
||||
sources = [self.page.ws] + ([watcher] if watcher.fileno() >= 0 else [])
|
||||
sources += [page.ws for page in self.windows.values()]
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
from pathlib import Path
|
||||
import re
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
DESKTOP = ROOT / "tools/linuxfs/desktop/droiddeck-desktop"
|
||||
SOURCE = ROOT / "app/src/main/cpp/waylandcomp/src/display_buffers.c"
|
||||
|
||||
|
||||
class DesktopDisplayBuffersTest(unittest.TestCase):
|
||||
def test_clearing_the_runtime_directory_keeps_what_the_compositor_serves(self):
|
||||
socket = re.search(r'#define DISPLAY_BUFFERS_SOCKET "([^"]+)"', SOURCE.read_text()).group(1)
|
||||
lines = [line for line in DESKTOP.read_text().splitlines() if line.startswith('find "$XDG_RUNTIME_DIR"')]
|
||||
self.assertEqual(len(lines), 1)
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
runtime = Path(directory) / "runtime"
|
||||
(runtime / "dbus-1").mkdir(parents=True)
|
||||
kept = ["wayland-0", "wayland-0.lock", "keymap.xkb", socket]
|
||||
for name in kept + ["wayland-1", "pipewire-0", "dbus-1/session"]:
|
||||
(runtime / name).write_text("")
|
||||
subprocess.run(["bash", "-c", lines[0]], env={"XDG_RUNTIME_DIR": str(runtime), "PATH": "/usr/bin:/bin"},
|
||||
check=True, timeout=20)
|
||||
self.assertEqual(sorted(path.name for path in runtime.iterdir()), sorted(kept))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -203,7 +203,7 @@ static struct { float kx, ky, off_x, off_y; int rx, ry, rw, rh; } g_map;
|
||||
static struct { VkImage img; int w, h; } g_scene;
|
||||
struct vkp_img_slot { VkImage img; int w, h; };
|
||||
static struct vkp_img_slot g_hdrscene, g_fgscene;
|
||||
static struct { int active, rw, rh; VkImage result; } g_pass;
|
||||
static struct { int active, rw, rh, ngen; VkImage result; VkImage gens[VKP_FG_MAX_GENERATIONS]; } g_pass;
|
||||
static struct { int64_t present_ns, present_max_ns; unsigned presents; } g_perf;
|
||||
static int effects_active = 1, framegen, cardboard;
|
||||
struct fx_settings { int scaling, cas_on, cas_pct; };
|
||||
@@ -368,7 +368,7 @@ static void run_path(int offscreen, const struct vkp_draw *draw, int n, const st
|
||||
assert(n > 0 && n <= 4);
|
||||
memcpy(before, draw, n * sizeof(*draw));
|
||||
int rw = 0, rh = 0;
|
||||
assert((offscreen ? pass_begin_impl(1920, 1080, draw, n, hdr, &rw, &rh)
|
||||
assert((offscreen ? pass_begin_impl(1920, 1080, draw, n, hdr, 0, &rw, &rh)
|
||||
: render_impl(1920, 1080, draw, n, hdr, NULL)) == 0);
|
||||
assert(memcmp(draw, before, n * sizeof(*draw)) == 0);
|
||||
if (offscreen) assert(rw == (fail_effects ? effects_w : (int)g_extent.width) &&
|
||||
@@ -393,7 +393,7 @@ static void check_path(int offscreen) {
|
||||
run_path(offscreen, &draw, 1, NULL); check_input(1280, 720);
|
||||
reset(); draw = fullscreen(); draw.dw = 1280; draw.dh = 720;
|
||||
int rw, rh;
|
||||
assert((offscreen ? pass_begin_impl(1280, 720, &draw, 1, NULL, &rw, &rh)
|
||||
assert((offscreen ? pass_begin_impl(1280, 720, &draw, 1, NULL, 0, &rw, &rh)
|
||||
: render_impl(1280, 720, &draw, 1, NULL, NULL)) == 0);
|
||||
check_input(1280, 720);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,118 @@
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
PATCH = ROOT / "tools/gamescope/patches/0138-limiter-even-cadence.patch"
|
||||
|
||||
|
||||
def added_source():
|
||||
return "\n".join(line[1:] for line in PATCH.read_text().splitlines() if line.startswith("+") and not line.startswith("+++"))
|
||||
|
||||
|
||||
def block(text, start):
|
||||
begin = text.index(start)
|
||||
return text[begin:text.index("\n}", begin) + 3]
|
||||
|
||||
|
||||
PREAMBLE = r'''
|
||||
#include <cassert>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <vector>
|
||||
'''
|
||||
|
||||
MAIN = r'''
|
||||
struct Run {
|
||||
std::vector<int> gaps;
|
||||
int frames = 0;
|
||||
};
|
||||
|
||||
static Run run(int hz, int fps, int vblanks, uint64_t latency) {
|
||||
const uint64_t cycle = 1000000000ull / hz;
|
||||
const uint64_t limited = cycle * hz / fps;
|
||||
uint64_t target = 0;
|
||||
int last = -1;
|
||||
Run r;
|
||||
for (int i = 0; i < vblanks; i++) {
|
||||
const uint64_t now = (1000ull + i) * cycle;
|
||||
if (limiter_holds_vblank(target, now, limited, cycle)) continue;
|
||||
target = limiter_latch_target(target, now + latency, limited, cycle);
|
||||
if (last >= 0) r.gaps.push_back(i - last);
|
||||
last = i;
|
||||
r.frames++;
|
||||
}
|
||||
return r;
|
||||
}
|
||||
|
||||
static void check(int hz, int fps, uint64_t latency) {
|
||||
const int vblanks = hz * 20;
|
||||
const Run r = run(hz, fps, vblanks, latency);
|
||||
const int low = hz / fps;
|
||||
const int high = (hz + fps - 1) / fps;
|
||||
for (int gap : r.gaps) {
|
||||
if (gap != low && gap != high) {
|
||||
std::printf("%d Hz at %d fps: a frame was held for %d refreshes\n", hz, fps, gap);
|
||||
assert(false);
|
||||
}
|
||||
}
|
||||
const int expected = fps * 20;
|
||||
if (r.frames < expected - 1 || r.frames > expected + 1) {
|
||||
std::printf("%d Hz at %d fps: %d frames, expected %d\n", hz, fps, r.frames, expected);
|
||||
assert(false);
|
||||
}
|
||||
}
|
||||
|
||||
int main() {
|
||||
const int rates[] = {60, 90, 120, 144, 165};
|
||||
const int limits[] = {24, 30, 36, 40, 45, 48, 50, 60, 72, 80, 90, 100, 120, 144};
|
||||
for (int hz : rates) {
|
||||
for (int fps : limits) {
|
||||
if (fps > hz) continue;
|
||||
check(hz, fps, 0);
|
||||
check(hz, fps, 1000000000ull / hz / 4);
|
||||
}
|
||||
}
|
||||
|
||||
const Run even = run(60, 30, 600, 0);
|
||||
for (int gap : even.gaps) assert(gap == 2);
|
||||
const Run full = run(120, 120, 600, 0);
|
||||
for (int gap : full.gaps) assert(gap == 1);
|
||||
const Run two_of_three = run(60, 40, 600, 0);
|
||||
for (size_t i = 1; i < two_of_three.gaps.size(); i++) assert(two_of_three.gaps[i] != two_of_three.gaps[i - 1]);
|
||||
|
||||
const uint64_t cycle = 16666666, limited = cycle * 60 / 45;
|
||||
assert(limiter_latch_target(1000 * cycle, 1500 * cycle, limited, cycle) == 1500 * cycle);
|
||||
assert(limiter_latch_target(1500 * cycle, 1000 * cycle, limited, cycle) == 1000 * cycle);
|
||||
assert(limiter_latch_target(1000 * cycle, 1001 * cycle, limited, cycle) == 1000 * cycle + limited);
|
||||
return 0;
|
||||
}
|
||||
'''
|
||||
|
||||
|
||||
class GamescopeLimiterCadenceTest(unittest.TestCase):
|
||||
def test_a_limit_the_refresh_rate_does_not_divide_is_spread_evenly(self):
|
||||
compiler = shutil.which("c++") or shutil.which("g++") or shutil.which("clang++")
|
||||
if not compiler:
|
||||
self.skipTest("no C++ compiler")
|
||||
added = added_source()
|
||||
source = PREAMBLE + block(added, "static uint64_t limiter_latch_target") + block(added, "static bool limiter_holds_vblank") + MAIN
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
src = Path(tmp) / "limiter_cadence.cpp"
|
||||
exe = Path(tmp) / "limiter_cadence"
|
||||
src.write_text(source)
|
||||
subprocess.run([compiler, "-std=c++17", "-Wall", "-Werror", "-UNDEBUG", str(src), "-o", str(exe)], check=True)
|
||||
subprocess.run([str(exe)], check=True)
|
||||
|
||||
def test_the_limited_cycle_is_no_longer_a_whole_number_of_refreshes(self):
|
||||
added = added_source()
|
||||
self.assertIn("g_SteamCompMgrAppRefreshCycle * nRealRefreshHz / nTargetFPS", added)
|
||||
removed = "\n".join(line[1:] for line in PATCH.read_text().splitlines() if line.startswith("-") and not line.startswith("---"))
|
||||
self.assertIn("nVblankDivisor", removed)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,87 @@
|
||||
from pathlib import Path
|
||||
import re
|
||||
import unittest
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
PATCH = ROOT / "tools/gamescope/patches/0139-hdr-switch-live.patch"
|
||||
APP = ROOT / "app/src/main/java/com/droiddeck/launcher"
|
||||
RES = ROOT / "app/src/main/res"
|
||||
|
||||
|
||||
def lines(prefix):
|
||||
return [line[1:] for line in PATCH.read_text().splitlines()
|
||||
if line.startswith(prefix) and not line.startswith(prefix * 3)]
|
||||
|
||||
|
||||
class HdrLiveSwitchTest(unittest.TestCase):
|
||||
def test_display_capability_does_not_depend_on_the_setting(self):
|
||||
added = [line for line in lines("+") if "bExposeHDRSupport =" in line]
|
||||
self.assertEqual(len(added), 1)
|
||||
self.assertNotIn("cv_hdr_enabled", added[0])
|
||||
self.assertIn("m_uMaxTargetLuminance > m_pConnector->m_uReferenceLuminance", added[0])
|
||||
|
||||
def test_sdr_keeps_the_8_bit_output(self):
|
||||
added = [line for line in lines("+") if "*pPrimaryPlaneFormat" in line]
|
||||
self.assertEqual(len(added), 1)
|
||||
self.assertRegex(added[0], r"cv_hdr_enabled && u10BitFormat != DRM_FORMAT_INVALID \) \? u10BitFormat : u8BitFormat")
|
||||
|
||||
def test_remade_output_images_pick_the_format_again(self):
|
||||
text = PATCH.read_text()
|
||||
hunk = text[text.index("src/rendervulkan.cpp"):]
|
||||
added = [line[1:] for line in hunk.splitlines() if line.startswith("+") and not line.startswith("+++")]
|
||||
self.assertEqual([line.strip() for line in added],
|
||||
["GetBackend()->GetPreferredOutputFormat( &pOutput->uOutputFormat, &pOutput->uOutputFormatOverlay );"])
|
||||
self.assertIn("if ( vulkan_defer_output_images() )", hunk[:hunk.index(added[0])])
|
||||
|
||||
def test_capable_display_does_not_force_dxvk_hdr_off(self):
|
||||
added = "\n".join(lines("+"))
|
||||
self.assertIn('unsetenv( "DXVK_HDR" )', added)
|
||||
off = added.index('setenv( "DXVK_HDR", "0", true )')
|
||||
self.assertIn("!GetCurrentConnector()->GetHDRInfo().bExposeHDRSupport", added[:off])
|
||||
|
||||
def test_the_gate_follows_the_display_not_the_setting(self):
|
||||
text = (APP / "SessionActivity.kt").read_text()
|
||||
start = text.index("val attached = CompositorHost.isStarted")
|
||||
block = text[start:text.index("DriverSetupLog.write", start)]
|
||||
request = block[block.index("nativeSetHdrRequest("):block.index("Log.i", block.index("nativeSetHdrRequest("))]
|
||||
self.assertNotIn("SessionPrefs.hdr", block[:block.index("if (!SessionState.running)")])
|
||||
self.assertIn("capable, false", request)
|
||||
self.assertIn("SessionState.hdrCapable && SessionPrefs.hdr(this, mode)", block)
|
||||
|
||||
def test_both_switches_apply_to_the_running_session(self):
|
||||
helper = (APP / "session/SessionHdr.kt").read_text()
|
||||
self.assertIn('setGamescopeConvar(app, "hdr_enabled", if (on) 1 else 0)', helper)
|
||||
self.assertIn("nativeSetHdrOutput(on)", helper)
|
||||
self.assertIn("nativeSetZeroCopy(on || SessionPrefs.zeroCopy(context, mode))", helper)
|
||||
self.assertIn("SessionPrefs.prefMode(SessionState.mode) != mode", helper)
|
||||
for name in ("SessionActivity.kt", "FrontEndActivity.kt"):
|
||||
text = (APP / name).read_text()
|
||||
self.assertEqual(len(re.findall(r"onHdr = \{ on -> com\.droiddeck\.launcher\.session\.SessionHdr\.set\(", text)), 1, name)
|
||||
self.assertNotIn("SessionPrefs.setHdr(", text, name)
|
||||
|
||||
def test_a_saved_opt_out_applies_before_the_gate_opens(self):
|
||||
native = (ROOT / "app/src/main/cpp/waylandcomp/src/wl_color_mgmt.c").read_text()
|
||||
switch = native[native.index("void droiddeck_color_set_output(int on)"):]
|
||||
switch = switch[:switch.index("if (gate != 1)")]
|
||||
self.assertLess(switch.index("pthread_mutex_lock(&g_output_mu)"), switch.index("atomic_store(&g_output_wanted, on)"))
|
||||
self.assertLess(switch.index("atomic_exchange(&g_output_on, on)"), switch.index("pthread_mutex_unlock(&g_output_mu)"))
|
||||
opened = native[native.index("atomic_store(&g_gate, 1);") - 40:]
|
||||
opened = opened[:opened.index("pthread_mutex_unlock(&g_output_mu)")]
|
||||
self.assertIn("pthread_mutex_lock(&g_output_mu)", opened)
|
||||
self.assertIn("if (mode == 3 || !atomic_load(&g_output_wanted)) atomic_store(&g_output_on, 0);", opened)
|
||||
text = (APP / "SessionActivity.kt").read_text()
|
||||
self.assertNotIn("if (attached) WaylandCompositor.nativeSetHdrOutput", text)
|
||||
|
||||
def test_retries_stay_with_the_session_that_asked(self):
|
||||
helper = (APP / "session/SessionHdr.kt").read_text()
|
||||
self.assertIn("val session = SessionState.sessionId", helper)
|
||||
self.assertIn("SessionState.sessionId == session", helper)
|
||||
|
||||
def test_no_restart_hint_is_left(self):
|
||||
for path in list(RES.glob("values*/strings.xml")) + list(APP.rglob("*.kt")):
|
||||
self.assertNotIn("mode_hdr_restart", path.read_text(), str(path))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,185 @@
|
||||
import json
|
||||
from pathlib import Path
|
||||
import runpy
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
BIN = ROOT / "tools/linuxfs/overlay/usr/local/bin"
|
||||
APP = ROOT / "app/src/main/java/com/droiddeck/launcher"
|
||||
LIVE = runpy.run_path(str(BIN / "droiddeck-steam-compat"))
|
||||
|
||||
HARNESS = r"""
|
||||
const assert = require('assert');
|
||||
globalThis.window = globalThis;
|
||||
globalThis.btoa = text => Buffer.from(text, 'binary').toString('base64');
|
||||
let now = 0, tick = null;
|
||||
Object.defineProperty(globalThis, 'performance', { value: { now: () => now }, configurable: true });
|
||||
globalThis.setInterval = callback => { tick = callback; return 1; };
|
||||
const varints = bytes => { const out = []; let value = 0, shift = 0;
|
||||
for (const b of bytes) { value += (b & 127) * 2 ** shift; shift += 7; if (b < 128) { out.push(value); value = 0; shift = 0; } }
|
||||
return out; };
|
||||
const writes = [], told = [];
|
||||
let apply = true;
|
||||
globalThis.settingsStore = { clientSettings: { gamescope_hdr_enabled: false } };
|
||||
globalThis.SteamClient = { Settings: { SetSetting(encoded) {
|
||||
const [key, value] = varints([...Buffer.from(encoded, 'base64')]);
|
||||
assert.strictEqual(key, 21015 * 8);
|
||||
writes.push(value);
|
||||
if (apply) settingsStore.clientSettings.gamescope_hdr_enabled = value === 1;
|
||||
} } };
|
||||
window.droiddeckHdrChanged = value => told.push(value);
|
||||
const script = require('fs').readFileSync(process.argv[2], 'utf8');
|
||||
assert.strictEqual(eval(script), 'installed');
|
||||
assert.strictEqual(eval(script), 'present');
|
||||
const bridge = window.__droiddeckHdr;
|
||||
tick();
|
||||
assert.deepStrictEqual(told, [], 'an unchanged client setting is not reported');
|
||||
assert.strictEqual(bridge.set(true), true);
|
||||
assert.deepStrictEqual(writes, [1]);
|
||||
tick();
|
||||
assert.deepStrictEqual(told, [], 'a value the app set is not reported back to it');
|
||||
assert.strictEqual(bridge.set(true), true);
|
||||
assert.deepStrictEqual(writes, [1], 'an equal value is not written again');
|
||||
settingsStore.clientSettings.gamescope_hdr_enabled = false;
|
||||
tick();
|
||||
assert.deepStrictEqual(told, ['0'], 'a change made in the client reaches the app');
|
||||
tick();
|
||||
assert.deepStrictEqual(told, ['0']);
|
||||
settingsStore.clientSettings.gamescope_hdr_enabled = true;
|
||||
tick();
|
||||
assert.deepStrictEqual(told, ['0', '1']);
|
||||
apply = false;
|
||||
bridge.set(false);
|
||||
assert.deepStrictEqual(writes, [1, 0]);
|
||||
now += 500; tick();
|
||||
assert.deepStrictEqual(told, ['0', '1'], 'the old value is not reported while a write is settling');
|
||||
now += 3000; tick();
|
||||
assert.deepStrictEqual(told, ['0', '1', '1'], 'a write the client did not take is reported as its real value');
|
||||
assert.strictEqual(bridge.set('yes'), true);
|
||||
assert.deepStrictEqual(writes, [1, 0]);
|
||||
bridge.set(false);
|
||||
bridge.set(true);
|
||||
assert.deepStrictEqual(writes, [1, 0, 0, 1], 'a newer opposite value is written while the earlier write is settling');
|
||||
settingsStore.clientSettings.gamescope_hdr_enabled = false;
|
||||
now += 500; tick();
|
||||
settingsStore.clientSettings.gamescope_hdr_enabled = true;
|
||||
now += 500; tick();
|
||||
assert.deepStrictEqual(told, ['0', '1', '1'], 'the earlier write landing late is not reported to the app');
|
||||
delete globalThis.__droiddeckHdr;
|
||||
delete settingsStore.clientSettings.gamescope_hdr_enabled;
|
||||
assert.strictEqual(eval(script), 'unavailable');
|
||||
"""
|
||||
|
||||
|
||||
class HdrSteamSyncTest(unittest.TestCase):
|
||||
def test_bridge_keeps_the_client_setting_and_the_app_equal(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
script = Path(directory) / "bridge.js"
|
||||
script.write_text(LIVE["HDR_JS"])
|
||||
test = Path(directory) / "test.js"
|
||||
test.write_text(HARNESS)
|
||||
result = subprocess.run(["node", str(test), str(script)], capture_output=True, text=True, timeout=20)
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
|
||||
def test_requests_accept_only_on_and_off(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
path = Path(directory) / "hdr.request"
|
||||
for value in ["2", "true", "", None, 1]:
|
||||
LIVE["hdr_request"](value, directory)
|
||||
self.assertFalse(path.exists())
|
||||
LIVE["hdr_request"]("1", directory)
|
||||
self.assertEqual(path.read_text(), "1\n")
|
||||
LIVE["hdr_request"]("0", directory)
|
||||
self.assertEqual(path.read_text(), "0\n")
|
||||
|
||||
def helper(self, directory):
|
||||
helper = LIVE["Helper"]("/steam", 0)
|
||||
calls = []
|
||||
|
||||
class Page:
|
||||
answer = True
|
||||
|
||||
def call(self, method, params=None):
|
||||
calls.append((method, params))
|
||||
|
||||
def evaluate(self, expression):
|
||||
calls.append(expression)
|
||||
return "installed" if expression == LIVE["HDR_JS"] else self.answer
|
||||
|
||||
helper.page = Page()
|
||||
return helper, calls
|
||||
|
||||
def test_the_app_state_is_applied_once_per_change(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
globals_ = LIVE["Helper"].sync_hdr.__globals__
|
||||
previous = globals_["CONTROLS_DIR"]
|
||||
try:
|
||||
globals_["CONTROLS_DIR"] = directory
|
||||
helper, calls = self.helper(directory)
|
||||
path = Path(directory) / "state.json"
|
||||
helper.sync_hdr()
|
||||
path.write_text(json.dumps({"brightness": 0.5}))
|
||||
helper.sync_hdr()
|
||||
self.assertEqual(calls, [], "a session that cannot show HDR leaves the client setting alone")
|
||||
path.write_text(json.dumps({"brightness": 0.5, "hdr": True}))
|
||||
helper.sync_hdr()
|
||||
helper.sync_hdr()
|
||||
self.assertEqual(calls[0], ("Runtime.addBinding", {"name": LIVE["HDR_BINDING"]}))
|
||||
self.assertEqual(calls[1], LIVE["HDR_JS"])
|
||||
self.assertEqual(calls[2:], ["window.__droiddeckHdr ? window.__droiddeckHdr.set(true) : false"])
|
||||
path.write_text(json.dumps({"brightness": 0.7, "hdr": True}))
|
||||
helper.sync_hdr()
|
||||
self.assertEqual(len(calls), 3)
|
||||
path.write_text(json.dumps({"hdr": False}))
|
||||
helper.sync_hdr()
|
||||
self.assertEqual(calls[3], "window.__droiddeckHdr ? window.__droiddeckHdr.set(false) : false")
|
||||
helper.page.answer = False
|
||||
path.write_text(json.dumps({"hdr": True}))
|
||||
helper.sync_hdr()
|
||||
self.assertFalse(helper.hdr_installed)
|
||||
self.assertIsNone(helper.hdr_state)
|
||||
helper.page.answer = True
|
||||
path.write_text(json.dumps({"hdr": False}))
|
||||
helper.sync_hdr()
|
||||
self.assertEqual(calls[-1], "window.__droiddeckHdr ? window.__droiddeckHdr.set(false) : false")
|
||||
finally:
|
||||
globals_["CONTROLS_DIR"] = previous
|
||||
|
||||
def test_a_client_without_the_setting_is_left_alone(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
globals_ = LIVE["Helper"].sync_hdr.__globals__
|
||||
previous = globals_["CONTROLS_DIR"]
|
||||
try:
|
||||
globals_["CONTROLS_DIR"] = directory
|
||||
helper, calls = self.helper(directory)
|
||||
helper.page.evaluate = lambda expression: calls.append(expression) or "unavailable"
|
||||
(Path(directory) / "state.json").write_text(json.dumps({"hdr": True}))
|
||||
helper.sync_hdr()
|
||||
self.assertEqual(calls, [("Runtime.addBinding", {"name": LIVE["HDR_BINDING"]}), LIVE["HDR_JS"]])
|
||||
self.assertFalse(helper.hdr_installed)
|
||||
self.assertIsNone(helper.hdr_state)
|
||||
helper.sync_hdr()
|
||||
self.assertEqual(len(calls), 2, "a client without the setting is not asked again straight away")
|
||||
finally:
|
||||
globals_["CONTROLS_DIR"] = previous
|
||||
|
||||
def test_the_app_publishes_and_takes_the_shared_value(self):
|
||||
controls = (APP / "runtime/DeviceControlsComponent.kt").read_text()
|
||||
self.assertIn('if (SessionState.hdrCapable) controls.put("hdr", SessionState.hdr)', controls)
|
||||
self.assertIn('"hdr.request" -> if (text == "0" || text == "1")', controls)
|
||||
self.assertIn('SessionHdr.set(context, SessionPrefs.prefMode(SessionState.mode), text == "1")', controls)
|
||||
self.assertIn('"hdr.request")', controls[controls.index("REQUESTS = setOf"):])
|
||||
session = (APP / "SessionActivity.kt").read_text()
|
||||
self.assertIn("if (key == SessionPrefs.hdrKey(hdrPrefMode()))", session)
|
||||
self.assertIn("registerOnSharedPreferenceChangeListener(hdrPrefListener)", session)
|
||||
self.assertIn("unregisterOnSharedPreferenceChangeListener(hdrPrefListener)", session)
|
||||
|
||||
def test_frame_limit_writes_share_the_setting_writer(self):
|
||||
self.assertIn("(21002, value)", LIVE["FRAME_LIMIT_JS"])
|
||||
self.assertNotIn("__SET_SETTING__", LIVE["FRAME_LIMIT_JS"] + LIVE["HDR_JS"])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -44,10 +44,11 @@ static struct surface surface = { .xdg_toplevel = 1, .toplevel_committed = 1 };
|
||||
static int g_input_pipe[2] = {-1, -1};
|
||||
static atomic_int g_output_refresh_mhz = 60000;
|
||||
static atomic_int g_output_refresh_pending;
|
||||
static atomic_int g_panel_rates_pending;
|
||||
static int g_output_announced_refresh_mhz = 60000;
|
||||
static int g_output_w = 1920, g_output_h = 1080;
|
||||
static int flushes, resizes, pointers, ticks;
|
||||
static int scale_changes, scale_mode, scale_alignment, renders;
|
||||
static int scale_changes, scale_mode, scale_alignment, renders, rate_notifies;
|
||||
static void *g_display;
|
||||
#define WL_OUTPUT_MODE_CURRENT 1
|
||||
#define WL_OUTPUT_MODE_PREFERRED 2
|
||||
@@ -77,6 +78,7 @@ static void vk_present_set_scale_mode(int mode, int alignment) {
|
||||
scale_changes++; scale_mode = mode; scale_alignment = alignment;
|
||||
}
|
||||
static void schedule_render(void) { renders++; }
|
||||
static void refresh_notify_rates(void) { rate_notifies++; }
|
||||
'''
|
||||
|
||||
CHECKS = r'''
|
||||
@@ -138,6 +140,11 @@ int main(void) {
|
||||
droiddeck_wayland_set_output_refresh_rate(90000);
|
||||
drain(); expect(6, 90000, 1);
|
||||
assert(scale_changes == 2 && scale_mode == 1 && scale_alignment == 3 && renders == 2);
|
||||
atomic_store(&g_panel_rates_pending, 1);
|
||||
drain();
|
||||
assert(rate_notifies == 1 && !atomic_load(&g_panel_rates_pending));
|
||||
drain();
|
||||
assert(rate_notifies == 1);
|
||||
close(g_input_pipe[0]); close(g_input_pipe[1]);
|
||||
puts("PASS");
|
||||
}
|
||||
|
||||
@@ -26,7 +26,7 @@ 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 int g_tick_held;
|
||||
static int g_tick_held, g_tick_spare, g_scene_queues;
|
||||
static int64_t g_hold_missed_ns;
|
||||
#define HOLD_RETRY_NS 1000000000LL
|
||||
static int64_t g_refresh_ns = 16666667;
|
||||
@@ -254,6 +254,15 @@ int main(void) {
|
||||
clock_ns += 200000000LL;
|
||||
schedule_render();
|
||||
assert(idles_added == idles && g_fallback_armed == 1 && timers_armed == 1);
|
||||
g_rendered_tick_ns = g_tick_vsync_ns;
|
||||
g_tick_spare = 0; g_scene_queues = 1;
|
||||
assert(!tick_takes_scene());
|
||||
g_tick_spare = 1;
|
||||
assert(tick_takes_scene());
|
||||
g_scene_queues = 0;
|
||||
assert(!tick_takes_scene());
|
||||
g_rendered_tick_ns = g_tick_vsync_ns - 1;
|
||||
assert(tick_takes_scene());
|
||||
puts("PASS");
|
||||
return 0;
|
||||
}
|
||||
@@ -270,7 +279,7 @@ class RenderOnCommitTest(unittest.TestCase):
|
||||
render = extract_function(source, 'render_scene')
|
||||
self.assertIn('g_rendered_tick_ns = g_tick_vsync_ns;', render)
|
||||
self.assertIn('g_tick_held = 0;', render)
|
||||
functions = ('scene_held_for_limit', 'commit_renders_on', 'render_on_commit', 'schedule_render', 'scene_waits_for_game', 'on_commit_idle',
|
||||
functions = ('scene_held_for_limit', 'commit_renders_on', 'tick_takes_scene', 'render_on_commit', 'schedule_render', 'scene_waits_for_game', 'on_commit_idle',
|
||||
'bfi_blocked', 'bfi_update', 'bfi_tick', '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:
|
||||
|
||||
@@ -33,6 +33,7 @@ static const uint32_t g_qfam = 2;
|
||||
%(is_dmabuf)s
|
||||
%(width)s
|
||||
%(height)s
|
||||
static int black_fill_below(const struct draw_list *dl, int n) { (void)dl; (void)n; return 0; }
|
||||
%(candidate)s
|
||||
|
||||
static int candidate(struct vkp_image *img) {
|
||||
|
||||
@@ -110,7 +110,7 @@ struct damage_list { int n; };
|
||||
struct surface {
|
||||
struct vkp_image *shm_img;
|
||||
struct wl_resource *resource;
|
||||
int buf_w, buf_h, buf_alpha, has_content;
|
||||
int buf_w, buf_h, buf_alpha, has_content, black_fill;
|
||||
/* Read by take_shm's game-frame detection; with no damage it stays off here. */
|
||||
int src_set; float src[4];
|
||||
struct damage_list damage_buf, damage_local;
|
||||
|
||||
Reference in new issue
Block a user