From c327ac2633942bd9b7d843053ca41063d0b65bb7 Mon Sep 17 00:00:00 2001 From: Alex Andres Date: Thu, 5 Nov 2026 12:45:43 +0100 Subject: [PATCH] fix: keep sleep prevented until the last request is released Each PowerManagement instance is now one idempotent request, and the native assertion is released with the last one. Windows moves to power requests, since the thread execution state cannot be released from another thread. --- docs/tools/desktop/power-management.md | 9 +- .../main/cpp/include/JNI_PowerManagement.h | 8 +- .../media/video/desktop/PowerManagement.h | 2 + .../desktop/linux/LinuxPowerManagement.h | 2 + .../desktop/windows/WindowsPowerManagement.h | 7 + .../src/main/cpp/src/JNI_PowerManagement.cpp | 4 +- .../desktop/linux/LinuxPowerManagement.cpp | 11 ++ .../desktop/macos/MacOSPowerManagement.cpp | 4 + .../windows/WindowsPowerManagement.cpp | 48 +++++- .../media/video/desktop/PowerManagement.java | 51 ++++++- .../video/desktop/PowerManagementTests.java | 137 ++++++++++++++++++ 11 files changed, 266 insertions(+), 17 deletions(-) create mode 100644 webrtc/src/test/java/dev/onvoid/webrtc/media/video/desktop/PowerManagementTests.java diff --git a/docs/tools/desktop/power-management.md b/docs/tools/desktop/power-management.md index 241c38281..690dfce17 100644 --- a/docs/tools/desktop/power-management.md +++ b/docs/tools/desktop/power-management.md @@ -12,8 +12,8 @@ API: `dev.onvoid.webrtc.media.video.desktop.PowerManagement` - **Responsibility**: You must explicitly disable the assertion when you are done. Key methods: -- `void enableUserActivity()` – Declare the user as active; prevents idle sleep. -- `void disableUserActivity()` – Revoke the assertion; system idle behavior resumes normally. +- `void enableUserActivity()` – Declare the user as active; prevents idle sleep. Enabling an instance repeatedly counts once. +- `void disableUserActivity()` – End the request of this instance; system idle behavior resumes normally once no other instance has an active request. ## Typical usage @@ -38,13 +38,14 @@ finally { ## Integration tips -- Lifetime management: Keep the `PowerManagement` instance for as long as you need the assertion. It's safe to call `enableUserActivity()` once at the start and `disableUserActivity()` once at the end. +- Lifetime management: Keep the `PowerManagement` instance for as long as you need the assertion. Each instance is one independent request, so disabling another instance does not end it. +- Multiple users: Give each component its own instance. The system may idle to sleep again only after the last enabled instance of the process is disabled, on whichever thread. - Fail‑safe: If your workflow can terminate unexpectedly, ensure `disableUserActivity()` is called (e.g., in `finally` blocks, shutdown hooks, or close handlers). - Minimal footprint: Only enable while strictly necessary. Do not keep the assertion enabled longer than needed. ## Platform notes -- **Windows**: Uses native Windows power APIs to request that the display remain on while enabled. +- **Windows**: Uses Windows power requests to keep the display on while enabled. - **Linux** (Freedesktop environments): Uses DBus screensaver inhibition (e.g., org.freedesktop.ScreenSaver) where available. - **macOS**: Uses macOS power management assertions to prevent display sleep while enabled. diff --git a/webrtc-jni/src/main/cpp/include/JNI_PowerManagement.h b/webrtc-jni/src/main/cpp/include/JNI_PowerManagement.h index f55be85fc..5cead5923 100644 --- a/webrtc-jni/src/main/cpp/include/JNI_PowerManagement.h +++ b/webrtc-jni/src/main/cpp/include/JNI_PowerManagement.h @@ -9,18 +9,18 @@ extern "C" { #endif /* * Class: dev_onvoid_webrtc_media_video_desktop_PowerManagement - * Method: enableUserActivity + * Method: enableUserActivityInternal * Signature: ()V */ - JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_video_desktop_PowerManagement_enableUserActivity + JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_video_desktop_PowerManagement_enableUserActivityInternal (JNIEnv *, jobject); /* * Class: dev_onvoid_webrtc_media_video_desktop_PowerManagement - * Method: disableUserActivity + * Method: disableUserActivityInternal * Signature: ()V */ - JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_video_desktop_PowerManagement_disableUserActivity + JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_video_desktop_PowerManagement_disableUserActivityInternal (JNIEnv *, jobject); #ifdef __cplusplus diff --git a/webrtc-jni/src/main/cpp/include/media/video/desktop/PowerManagement.h b/webrtc-jni/src/main/cpp/include/media/video/desktop/PowerManagement.h index b5e8e74c7..94637ae66 100644 --- a/webrtc-jni/src/main/cpp/include/media/video/desktop/PowerManagement.h +++ b/webrtc-jni/src/main/cpp/include/media/video/desktop/PowerManagement.h @@ -27,6 +27,8 @@ namespace jni PowerManagement() = default; virtual ~PowerManagement() = default; + // Both are idempotent: the assertion is taken once and released once. Callers + // must serialize them; the Java class counts the requests of its instances. virtual void enableUserActivity() = 0; virtual void disableUserActivity() = 0; }; diff --git a/webrtc-jni/src/main/cpp/include/media/video/desktop/linux/LinuxPowerManagement.h b/webrtc-jni/src/main/cpp/include/media/video/desktop/linux/LinuxPowerManagement.h index e01b92fe0..31b30d58d 100644 --- a/webrtc-jni/src/main/cpp/include/media/video/desktop/linux/LinuxPowerManagement.h +++ b/webrtc-jni/src/main/cpp/include/media/video/desktop/linux/LinuxPowerManagement.h @@ -35,7 +35,9 @@ namespace jni void disableUserActivity(); private: + // Any value is a valid cookie, so it cannot tell whether one is held. uint32_t dbusCookie = 0; + bool inhibited = false; // KDE >= 4 and GNOME >= 3.10 const char * BUS_SERVICE_NAME = "org.freedesktop.ScreenSaver"; diff --git a/webrtc-jni/src/main/cpp/include/media/video/desktop/windows/WindowsPowerManagement.h b/webrtc-jni/src/main/cpp/include/media/video/desktop/windows/WindowsPowerManagement.h index d1929846c..298bfe055 100644 --- a/webrtc-jni/src/main/cpp/include/media/video/desktop/windows/WindowsPowerManagement.h +++ b/webrtc-jni/src/main/cpp/include/media/video/desktop/windows/WindowsPowerManagement.h @@ -19,6 +19,8 @@ #include "media/video/desktop/PowerManagement.h" +#include + namespace jni { namespace avdev @@ -31,6 +33,11 @@ namespace jni void enableUserActivity(); void disableUserActivity(); + + private: + // Unlike SetThreadExecutionState, not tied to the calling thread: the last + // release may come from another thread and the enabling thread may exit. + HANDLE powerRequest = nullptr; }; } } diff --git a/webrtc-jni/src/main/cpp/src/JNI_PowerManagement.cpp b/webrtc-jni/src/main/cpp/src/JNI_PowerManagement.cpp index 71ebc9d29..38fd5220d 100644 --- a/webrtc-jni/src/main/cpp/src/JNI_PowerManagement.cpp +++ b/webrtc-jni/src/main/cpp/src/JNI_PowerManagement.cpp @@ -17,7 +17,7 @@ #include "JNI_PowerManagement.h" #include "WebRTCContext.h" -JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_video_desktop_PowerManagement_enableUserActivity +JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_video_desktop_PowerManagement_enableUserActivityInternal (JNIEnv * env, jobject caller) { jni::WebRTCContext * context = static_cast(javaContext); @@ -32,7 +32,7 @@ JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_video_desktop_PowerManagemen fflush(NULL); } -JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_video_desktop_PowerManagement_disableUserActivity +JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_video_desktop_PowerManagement_disableUserActivityInternal (JNIEnv * env, jobject caller) { jni::WebRTCContext * context = static_cast(javaContext); diff --git a/webrtc-jni/src/main/cpp/src/media/video/desktop/linux/LinuxPowerManagement.cpp b/webrtc-jni/src/main/cpp/src/media/video/desktop/linux/LinuxPowerManagement.cpp index 2aa061912..c75201dff 100644 --- a/webrtc-jni/src/main/cpp/src/media/video/desktop/linux/LinuxPowerManagement.cpp +++ b/webrtc-jni/src/main/cpp/src/media/video/desktop/linux/LinuxPowerManagement.cpp @@ -32,6 +32,10 @@ namespace jni void LinuxPowerManagement::enableUserActivity() { + if (inhibited) { + return; + } + if (!DBusLoader::instance().load()) { RTC_LOG(LS_WARNING) << "[PowerManagement] libdbus not found on system"; return; @@ -84,6 +88,7 @@ namespace jni DBusMessageIter reply_iter; dbus.dbus_message_iter_init(reply, &reply_iter); dbus.dbus_message_iter_get_basic(&reply_iter, &dbusCookie); + inhibited = true; RTC_LOG(LS_INFO) << "[PowerManagement] Acquired screensaver inhibition cookie"; @@ -93,6 +98,10 @@ namespace jni void LinuxPowerManagement::disableUserActivity() { + if (!inhibited) { + return; + } + if (!DBusLoader::instance().load()) { RTC_LOG(LS_WARNING) << "[PowerManagement] libdbus not found on system"; return; @@ -134,6 +143,8 @@ namespace jni return; } + inhibited = false; + RTC_LOG(LS_INFO) << "[PowerManagement] Released screensaver inhibition cookie"; dbus.dbus_message_unref(reply); diff --git a/webrtc-jni/src/main/cpp/src/media/video/desktop/macos/MacOSPowerManagement.cpp b/webrtc-jni/src/main/cpp/src/media/video/desktop/macos/MacOSPowerManagement.cpp index 426fb9345..5e0f452ee 100644 --- a/webrtc-jni/src/main/cpp/src/media/video/desktop/macos/MacOSPowerManagement.cpp +++ b/webrtc-jni/src/main/cpp/src/media/video/desktop/macos/MacOSPowerManagement.cpp @@ -27,6 +27,10 @@ namespace jni void MacOSPowerManagement::enableUserActivity() { + if (powerAssertion != kIOPMNullAssertionID) { + return; + } + CFStringRef name = CFSTR("WebRTC-Java processing"); if (IOPMAssertionCreateWithName(kIOPMAssertionTypeNoDisplaySleep, kIOPMAssertionLevelOn, name, &powerAssertion) != kIOReturnSuccess) { diff --git a/webrtc-jni/src/main/cpp/src/media/video/desktop/windows/WindowsPowerManagement.cpp b/webrtc-jni/src/main/cpp/src/media/video/desktop/windows/WindowsPowerManagement.cpp index 8ae57ea21..0be2e4524 100644 --- a/webrtc-jni/src/main/cpp/src/media/video/desktop/windows/WindowsPowerManagement.cpp +++ b/webrtc-jni/src/main/cpp/src/media/video/desktop/windows/WindowsPowerManagement.cpp @@ -16,24 +16,66 @@ #include "media/video/desktop/windows/WindowsPowerManagement.h" -#include +#include "rtc_base/logging.h" namespace jni { namespace avdev { + namespace + { + constexpr POWER_REQUEST_TYPE kPowerRequestTypes[] = { + PowerRequestDisplayRequired, + PowerRequestSystemRequired, + PowerRequestAwayModeRequired + }; + } + WindowsPowerManagement::WindowsPowerManagement() { } void WindowsPowerManagement::enableUserActivity() { - SetThreadExecutionState(ES_CONTINUOUS | ES_SYSTEM_REQUIRED | ES_AWAYMODE_REQUIRED | ES_DISPLAY_REQUIRED); + if (powerRequest != nullptr) { + return; + } + + wchar_t reason[] = L"WebRTC-Java processing"; + + REASON_CONTEXT context = {}; + context.Version = POWER_REQUEST_CONTEXT_VERSION; + context.Flags = POWER_REQUEST_CONTEXT_SIMPLE_STRING; + context.Reason.SimpleReasonString = reason; + + HANDLE request = PowerCreateRequest(&context); + + if (request == INVALID_HANDLE_VALUE) { + RTC_LOG(LS_ERROR) << "[PowerManagement] Cannot create power request: " << GetLastError(); + return; + } + + for (POWER_REQUEST_TYPE type : kPowerRequestTypes) { + if (!PowerSetRequest(request, type)) { + RTC_LOG(LS_WARNING) << "[PowerManagement] Cannot set power request " << static_cast(type) << ": " << GetLastError(); + } + } + + powerRequest = request; } void WindowsPowerManagement::disableUserActivity() { - SetThreadExecutionState(ES_CONTINUOUS); + if (powerRequest == nullptr) { + return; + } + + for (POWER_REQUEST_TYPE type : kPowerRequestTypes) { + PowerClearRequest(powerRequest, type); + } + + CloseHandle(powerRequest); + powerRequest = nullptr; } } } \ No newline at end of file diff --git a/webrtc/src/main/java/dev/onvoid/webrtc/media/video/desktop/PowerManagement.java b/webrtc/src/main/java/dev/onvoid/webrtc/media/video/desktop/PowerManagement.java index 4ae1c1886..6d72d4f71 100644 --- a/webrtc/src/main/java/dev/onvoid/webrtc/media/video/desktop/PowerManagement.java +++ b/webrtc/src/main/java/dev/onvoid/webrtc/media/video/desktop/PowerManagement.java @@ -20,11 +20,26 @@ /** * Power management assertions to wake the display and prevent it from going to sleep on user idle. + *

