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:
MaxsTechReview authored and GitHub committed 2026-11-21 00:26:50 -05:00
1 parent f29f72d5d9
commit 4349563fd1
101 files changed
+3927 -624

No files matched your search

@@ -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()
+87
View File
@@ -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()
+185
View File
@@ -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()
+8 -1
View File
@@ -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");
}
+11 -2
View File
@@ -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:
+1
View File
@@ -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) {
+1 -1
View File
@@ -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;