+ * Each instance is one independent request. Enabling an instance repeatedly counts once, so a single + * {@link #disableUserActivity()} ends its request. The system may idle to sleep again once the last + * enabled instance of this process is disabled. Keep the instance that enabled the request, since + * disabling another instance does not end it. All methods are thread-safe. * * @author Alex Andres */ public class PowerManagement { + /** Guards the request state and serializes access to the process-wide native assertion. */ + private static final Object LOCK = new Object(); + + /** The number of instances with an active request. */ + private static int activeRequests; + + /** Whether this instance has an active request. */ + private boolean active; + + static { try { NativeLoader.loadLibrary("webrtc-java"); @@ -35,13 +50,41 @@ public class PowerManagement { } /** - * Declares that the user is active on the system and prevents the sleep idle time-out. + * Declares that the user is active on the system and prevents the sleep idle time-out. Has no further + * effect if this instance is already enabled. */ - native public void enableUserActivity(); + public void enableUserActivity() { + synchronized (LOCK) { + if (!active) { + active = true; + activeRequests++; + } + + // No-op while the native assertion is held; otherwise retries one that could not be taken. + enableUserActivityInternal(); + } + } /** - * Declares that the user is no longer active on the system and allow the system to idle to sleep normally. + * Ends the request of this instance. The system may idle to sleep normally once no other instance has + * an active request. Has no further effect if this instance is not enabled. */ - native public void disableUserActivity(); + public void disableUserActivity() { + synchronized (LOCK) { + if (active) { + active = false; + activeRequests--; + } + + // No-op without a native assertion; otherwise also retries a release that failed. + if (activeRequests == 0) { + disableUserActivityInternal(); + } + } + } + + native void enableUserActivityInternal(); + + native void disableUserActivityInternal(); } diff --git a/webrtc/src/test/java/dev/onvoid/webrtc/media/video/desktop/PowerManagementTests.java b/webrtc/src/test/java/dev/onvoid/webrtc/media/video/desktop/PowerManagementTests.java new file mode 100644 index 000000000..d1b590fdc --- /dev/null +++ b/webrtc/src/test/java/dev/onvoid/webrtc/media/video/desktop/PowerManagementTests.java @@ -0,0 +1,137 @@ +/* + * Copyright 2019 Alex Andres + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package dev.onvoid.webrtc.media.video.desktop; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertEquals; + +import dev.onvoid.webrtc.TestBase; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +class PowerManagementTests extends TestBase { + + private int released; + + + @BeforeEach + void resetReleased() { + released = 0; + } + + @Test + void nativeCallsSucceed() { + PowerManagement powerManagement = new PowerManagement(); + + // Repeated on purpose, what the assertion does depends on the system running the test. + assertDoesNotThrow(() -> { + powerManagement.enableUserActivity(); + powerManagement.enableUserActivity(); + powerManagement.disableUserActivity(); + powerManagement.disableUserActivity(); + }); + } + + @Test + void repeatedEnableNeedsOneDisable() { + PowerManagement powerManagement = new RecordingPowerManagement(); + + powerManagement.enableUserActivity(); + powerManagement.enableUserActivity(); + powerManagement.disableUserActivity(); + + assertEquals(1, released); + } + + @Test + void lastInstanceReleases() { + PowerManagement first = new RecordingPowerManagement(); + PowerManagement second = new RecordingPowerManagement(); + + first.enableUserActivity(); + second.enableUserActivity(); + first.disableUserActivity(); + + assertEquals(0, released); + + second.disableUserActivity(); + + assertEquals(1, released); + } + + @Test + void repeatedDisableKeepsOtherRequest() { + PowerManagement first = new RecordingPowerManagement(); + PowerManagement second = new RecordingPowerManagement(); + + first.enableUserActivity(); + second.enableUserActivity(); + first.disableUserActivity(); + first.disableUserActivity(); + + assertEquals(0, released); + + second.disableUserActivity(); + + assertEquals(1, released); + } + + @Test + void disabledInstanceKeepsOtherRequest() { + PowerManagement enabled = new RecordingPowerManagement(); + PowerManagement disabled = new RecordingPowerManagement(); + + enabled.enableUserActivity(); + disabled.disableUserActivity(); + + assertEquals(0, released); + + enabled.disableUserActivity(); + + assertEquals(1, released); + } + + @Test + void enableAfterRelease() { + PowerManagement powerManagement = new RecordingPowerManagement(); + + powerManagement.enableUserActivity(); + powerManagement.disableUserActivity(); + powerManagement.enableUserActivity(); + powerManagement.disableUserActivity(); + + assertEquals(2, released); + } + + + /** + * Keeps the system assertion out of these tests. The request state is process-wide, so each test + * disables all instances it enabled. + */ + private class RecordingPowerManagement extends PowerManagement { + + @Override + void enableUserActivityInternal() { + } + + @Override + void disableUserActivityInternal() { + released++; + } + } +}