Преглед изворни кода

fixed audio on 5.1. fixed hrtf. small gnome fixes

UwU пре 1 месец
родитељ
комит
5ec01f0cc7
100 измењених фајлова са 5054 додато и 995 уклоњено
  1. 44 2
      CMakeLists.txt
  2. 6 1
      README.md
  3. 1 1
      gnome-shell-extension/linux-wallpaperengine@wallpaperenginelover.github.io/extension.js
  4. 1 1
      gnome-shell-extension/linux-wallpaperengine@wallpaperenginelover.github.io/metadata.json
  5. 1 0
      nix/package.nix
  6. 2 0
      packaging/aur/linux-wallpaperengine-kde-bin/PKGBUILD
  7. 2 0
      packaging/aur/linux-wallpaperengine-kde-git/PKGBUILD
  8. 102 0
      protocols/fractional-scale-v1.xml
  9. BIN
      resources/icons/hicolor/128x128/apps/linux-wallpaperengine.png
  10. BIN
      resources/icons/hicolor/16x16/apps/linux-wallpaperengine.png
  11. BIN
      resources/icons/hicolor/22x22/apps/linux-wallpaperengine.png
  12. BIN
      resources/icons/hicolor/24x24/apps/linux-wallpaperengine.png
  13. BIN
      resources/icons/hicolor/256x256/apps/linux-wallpaperengine.png
  14. BIN
      resources/icons/hicolor/32x32/apps/linux-wallpaperengine.png
  15. BIN
      resources/icons/hicolor/48x48/apps/linux-wallpaperengine.png
  16. BIN
      resources/icons/hicolor/512x512/apps/linux-wallpaperengine.png
  17. BIN
      resources/icons/hicolor/64x64/apps/linux-wallpaperengine.png
  18. BIN
      resources/icons/icon-source.png
  19. BIN
      resources/icons/linux-wallpaperengine.png
  20. 9 0
      resources/linux-wallpaperengine.desktop
  21. 40 0
      src/WallpaperEngine/Application/ApplicationContext.cpp
  22. 16 0
      src/WallpaperEngine/Application/ApplicationContext.h
  23. 94 128
      src/WallpaperEngine/Application/WallpaperApplication.cpp
  24. 9 0
      src/WallpaperEngine/Application/WallpaperApplication.h
  25. 11 0
      src/WallpaperEngine/Audio/AudioContext.cpp
  26. 9 0
      src/WallpaperEngine/Audio/AudioContext.h
  27. 221 154
      src/WallpaperEngine/Audio/AudioStream.cpp
  28. 43 8
      src/WallpaperEngine/Audio/AudioStream.h
  29. 23 0
      src/WallpaperEngine/Audio/Drivers/AudioDriver.h
  30. 234 0
      src/WallpaperEngine/Audio/Drivers/Detectors/HeadphonesDetector.cpp
  31. 51 0
      src/WallpaperEngine/Audio/Drivers/Detectors/HeadphonesDetector.h
  32. 397 100
      src/WallpaperEngine/Audio/Drivers/SDLAudioDriver.cpp
  33. 79 9
      src/WallpaperEngine/Audio/Drivers/SDLAudioDriver.h
  34. 550 0
      src/WallpaperEngine/Audio/Hrtf.cpp
  35. 91 0
      src/WallpaperEngine/Audio/Hrtf.h
  36. 6 0
      src/WallpaperEngine/Audio/resources/DefaultHrtf.generated.h.in
  37. BIN
      src/WallpaperEngine/Audio/resources/default_hrtf.mhr
  38. 2 0
      src/WallpaperEngine/Data/Model/Object.h
  39. 9 0
      src/WallpaperEngine/Data/Model/Wallpaper.h
  40. 1 0
      src/WallpaperEngine/Data/Parsers/ObjectParser.cpp
  41. 37 0
      src/WallpaperEngine/Data/Parsers/WallpaperParser.cpp
  42. 1 31
      src/WallpaperEngine/Desktop/GnomeShell.cpp
  43. 183 0
      src/WallpaperEngine/Desktop/HostWayland.cpp
  44. 17 0
      src/WallpaperEngine/Desktop/HostWayland.h
  45. 136 0
      src/WallpaperEngine/Desktop/HyprlandIPC.cpp
  46. 19 0
      src/WallpaperEngine/Desktop/HyprlandIPC.h
  47. 53 0
      src/WallpaperEngine/Desktop/SessionBus.cpp
  48. 12 0
      src/WallpaperEngine/Desktop/SessionBus.h
  49. 3 3
      src/WallpaperEngine/Input/Drivers/KDECursorInput.cpp
  50. 83 52
      src/WallpaperEngine/Input/Drivers/WaylandMouseInput.cpp
  51. 8 1
      src/WallpaperEngine/Input/Drivers/WaylandMouseInput.h
  52. 5 0
      src/WallpaperEngine/Input/MouseInput.h
  53. 5 0
      src/WallpaperEngine/Render/CTexture.cpp
  54. 102 4
      src/WallpaperEngine/Render/CWallpaper.cpp
  55. 13 1
      src/WallpaperEngine/Render/CWallpaper.h
  56. 32 7
      src/WallpaperEngine/Render/Drivers/Detectors/KDEWaylandFullScreenDetector.cpp
  57. 226 156
      src/WallpaperEngine/Render/Drivers/Detectors/WaylandFullScreenDetector.cpp
  58. 51 15
      src/WallpaperEngine/Render/Drivers/Detectors/WaylandFullScreenDetector.h
  59. 5 3
      src/WallpaperEngine/Render/Drivers/Output/WaylandOutput.cpp
  60. 81 15
      src/WallpaperEngine/Render/Drivers/Output/WaylandOutputViewport.cpp
  61. 16 0
      src/WallpaperEngine/Render/Drivers/Output/WaylandOutputViewport.h
  62. 42 6
      src/WallpaperEngine/Render/Drivers/WaylandOpenGLDriver.cpp
  63. 5 0
      src/WallpaperEngine/Render/Drivers/WaylandOpenGLDriver.h
  64. 102 9
      src/WallpaperEngine/Render/Objects/CSound.cpp
  65. 28 4
      src/WallpaperEngine/Render/Objects/CSound.h
  66. 31 10
      src/WallpaperEngine/Render/Wallpapers/CScene.cpp
  67. 1 1
      src/WallpaperEngine/Render/Wallpapers/CSplat.cpp
  68. 2 0
      src/WallpaperEngine/Render/Wallpapers/CVideo.cpp
  69. 2 2
      src/WallpaperEngine/Render/Wallpapers/CWeb.cpp
  70. 185 78
      src/WallpaperEngine/Scripting/Adapters/ScriptableObjectAdapter.cpp
  71. 15 0
      src/WallpaperEngine/Scripting/Adapters/ScriptableObjectAdapter.h
  72. 10 3
      src/WallpaperEngine/Scripting/SceneObject.cpp
  73. 90 120
      src/WallpaperEngine/Scripting/ScriptEngine.cpp
  74. 5 15
      src/WallpaperEngine/Scripting/ScriptEngine.h
  75. 7 0
      src/WallpaperEngine/Scripting/ScriptableObject.cpp
  76. 133 0
      src/WallpaperEngine/Testing/Cases/HyprlandIPC.cpp
  77. 69 0
      src/WallpaperEngine/Testing/Cases/WebHostFiles.cpp
  78. 97 18
      src/WallpaperEngine/VideoPlayback/MPV/GLPlayer.cpp
  79. 20 2
      src/WallpaperEngine/VideoPlayback/MPV/GLPlayer.h
  80. 15 1
      src/WallpaperEngine/WebBrowser/CEF/BrowserApp.cpp
  81. 83 21
      src/WallpaperEngine/WebBrowser/IPC/WebHostSharedMemory.cpp
  82. 11 2
      src/WallpaperEngine/WebBrowser/IPC/WebHostSharedMemory.h
  83. 23 2
      src/WallpaperEngine/WebBrowser/WebBrowserContext.cpp
  84. 4 0
      src/WallpaperEngine/WebBrowser/WebBrowserContext.h
  85. 38 5
      src/gnome_wayland_helper.c
  86. 4 0
      src/main.cpp
  87. 1 0
      tests/desktops/fixtures/posprobe/project.json
  88. 32 0
      tests/desktops/fixtures/posprobe/scene.json
  89. 98 0
      tests/desktops/test_fractional_scale.py
  90. 3 1
      tests/desktops/test_gnome.py
  91. 114 0
      tests/desktops/test_span.py
  92. 90 0
      tests/desktops/test_wlroots_pause.py
  93. 1 1
      tools/desktops/__init__.py
  94. 1 1
      tools/desktops/rootfs-ubuntu-kde5.txt
  95. 73 1
      tools/desktops/session.py
  96. 152 0
      tools/desktops/wlr-virtual-pointer-unstable-v1.xml
  97. 66 0
      tools/desktops/wlr_virtual_pointer.c
  98. 55 0
      tools/gpu_meter.sh
  99. 76 0
      tools/linuxvm/cdp.py
  100. 128 0
      tools/linuxvm/linuxvm.sh

+ 44 - 2
CMakeLists.txt

@@ -189,6 +189,14 @@ if(WAYLAND_SUPPORT_FOUND)
         COMMAND ${WaylandScanner} client-header ${CMAKE_CURRENT_SOURCE_DIR}/protocols/color-management-v1.xml ${WAYLAND_OUTPUT_DIR}/color-management-v1-protocol.h)
     add_custom_command(OUTPUT ${WAYLAND_OUTPUT_DIR}/color-management-v1-protocol.c
         COMMAND ${WaylandScanner} private-code ${CMAKE_CURRENT_SOURCE_DIR}/protocols/color-management-v1.xml ${WAYLAND_OUTPUT_DIR}/color-management-v1-protocol.c)
+    add_custom_command(OUTPUT ${WAYLAND_OUTPUT_DIR}/fractional-scale-v1-protocol.h
+        COMMAND ${WaylandScanner} client-header ${CMAKE_CURRENT_SOURCE_DIR}/protocols/fractional-scale-v1.xml ${WAYLAND_OUTPUT_DIR}/fractional-scale-v1-protocol.h)
+    add_custom_command(OUTPUT ${WAYLAND_OUTPUT_DIR}/fractional-scale-v1-protocol.c
+        COMMAND ${WaylandScanner} private-code ${CMAKE_CURRENT_SOURCE_DIR}/protocols/fractional-scale-v1.xml ${WAYLAND_OUTPUT_DIR}/fractional-scale-v1-protocol.c)
+    add_custom_command(OUTPUT ${WAYLAND_OUTPUT_DIR}/viewporter-protocol.h
+        COMMAND ${WaylandScanner} client-header ${WAYLAND_PROTOCOLS_DIR}/stable/viewporter/viewporter.xml ${WAYLAND_OUTPUT_DIR}/viewporter-protocol.h)
+    add_custom_command(OUTPUT ${WAYLAND_OUTPUT_DIR}/viewporter-protocol.c
+        COMMAND ${WaylandScanner} private-code ${WAYLAND_PROTOCOLS_DIR}/stable/viewporter/viewporter.xml ${WAYLAND_OUTPUT_DIR}/viewporter-protocol.c)
     add_custom_command(OUTPUT ${WAYLAND_OUTPUT_DIR}/xdg-shell-protocol.h
         COMMAND ${WaylandScanner} client-header ${WAYLAND_PROTOCOLS_DIR}/stable/xdg-shell/xdg-shell.xml ${WAYLAND_OUTPUT_DIR}/xdg-shell-protocol.h)
     add_custom_command(OUTPUT ${WAYLAND_OUTPUT_DIR}/xdg-shell-protocol.c
@@ -211,6 +219,8 @@ if(WAYLAND_SUPPORT_FOUND)
         src/WallpaperEngine/Render/Drivers/HeadlessOpenGLDriver.cpp
         src/WallpaperEngine/Render/Drivers/WaylandOpenGLDriver.h
         src/WallpaperEngine/Render/Drivers/WaylandOpenGLDriver.cpp
+        src/WallpaperEngine/Desktop/HostWayland.h
+        src/WallpaperEngine/Desktop/HostWayland.cpp
         src/WallpaperEngine/Render/Drivers/Detectors/WaylandFullScreenDetector.cpp
         src/WallpaperEngine/Render/Drivers/Detectors/WaylandFullScreenDetector.h
         src/WallpaperEngine/Render/Drivers/Detectors/GnomeFullScreenDetector.cpp
@@ -230,7 +240,11 @@ if(WAYLAND_SUPPORT_FOUND)
         ${WAYLAND_OUTPUT_DIR}/xdg-output-unstable-v1-protocol.c
         ${WAYLAND_OUTPUT_DIR}/xdg-output-unstable-v1-protocol.h
         ${WAYLAND_OUTPUT_DIR}/color-management-v1-protocol.c
-        ${WAYLAND_OUTPUT_DIR}/color-management-v1-protocol.h)
+        ${WAYLAND_OUTPUT_DIR}/color-management-v1-protocol.h
+        ${WAYLAND_OUTPUT_DIR}/fractional-scale-v1-protocol.c
+        ${WAYLAND_OUTPUT_DIR}/fractional-scale-v1-protocol.h
+        ${WAYLAND_OUTPUT_DIR}/viewporter-protocol.c
+        ${WAYLAND_OUTPUT_DIR}/viewporter-protocol.h)
 
     if(NOT DISABLE_KDE_FEATURES)
         pkg_check_modules(DBUS dbus-1)
@@ -319,6 +333,17 @@ configure_file(
 # re-run configuration (regenerating the header) whenever the .js changes
 set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS "${WPENGINE_BUILTINS_JS}")
 
+# OpenAL Soft 1.21.1's built-in HRTF data set (hrtf/Default HRTF.mhr, MIT KEMAR based), the same bytes WE's
+# mediaextensions64.dll embeds, as a byte array for the sound objects' headphones rendering
+set(WPENGINE_DEFAULT_HRTF "${CMAKE_CURRENT_SOURCE_DIR}/src/WallpaperEngine/Audio/resources/default_hrtf.mhr")
+file(READ "${WPENGINE_DEFAULT_HRTF}" WPENGINE_DEFAULT_HRTF_HEX HEX)
+string(REGEX REPLACE "([0-9a-f][0-9a-f])" "0x\\1," WPENGINE_DEFAULT_HRTF_BYTES "${WPENGINE_DEFAULT_HRTF_HEX}")
+configure_file(
+    "${CMAKE_CURRENT_SOURCE_DIR}/src/WallpaperEngine/Audio/resources/DefaultHrtf.generated.h.in"
+    "${WPENGINE_GENERATED_DIR}/WallpaperEngine/Audio/DefaultHrtf.generated.h"
+    @ONLY)
+set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS "${WPENGINE_DEFAULT_HRTF}")
+
 include_directories(
     ${WPENGINE_GENERATED_DIR}
     src
@@ -394,6 +419,8 @@ set(COMMON_SOURCES
     src/WallpaperEngine/Audio/Drivers/Detectors/PulseAudioPlayingDetector.h
     src/WallpaperEngine/Audio/Drivers/Detectors/AudioPlayingDetector.cpp
     src/WallpaperEngine/Audio/Drivers/Detectors/AudioPlayingDetector.h
+    src/WallpaperEngine/Audio/Drivers/Detectors/HeadphonesDetector.cpp
+    src/WallpaperEngine/Audio/Drivers/Detectors/HeadphonesDetector.h
 
     src/WallpaperEngine/Audio/Drivers/AudioDriver.cpp
     src/WallpaperEngine/Audio/Drivers/AudioDriver.h
@@ -403,6 +430,8 @@ set(COMMON_SOURCES
     src/WallpaperEngine/Audio/AudioContext.h
     src/WallpaperEngine/Audio/AudioStream.cpp
     src/WallpaperEngine/Audio/AudioStream.h
+    src/WallpaperEngine/Audio/Hrtf.cpp
+    src/WallpaperEngine/Audio/Hrtf.h
 
     src/WallpaperEngine/Input/InputContext.cpp
     src/WallpaperEngine/Input/InputContext.h
@@ -428,6 +457,8 @@ set(COMMON_SOURCES
     src/WallpaperEngine/Desktop/KWinScript.cpp
     src/WallpaperEngine/Desktop/SessionBus.h
     src/WallpaperEngine/Desktop/SessionBus.cpp
+    src/WallpaperEngine/Desktop/HyprlandIPC.h
+    src/WallpaperEngine/Desktop/HyprlandIPC.cpp
     src/WallpaperEngine/Media/ThumbnailPalette.h
     src/WallpaperEngine/Media/ThumbnailPalette.cpp
 
@@ -700,7 +731,9 @@ if(BUILD_TESTING)
         src/WallpaperEngine/Testing/Cases/TextLayoutRules.cpp
         src/WallpaperEngine/Testing/Cases/MediaCover.cpp
         src/WallpaperEngine/Testing/Cases/ForwardedButton.cpp
-        src/WallpaperEngine/Testing/Cases/LocalStorage.cpp)
+        src/WallpaperEngine/Testing/Cases/LocalStorage.cpp
+        src/WallpaperEngine/Testing/Cases/HyprlandIPC.cpp
+        src/WallpaperEngine/Testing/Cases/WebHostFiles.cpp)
 endif()
 
 add_library(
@@ -833,6 +866,10 @@ add_executable(linux-wallpaperengine
     src/main.cpp)
 
 target_link_libraries (linux-wallpaperengine PUBLIC linux-wallpaperengine-lib)
+# libcef has to load before libc: Chromium's close() wrapper finds libc's with dlsym (RTLD_NEXT), which only searches
+# the objects after libcef. Debian and Ubuntu link --as-needed by default, which dropped the direct dependency and left
+# libcef behind libc, so the web host aborted with "close symbol missing" (portable release, Flatpak, Debian builds)
+target_link_options (linux-wallpaperengine PRIVATE -Wl,--no-as-needed)
 
 # Chromium child processes of the web host, only libcef and the page shim
 add_executable(linux-wallpaperengine-web-helper
@@ -882,6 +919,11 @@ install(TARGETS linux-wallpaperengine-lib
 
 # Install everything else from the output directory (CEF resources, helper binaries, etc.)
 # but exclude the files already handled by install(TARGETS) above.
+# the icon and a hidden desktop entry, which gives windows of the engine (app id and X11 class linux-wallpaperengine)
+# their icon
+install(DIRECTORY resources/icons/hicolor DESTINATION share/icons)
+install(FILES resources/linux-wallpaperengine.desktop DESTINATION share/applications)
+
 install(DIRECTORY ${TARGET_OUTPUT_DIRECTORY}/ DESTINATION . USE_SOURCE_PERMISSIONS
     PATTERN "linux-wallpaperengine" EXCLUDE
     PATTERN "linux-wallpaperengine-web-helper" EXCLUDE

+ 6 - 1
README.md

@@ -133,6 +133,8 @@ cmake -DCMAKE_BUILD_TYPE='Release' -DDISABLE_KDE_FEATURES=ON ..
 
 On KDE Plasma the engine loads KWin scripts of its own for the cursor position and for the windows that pause it (maximized, fullscreen, and focused with `--pause-on-focus`), per screen like Wallpaper Engine; nothing needs installing.
 
+On sway, Hyprland, niri, labwc and other compositors with the wlr foreign toplevel protocol a fullscreen window pauses only the screen it is on (maximized ones too with `--pause-on-maximized`). sway before 1.12 doesn't say which screen a window that opens fullscreen is on, so such a window pauses every screen there.
+
 ## Assets
 
 You need Wallpaper Engine installed through Steam - this is where the backgrounds and shared assets come from. The binary looks for it automatically under:
@@ -218,11 +220,13 @@ The background can be a Steam Workshop ID (`1845706469`) or a path to a backgrou
 | `--input-file <path>` | Wayland: file a desktop shell writes the left button to as `{"leftDown": true}`, refreshed while it is held (ignored after 2 seconds). For shells that cover the background and swallow its pointer events |
 | `--disable-parallax` | Disable parallax |
 | `--no-fullscreen-pause` | Don't pause while an app is fullscreen |
-| `--pause-on-focus` | Also pause while another application has the focus (Wallpaper Engine's "Other application focused: Pause"; on GNOME and KDE only that monitor) |
+| `--pause-on-focus` | Also pause while another application has the focus (Wallpaper Engine's "Other application focused: Pause"; on Wayland only that monitor) |
+| `--pause-on-maximized` | wlroots compositors (sway, Hyprland, niri, labwc...): also pause the monitor a maximized window is on. KDE and GNOME always do, like Wallpaper Engine |
 | `--fullscreen-pause-only-active` | Wayland only: pause only when the fullscreen window is active |
 | `--fullscreen-pause-ignore-appid <val>` | Wayland only: ignore fullscreen windows whose app_id contains `<val>`, repeatable |
 | `--audio-screen <screen>` | Only this screen's background produces audio |
 | `--ambient-volume <val>` | Separate volume for non-video backgrounds; video keeps using `--volume` |
+| `--hrtf <auto\|on\|off>` | Headphones (HRTF) rendering of scene sounds like Wallpaper Engine: `auto` uses it while the default output is headphones or a headset |
 | `--sound-volume <id/name>=<val>` | Per-object volume (0-1), repeatable, `*` for unmatched objects |
 | `--audio-sensitivity <id/name>=<mult>` | Scale an object's audio-reactive swing; `0` disables it, `1` is default; repeatable, `*` for unmatched objects |
 | `--list-audio-objects` | List objects whose script reacts to music |
@@ -351,3 +355,4 @@ Scripting (SceneScript):
 
 - [RePKG](https://github.com/notscuffed/repkg) - texture flag insights
 - [RenderDoc](https://github.com/baldurk/renderdoc) - OpenGL debugging
+- [OpenAL Soft](https://github.com/kcat/openal-soft) (LGPL) - the HRTF renderer for sound objects is a port of its 1.21.1 code, with its built-in data set based on the [MIT KEMAR](http://sound.media.mit.edu/resources/KEMAR.html) measurements (`src/WallpaperEngine/Audio/resources/default_hrtf.mhr`)

+ 1 - 1
gnome-shell-extension/linux-wallpaperengine@wallpaperenginelover.github.io/extension.js

@@ -231,7 +231,7 @@ export default class WallpaperEngineExtension extends Extension {
 
             const runtime = `${GLib.get_user_runtime_dir()}/`;
             const socketName = socket.startsWith(runtime) ? socket.slice(runtime.length) : '';
-            if (!/^(app\/[^/]+\/)?lwe-gnome-\d+\.sock$/.test(socketName))
+            if (!/^(app\/[^/]+\/)?lwe-gnome-(\d+_)?\d+\.sock$/.test(socketName))
                 throw new Error(`refusing a helper for ${socket}`);
 
             const helper = GLib.build_filenamev([this.path, HELPER]);

+ 1 - 1
gnome-shell-extension/linux-wallpaperengine@wallpaperenginelover.github.io/metadata.json

@@ -5,5 +5,5 @@
   "url": "https://github.com/WallpaperEngineLover/linux-wallpaperengine-kde",
   "session-modes": ["user", "unlock-dialog"],
   "shell-version": ["45", "46", "47", "48", "49", "50"],
-  "version-name": "1"
+  "version-name": "2"
 }

+ 1 - 0
nix/package.nix

@@ -168,6 +168,7 @@ stdenv.mkDerivation {
     mkdir -p $out/opt $out/bin
     tar -xzf "$TMPDIR/dist/linux-wallpaperengine-kde.tar.gz" -C $out/opt
     ln -s $out/opt/linux-wallpaperengine-kde/linux-wallpaperengine $out/bin/linux-wallpaperengine
+    cp -r $out/opt/linux-wallpaperengine-kde/share $out/share
     runHook postInstall
   '';
 

+ 2 - 0
packaging/aur/linux-wallpaperengine-kde-bin/PKGBUILD

@@ -27,4 +27,6 @@ package() {
 
     install -d "$pkgdir/usr/bin"
     ln -s "/opt/$_pkgname/linux-wallpaperengine" "$pkgdir/usr/bin/linux-wallpaperengine"
+    install -d "$pkgdir/usr/share"
+    cp -a "$pkgdir/opt/$_pkgname/share/icons" "$pkgdir/opt/$_pkgname/share/applications" "$pkgdir/usr/share/"
 }

+ 2 - 0
packaging/aur/linux-wallpaperengine-kde-git/PKGBUILD

@@ -53,5 +53,7 @@ package() {
 
     install -d "$pkgdir/usr/bin"
     ln -s "/opt/$_pkgname/linux-wallpaperengine" "$pkgdir/usr/bin/linux-wallpaperengine"
+    install -d "$pkgdir/usr/share"
+    cp -a "$pkgdir/opt/$_pkgname/share/icons" "$pkgdir/opt/$_pkgname/share/applications" "$pkgdir/usr/share/"
     install -Dm644 "$_pkgname/LICENSE" "$pkgdir/usr/share/licenses/$pkgname/LICENSE"
 }

+ 102 - 0
protocols/fractional-scale-v1.xml

@@ -0,0 +1,102 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<protocol name="fractional_scale_v1">
+  <copyright>
+    Copyright © 2022 Kenny Levinsen
+
+    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>
+
+  <description summary="Protocol for requesting fractional surface scales">
+    This protocol allows a compositor to suggest for surfaces to render at
+    fractional scales.
+
+    A client can submit scaled content by utilizing wp_viewport. This is done by
+    creating a wp_viewport object for the surface and setting the destination
+    rectangle to the surface size before the scale factor is applied.
+
+    The buffer size is calculated by multiplying the surface size by the
+    intended scale.
+
+    The wl_surface buffer scale should remain set to 1.
+
+    If a surface has a surface-local size of 100 px by 50 px and wishes to
+    submit buffers with a scale of 1.5, then a buffer of 150px by 75 px should
+    be used and the wp_viewport destination rectangle should be 100 px by 50 px.
+
+    For toplevel surfaces, the size is rounded halfway away from zero. The
+    rounding algorithm for subsurface position and size is not defined.
+  </description>
+
+  <interface name="wp_fractional_scale_manager_v1" version="1">
+    <description summary="fractional surface scale information">
+      A global interface for requesting surfaces to use fractional scales.
+    </description>
+
+    <request name="destroy" type="destructor">
+      <description summary="unbind the fractional surface scale interface">
+        Informs the server that the client will not be using this protocol
+        object anymore. This does not affect any other objects,
+        wp_fractional_scale_v1 objects included.
+      </description>
+    </request>
+
+    <enum name="error">
+      <entry name="fractional_scale_exists" value="0"
+        summary="the surface already has a fractional_scale object associated"/>
+    </enum>
+
+    <request name="get_fractional_scale">
+      <description summary="extend surface interface for scale information">
+        Create an add-on object for the the wl_surface to let the compositor
+        request fractional scales. If the given wl_surface already has a
+        wp_fractional_scale_v1 object associated, the fractional_scale_exists
+        protocol error is raised.
+      </description>
+      <arg name="id" type="new_id" interface="wp_fractional_scale_v1"
+           summary="the new surface scale info interface id"/>
+      <arg name="surface" type="object" interface="wl_surface"
+           summary="the surface"/>
+    </request>
+  </interface>
+
+  <interface name="wp_fractional_scale_v1" version="1">
+    <description summary="fractional scale interface to a wl_surface">
+      An additional interface to a wl_surface object which allows the compositor
+      to inform the client of the preferred scale.
+    </description>
+
+    <request name="destroy" type="destructor">
+      <description summary="remove surface scale information for surface">
+        Destroy the fractional scale object. When this object is destroyed,
+        preferred_scale events will no longer be sent.
+      </description>
+    </request>
+
+    <event name="preferred_scale">
+      <description summary="notify of new preferred scale">
+        Notification of a new preferred scale for this surface that the
+        compositor suggests that the client should use.
+
+        The sent scale is the numerator of a fraction with a denominator of 120.
+      </description>
+      <arg name="scale" type="uint" summary="the new preferred scale"/>
+    </event>
+  </interface>
+</protocol>

BIN
resources/icons/hicolor/128x128/apps/linux-wallpaperengine.png


BIN
resources/icons/hicolor/16x16/apps/linux-wallpaperengine.png


BIN
resources/icons/hicolor/22x22/apps/linux-wallpaperengine.png


BIN
resources/icons/hicolor/24x24/apps/linux-wallpaperengine.png


BIN
resources/icons/hicolor/256x256/apps/linux-wallpaperengine.png


BIN
resources/icons/hicolor/32x32/apps/linux-wallpaperengine.png


BIN
resources/icons/hicolor/48x48/apps/linux-wallpaperengine.png


BIN
resources/icons/hicolor/512x512/apps/linux-wallpaperengine.png


BIN
resources/icons/hicolor/64x64/apps/linux-wallpaperengine.png


BIN
resources/icons/icon-source.png


BIN
resources/icons/linux-wallpaperengine.png


+ 9 - 0
resources/linux-wallpaperengine.desktop

@@ -0,0 +1,9 @@
+[Desktop Entry]
+Type=Application
+Name=linux-wallpaperengine
+Comment=Wallpaper Engine live wallpapers on Linux
+Exec=linux-wallpaperengine
+Icon=linux-wallpaperengine
+Terminal=false
+NoDisplay=true
+Categories=Utility;

+ 40 - 0
src/WallpaperEngine/Application/ApplicationContext.cpp

@@ -331,6 +331,22 @@ std::optional<float> ApplicationContext::resolveAudioSensitivity (int id, const
     return wildcard;
 }
 
+std::optional<ApplicationContext::HRTF_MODE> ApplicationContext::parseHrtfMode (const std::string& value) {
+    if (value == "auto") {
+	return HRTF_AUTO;
+    }
+
+    if (value == "on") {
+	return HRTF_ON;
+    }
+
+    if (value == "off") {
+	return HRTF_OFF;
+    }
+
+    return std::nullopt;
+}
+
 std::optional<float> ApplicationContext::resolveSoundVolume (int id, const std::string& name) const {
     // "*" is a wildcard default, checked last so a specific id/name match always wins (same rule as
     // resolveAudioSensitivity).
@@ -945,6 +961,14 @@ void ApplicationContext::loadSettingsFromArgv () {
 	.flag ()
 	.action ([this] (const std::string& value) -> void { this->settings.render.pauseOnFocus = true; });
 
+    performanceGroup.add_argument ("--pause-on-maximized")
+	.help (
+	    "wlroots compositors: also pause the outputs a maximized window is on (KDE and GNOME always do, like "
+	    "Wallpaper Engine)"
+	)
+	.flag ()
+	.action ([this] (const std::string& value) -> void { this->settings.render.pauseOnMaximized = true; });
+
     performanceGroup.add_argument ("--fullscreen-pause-ignore-appid")
 	.help ("Wayland only: ignore fullscreen windows whose app_id contains this value (repeatable)")
 	.action ([this] (const std::string& value) -> void {
@@ -1007,6 +1031,22 @@ void ApplicationContext::loadSettingsFromArgv () {
 	    }
 	});
 
+    audioGroup.add_argument ("--hrtf")
+	.help (
+	    "Headphones (HRTF) rendering of scene sound objects, like Wallpaper Engine's OpenAL: auto (default) "
+	    "uses it while the default output is headphones or a headset, on and off force it. Control file: "
+	    "hrtf=<mode>"
+	)
+	.action ([this] (const std::string& value) -> void {
+	    const auto mode = parseHrtfMode (value);
+
+	    if (!mode.has_value ()) {
+		sLog.exception ("Invalid --hrtf value: ", value);
+	    }
+
+	    this->settings.audio.hrtf = *mode;
+	});
+
     auto& screenshotGroup = program.add_group ("Screenshot options");
 
     screenshotGroup.add_argument ("--screenshot")

+ 16 - 0
src/WallpaperEngine/Application/ApplicationContext.h

@@ -76,6 +76,17 @@ public:
 	WAYLAND_LAYER_OVERLAY = 3,
     };
 
+    /** Headphones rendering of sound objects, OpenAL Soft's "hrtf" setting */
+    enum HRTF_MODE {
+	/** like WE: on when the default output is headphones */
+	HRTF_AUTO = 0,
+	HRTF_ON = 1,
+	HRTF_OFF = 2,
+    };
+
+    /** auto, on or off, nullopt for anything else */
+    [[nodiscard]] static std::optional<HRTF_MODE> parseHrtfMode (const std::string& value);
+
     struct PlaylistSettings {
 	uint32_t delayMinutes = 60;
 	std::string mode = "timer";
@@ -199,6 +210,8 @@ public:
 	    bool pauseOnFullscreenOnlyWhenActive;
 	    /** WE's "Other application focused: Pause" (--pause-on-focus) */
 	    bool pauseOnFocus;
+	    /** wlroots: maximized toplevels pause their outputs too (KDE and GNOME always do, like WE) */
+	    bool pauseOnMaximized;
 	    /**
 	     * Wayland-only: list of app_id substrings to ignore for fullscreen pause.
 	     * Example: "firefox" will match "org.mozilla.firefox".
@@ -250,6 +263,7 @@ public:
 	    std::optional<std::string> audioScreen;
 	    /** 0-128, applied to non-video (scene sound + web) backgrounds instead of volume; nullopt = use volume */
 	    std::optional<int> ambientVolume;
+	    HRTF_MODE hrtf;
 	} audio;
 
 	struct {
@@ -311,6 +325,7 @@ public:
             .pauseOnFullscreen = true,
             .pauseOnFullscreenOnlyWhenActive = false,
             .pauseOnFocus = false,
+            .pauseOnMaximized = false,
             .fullscreenPauseIgnoreAppIds = {},
             .hdr = false,
             .debug = {
@@ -344,6 +359,7 @@ public:
             .audioprocessing = true,
             .audioScreen = std::nullopt,
             .ambientVolume = std::nullopt,
+            .hrtf = HRTF_AUTO,
         },
         .mouse = {
             .enabled = true,

+ 94 - 128
src/WallpaperEngine/Application/WallpaperApplication.cpp

@@ -587,30 +587,8 @@ void WallpaperApplication::advancePlaylist (
 	this->m_backgrounds[screen] = std::move (project);
 
 	try {
-	    const auto scalingIt = this->m_context.settings.general.screenScalings.find (screen);
-	    const auto clampIt = this->m_context.settings.general.screenClamps.find (screen);
-	    const auto scaling = scalingIt != this->m_context.settings.general.screenScalings.end ()
-		? scalingIt->second
-		: this->m_context.settings.render.window.scalingMode;
-	    const auto clamp = clampIt != this->m_context.settings.general.screenClamps.end ()
-		? clampIt->second
-		: this->m_context.settings.render.window.clamp;
-
 	    if (this->m_renderContext) {
-		auto wallpaper = WallpaperEngine::Render::CWallpaper::fromWallpaper (
-		    *this->m_backgrounds[screen]->wallpaper, *this->m_renderContext, *this->m_audioContext, nextPath,
-		    scaling, clamp, this->resolveScreenRenderSize (screen)
-		);
-		wallpaper->setStorageScreen (this->storageScreen (screen));
-		wallpaper->setZoom (this->resolveScreenZoom (screen));
-		const auto offset = this->resolveScreenOffset (screen);
-		wallpaper->setOffset (offset.x, offset.y);
-		wallpaper->setAlignment (this->resolveScreenAlignment (screen));
-		wallpaper->setCornerColor (this->resolveScreenCornerColor (screen));
-		wallpaper->setImageAdjustments (
-		    this->resolveScreenImageAdjustments (screen, *this->m_backgrounds[screen])
-		);
-		this->m_renderContext->setWallpaper (screen, std::move (wallpaper), true);
+		this->installWallpaper (screen, *this->m_backgrounds[screen], nextPath, true);
 		this->applyAudioPolicy ();
 	    }
 	} catch (...) {
@@ -714,6 +692,8 @@ struct HotswapRequest {
     std::optional<std::string> videoSegments;
     /** mpv hwdec value, see --hwdec */
     std::optional<std::string> hwdec;
+    /** auto/on/off, see --hrtf */
+    std::optional<std::string> hrtf;
     /** position to jump video wallpapers to, same format */
     std::optional<std::string> videoSeek;
     /** screen name to restrict audio to, or "" to clear the restriction, see --audio-screen */
@@ -872,6 +852,8 @@ HotswapRequest parseHotswapRequest (std::istream& file) {
 	    request.videoSeek = value;
 	} else if (key == "hwdec") {
 	    request.hwdec = value;
+	} else if (key == "hrtf") {
+	    request.hrtf = value;
 	} else if (key == "audio-screen") {
 	    request.audioScreen = value;
 	} else if (key == "ambient-volume") {
@@ -939,7 +921,7 @@ void WallpaperApplication::checkHotswapRequest () {
 	&& !request.videoEnd.has_value () && !request.videoSegments.has_value () && !request.videoSeek.has_value ()
 	&& !request.audioScreen.has_value () && !request.ambientVolume.has_value () && !request.propertiesProvided
 	&& !request.audioSensitivityProvided && !request.soundVolumeProvided && !request.effectsProvided
-	&& !request.disableAnimations.has_value () && !request.hwdec.has_value ()) {
+	&& !request.disableAnimations.has_value () && !request.hwdec.has_value () && !request.hrtf.has_value ()) {
 	sLog.error ("Hotswap requested but control file was empty");
 	return;
     }
@@ -1024,6 +1006,15 @@ void WallpaperApplication::checkHotswapRequest () {
 	this->applyHwdecHotswap (*request.hwdec);
     }
 
+    if (request.hrtf.has_value ()) {
+	// the audio driver picks the mode up on its next update
+	if (const auto mode = ApplicationContext::parseHrtfMode (*request.hrtf); mode.has_value ()) {
+	    this->m_context.settings.audio.hrtf = *mode;
+	} else {
+	    sLog.error ("Hotswap: ignoring invalid hrtf value: ", *request.hrtf);
+	}
+    }
+
     if (request.audioScreen.has_value ()) {
 	this->applyAudioScreenHotswap (*request.audioScreen);
     }
@@ -1155,28 +1146,8 @@ void WallpaperApplication::checkHotswapRequest () {
 	    background = std::move (project);
 
 	    try {
-		const auto scalingIt = this->m_context.settings.general.screenScalings.find (screen);
-		const auto clampIt = this->m_context.settings.general.screenClamps.find (screen);
-		const auto scaling = scalingIt != this->m_context.settings.general.screenScalings.end ()
-		    ? scalingIt->second
-		    : this->m_context.settings.render.window.scalingMode;
-		const auto clamp = clampIt != this->m_context.settings.general.screenClamps.end ()
-		    ? clampIt->second
-		    : this->m_context.settings.render.window.clamp;
-
 		if (this->m_renderContext) {
-		    auto wallpaper = WallpaperEngine::Render::CWallpaper::fromWallpaper (
-			*background->wallpaper, *this->m_renderContext, *this->m_audioContext, targetPath, scaling,
-			clamp, this->resolveScreenRenderSize (screen)
-		    );
-		    wallpaper->setStorageScreen (this->storageScreen (screen));
-		    wallpaper->setZoom (this->resolveScreenZoom (screen));
-		    const auto offset = this->resolveScreenOffset (screen);
-		    wallpaper->setOffset (offset.x, offset.y);
-		    wallpaper->setAlignment (this->resolveScreenAlignment (screen));
-		    wallpaper->setCornerColor (this->resolveScreenCornerColor (screen));
-		    wallpaper->setImageAdjustments (this->resolveScreenImageAdjustments (screen, *background));
-		    this->m_renderContext->setWallpaper (screen, std::move (wallpaper), true);
+		    this->installWallpaper (screen, *background, targetPath, true);
 		}
 	    } catch (...) {
 		project = std::move (background);
@@ -2487,106 +2458,101 @@ void WallpaperApplication::ensureAudioCapture (const Project& project) {
     this->m_audioCapturing = true;
 }
 
-void WallpaperApplication::prepareOutputs () {
-    m_renderContext
-	= std::make_unique<WallpaperEngine::Render::RenderContext> (*m_videoDriver, *this, *this->m_mediaSource);
+const ApplicationContext::SpanGroup* WallpaperApplication::findSpanGroup (const std::string& screen) const {
+    if (!screen.starts_with ("span:")) {
+	return nullptr;
+    }
 
-    // set all the specific wallpapers required (skip span group synthetic keys)
-    for (const auto& [background, info] : this->m_backgrounds) {
-	if (background.rfind ("span:", 0) == 0) {
-	    continue;
+    for (const auto& spanGroup : this->m_context.settings.general.spanGroups) {
+	if (!spanGroup.screens.empty () && "span:" + spanGroup.screens.front () == screen) {
+	    return &spanGroup;
 	}
-	const auto scalingIt = this->m_context.settings.general.screenScalings.find (background);
-	const auto clampIt = this->m_context.settings.general.screenClamps.find (background);
-	const auto scaling = scalingIt != this->m_context.settings.general.screenScalings.end ()
-	    ? scalingIt->second
-	    : this->m_context.settings.render.window.scalingMode;
-	const auto clamp = clampIt != this->m_context.settings.general.screenClamps.end ()
-	    ? clampIt->second
-	    : this->m_context.settings.render.window.clamp;
+    }
+
+    return nullptr;
+}
+
+void WallpaperApplication::installWallpaper (
+    const std::string& screen, const Project& project, const std::filesystem::path& path, const bool holdPrevious
+) {
+    const auto& general = this->m_context.settings.general;
+    const auto& window = this->m_context.settings.render.window;
+    const auto* spanGroup = this->findSpanGroup (screen);
+
+    if (spanGroup == nullptr) {
+	const auto scalingIt = general.screenScalings.find (screen);
+	const auto clampIt = general.screenClamps.find (screen);
 
 	auto wallpaper = WallpaperEngine::Render::CWallpaper::fromWallpaper (
-	    *info->wallpaper, *m_renderContext, *m_audioContext, this->resolveScreenBackgroundPath (background),
-	    scaling, clamp, this->resolveScreenRenderSize (background)
+	    *project.wallpaper, *this->m_renderContext, *this->m_audioContext, path,
+	    scalingIt != general.screenScalings.end () ? scalingIt->second : window.scalingMode,
+	    clampIt != general.screenClamps.end () ? clampIt->second : window.clamp,
+	    this->resolveScreenRenderSize (screen)
 	);
-	wallpaper->setStorageScreen (this->storageScreen (background));
-	wallpaper->setZoom (this->resolveScreenZoom (background));
-	const auto offset = this->resolveScreenOffset (background);
+	wallpaper->setStorageScreen (this->storageScreen (screen));
+	wallpaper->setZoom (this->resolveScreenZoom (screen));
+	const auto offset = this->resolveScreenOffset (screen);
 	wallpaper->setOffset (offset.x, offset.y);
-	wallpaper->setAlignment (this->resolveScreenAlignment (background));
-	wallpaper->setCornerColor (this->resolveScreenCornerColor (background));
-	wallpaper->setImageAdjustments (this->resolveScreenImageAdjustments (background, *info));
-	m_renderContext->setWallpaper (background, std::move (wallpaper));
+	wallpaper->setAlignment (this->resolveScreenAlignment (screen));
+	wallpaper->setCornerColor (this->resolveScreenCornerColor (screen));
+	wallpaper->setImageAdjustments (this->resolveScreenImageAdjustments (screen, project));
+	this->m_renderContext->setWallpaper (screen, std::move (wallpaper), holdPrevious);
+	return;
     }
 
-    // Set up span groups: one shared wallpaper per group, registered for each viewport
-    for (const auto& spanGroup : this->m_context.settings.general.spanGroups) {
-	if (spanGroup.screens.empty ()) {
-	    continue;
-	}
+    // the bounding box of the group's outputs, CWallpaper follows their layout from then on
+    const auto& viewports = this->m_renderContext->getOutput ().getViewports ();
+    glm::ivec2 low (INT_MAX);
+    glm::ivec2 high (INT_MIN);
 
-	const std::string groupKey = "span:" + spanGroup.screens.front ();
-	const auto bgIt = this->m_backgrounds.find (groupKey);
-	if (bgIt == this->m_backgrounds.end ()) {
+    for (const auto& name : spanGroup->screens) {
+	const auto it = viewports.find (name);
+
+	if (it == viewports.end ()) {
+	    sLog.error ("Span group screen not found: ", name);
 	    continue;
 	}
 
-	// bounding box of all viewports in this span group
-	const auto& viewports = m_renderContext->getOutput ().getViewports ();
-	int minX = INT_MAX, minY = INT_MAX, maxX = INT_MIN, maxY = INT_MIN;
-	bool anyFound = false;
-
-	for (const auto& screenName : spanGroup.screens) {
-	    const auto vpIt = viewports.find (screenName);
-	    if (vpIt == viewports.end ()) {
-		sLog.error ("Span group screen not found: ", screenName);
-		continue;
-	    }
-	    anyFound = true;
-	    const auto& vp = vpIt->second;
-	    const int x = vp->globalPosition.x;
-	    const int y = vp->globalPosition.y;
-	    const int w = vp->logicalSize.x;
-	    const int h = vp->logicalSize.y;
-	    sLog.debug (
-		"SPAN DEBUG prepareOutputs: screen '", screenName, "' globalPos=(", x, ",", y, ") logicalSize=", w, "x",
-		h
-	    );
-	    minX = std::min (minX, x);
-	    minY = std::min (minY, y);
-	    maxX = std::max (maxX, x + w);
-	    maxY = std::max (maxY, y + h);
-	}
+	low = glm::min (low, it->second->globalPosition);
+	high = glm::max (high, it->second->globalPosition + it->second->logicalSize);
+    }
 
-	if (!anyFound) {
-	    sLog.error ("No viewports found for span group, skipping");
-	    continue;
-	}
+    if (high.x <= low.x || high.y <= low.y) {
+	throw std::runtime_error ("none of the span group's screens is there");
+    }
 
-	sLog.debug (
-	    "SPAN DEBUG prepareOutputs: bounding box=(", minX, ",", minY, ",", maxX - minX, ",", maxY - minY, ")"
+    std::shared_ptr<WallpaperEngine::Render::CWallpaper> wallpaper
+	= WallpaperEngine::Render::CWallpaper::fromWallpaper (
+	    *project.wallpaper, *this->m_renderContext, *this->m_audioContext, path, spanGroup->scaling,
+	    spanGroup->clamp, high - low
 	);
+    wallpaper->setStorageScreen (this->storageScreen (screen));
+    wallpaper->setZoom (spanGroup->zoom);
+    wallpaper->setOffset (spanGroup->offset.x, spanGroup->offset.y);
+    wallpaper->setAlignment (spanGroup->alignment);
+    wallpaper->setCornerColor (spanGroup->cornerColor);
+    wallpaper->setImageAdjustments (this->resolveScreenImageAdjustments (screen, project));
+    wallpaper->setSpanInfo ({ .screens = spanGroup->screens, .totalBounds = { low, high - low } });
 
-	WallpaperEngine::Render::CWallpaper::SpanInfo spanInfo;
-	spanInfo.totalBounds = { minX, minY, maxX - minX, maxY - minY };
+    for (const auto& name : spanGroup->screens) {
+	this->m_renderContext->setWallpaper (name, wallpaper, holdPrevious);
+    }
+}
 
-	auto sharedWallpaper = WallpaperEngine::Render::CWallpaper::fromWallpaper (
-	    *bgIt->second->wallpaper, *m_renderContext, *m_audioContext, this->resolveScreenBackgroundPath (groupKey),
-	    spanGroup.scaling, spanGroup.clamp, glm::ivec2 { maxX - minX, maxY - minY }
-	);
-	sharedWallpaper->setStorageScreen (this->storageScreen (groupKey));
-	sharedWallpaper->setZoom (spanGroup.zoom);
-	sharedWallpaper->setOffset (spanGroup.offset.x, spanGroup.offset.y);
-	sharedWallpaper->setAlignment (spanGroup.alignment);
-	sharedWallpaper->setCornerColor (spanGroup.cornerColor);
-	sharedWallpaper->setImageAdjustments (this->resolveScreenImageAdjustments (groupKey, *bgIt->second));
-
-	// Convert to shared_ptr so it can be registered for multiple viewports
-	std::shared_ptr<WallpaperEngine::Render::CWallpaper> shared (std::move (sharedWallpaper));
-	shared->setSpanInfo (spanInfo);
-
-	for (const auto& screenName : spanGroup.screens) {
-	    m_renderContext->setWallpaper (screenName, shared);
+void WallpaperApplication::prepareOutputs () {
+    m_renderContext
+	= std::make_unique<WallpaperEngine::Render::RenderContext> (*m_videoDriver, *this, *this->m_mediaSource);
+
+    for (const auto& [background, info] : this->m_backgrounds) {
+	if (this->findSpanGroup (background) == nullptr) {
+	    this->installWallpaper (background, *info, this->resolveScreenBackgroundPath (background), false);
+	    continue;
+	}
+
+	try {
+	    this->installWallpaper (background, *info, this->resolveScreenBackgroundPath (background), false);
+	} catch (const std::runtime_error& e) {
+	    sLog.error ("Skipping span group ", background, ": ", e.what ());
 	}
     }
 

+ 9 - 0
src/WallpaperEngine/Application/WallpaperApplication.h

@@ -231,6 +231,15 @@ private:
     // The resolution a Web wallpaper on this screen will actually be rendered at - falls back to
     // the combined bounding box of every active screen if this one isn't registered yet.
     [[nodiscard]] glm::ivec2 resolveScreenRenderSize (const std::string& screen) const;
+    /** The span group loaded as this "span:<first screen>" key, null for a plain screen */
+    [[nodiscard]] const ApplicationContext::SpanGroup* findSpanGroup (const std::string& screen) const;
+    /**
+     * Builds the wallpaper for a screen or span group key and puts it on its outputs, a span group's one wallpaper
+     * on every screen of the group. Throws when the wallpaper can't be built, the outputs keep what they had
+     */
+    void installWallpaper (
+	const std::string& screen, const Project& project, const std::filesystem::path& path, bool holdPrevious
+    );
 
     ApplicationContext& m_context;
     std::map<std::string, ProjectUniquePtr> m_backgrounds {};

+ 11 - 0
src/WallpaperEngine/Audio/AudioContext.cpp

@@ -1,4 +1,5 @@
 #include "AudioContext.h"
+#include "WallpaperEngine/Audio/AudioStream.h"
 #include "WallpaperEngine/Audio/Drivers/AudioDriver.h"
 
 namespace WallpaperEngine::Audio {
@@ -21,6 +22,16 @@ void AudioContext::setStreamPaused (int streamId, bool paused) const {
     this->m_driver.setStreamPaused (streamId, paused);
 }
 
+void AudioContext::stopStream (int streamId, std::unique_ptr<AudioStream> stream) const {
+    this->m_driver.stopStream (streamId, std::move (stream));
+}
+
+void AudioContext::setStreamHrtf (int streamId, const Drivers::StreamHrtf* hrtf) const {
+    this->m_driver.setStreamHrtf (streamId, hrtf);
+}
+
+const Hrtf::Store* AudioContext::getHrtf () const { return this->m_driver.getHrtf (); }
+
 AVSampleFormat AudioContext::getFormat () const { return this->m_driver.getFormat (); }
 
 int AudioContext::getSampleRate () const { return this->m_driver.getSampleRate (); }

+ 9 - 0
src/WallpaperEngine/Audio/AudioContext.h

@@ -1,10 +1,13 @@
 #pragma once
 
+#include <memory>
+
 #include <libavutil/samplefmt.h>
 #include <vector>
 
 #include "WallpaperEngine/Application/ApplicationContext.h"
 #include "WallpaperEngine/Audio/Drivers/Recorders/PulseAudioPlaybackRecorder.h"
+#include "WallpaperEngine/Audio/Hrtf.h"
 
 namespace WallpaperEngine {
 namespace Application {
@@ -14,6 +17,7 @@ namespace Application {
 namespace Audio {
     namespace Drivers {
 	class AudioDriver;
+	struct StreamHrtf;
 
 	namespace Recorders {
 	    class PulseAudioPlaybackRecorder;
@@ -44,6 +48,11 @@ namespace Audio {
 	void setStreamGains (int streamId, float left, float right) const;
 
 	void setStreamPaused (int streamId, bool paused) const;
+	/** Stops the stream like OpenAL's alSourceStop (one more silent update, see AudioDriver) and frees it */
+	void stopStream (int streamId, std::unique_ptr<AudioStream> stream) const;
+	void setStreamHrtf (int streamId, const Drivers::StreamHrtf* hrtf) const;
+	/** The HRTF data set while sound objects render for headphones, nullptr otherwise */
+	[[nodiscard]] const Hrtf::Store* getHrtf () const;
 
 	/**
 	 * TODO: MAYBE THIS SHOULD BE OUR OWN DEFINITIONS INSTEAD OF LIBRARY SPECIFIC ONES?

+ 221 - 154
src/WallpaperEngine/Audio/AudioStream.cpp

@@ -1,11 +1,21 @@
 #include "AudioStream.h"
 #include "WallpaperEngine/Logging/Log.h"
+#include <algorithm>
 #include <cassert>
 #include <cmath>
 #include <iostream>
 
 using namespace WallpaperEngine::Audio;
 
+namespace {
+/** OpenAL Soft 1.21.1 core/mixer/defs.h and alu.cpp */
+constexpr uint32_t MixerFracBits = 12;
+constexpr uint32_t MixerFracOne = 1 << MixerFracBits;
+constexpr uint32_t MixerFracMask = MixerFracOne - 1;
+constexpr uint32_t MaxPitch = 10;
+constexpr size_t MaxResamplerPadding = 48;
+} // namespace
+
 int audio_read_thread (void* arg) {
     SDL_mutex* waitMutex = SDL_CreateMutex ();
     auto* stream = static_cast<AudioStream*> (arg);
@@ -224,47 +234,22 @@ void AudioStream::initialize () {
 #endif
 
 #if FF_API_OLD_CHANNEL_LAYOUT
-    int64_t out_channel_layout;
-
-    switch (this->m_audioContext.getChannels ()) {
-	case 1:
-	    out_channel_layout = AV_CH_LAYOUT_MONO;
-	    break;
-	case 2:
-	    out_channel_layout = AV_CH_LAYOUT_STEREO;
-	    break;
-	default:
-	    out_channel_layout = AV_CH_LAYOUT_SURROUND;
-	    break;
-    }
+    // the mixer reads frames of the device's width, so swr has to write that many channels
+    const int64_t out_channel_layout = av_get_default_channel_layout (this->m_audioContext.getChannels ());
 
     this->m_swrctx = swr_alloc_set_opts (
-	nullptr, out_channel_layout, this->m_audioContext.getFormat (), this->m_audioContext.getSampleRate (),
+	nullptr, out_channel_layout, AV_SAMPLE_FMT_FLT, this->getContext ()->sample_rate,
 	this->getContext ()->channel_layout, this->getContext ()->sample_fmt, this->getContext ()->sample_rate, 0,
 	nullptr
     );
 #else
+    // the mixer reads frames of the device's width, so swr has to write that many channels
     AVChannelLayout out_channel_layout;
-    int64_t out_channel_mask;
-
-    switch (this->m_audioContext.getChannels ()) {
-	case 1:
-	    out_channel_mask = AV_CH_LAYOUT_MONO;
-	    break;
-	case 2:
-	    out_channel_mask = AV_CH_LAYOUT_STEREO;
-	    break;
-	default:
-	    out_channel_mask = AV_CH_LAYOUT_SURROUND;
-	    break;
-    }
-
-    if (av_channel_layout_from_mask (&out_channel_layout, out_channel_mask) != 0) {
-	sLog.exception ("Cannot get channel layout from mask");
-    }
+    av_channel_layout_default (&out_channel_layout, this->m_audioContext.getChannels ());
 
+    // only the sample format and the layout change here, the rate is converted in read () like OpenAL does
     swr_alloc_set_opts2 (
-	&this->m_swrctx, &out_channel_layout, this->m_audioContext.getFormat (), this->m_audioContext.getSampleRate (),
+	&this->m_swrctx, &out_channel_layout, AV_SAMPLE_FMT_FLT, this->m_context->sample_rate,
 	&this->m_context->ch_layout, this->m_context->sample_fmt, this->m_context->sample_rate, 0, nullptr
     );
 #endif
@@ -284,6 +269,19 @@ void AudioStream::initialize () {
 	sLog.exception ("Failed to initialize the resampling context.");
     }
 
+    this->m_channels = this->m_audioContext.getChannels ();
+
+    // CalcNonAttnSourceParams/CalcAttnSourceParams: pitch 1 times buffer rate / device rate, rounded to the 12 bit
+    // fixed point step (fastf2u is cvtss2si in the DLL, sub_180190400 and sub_1801920C0), at most 10x
+    const float pitch = static_cast<float> (this->m_context->sample_rate)
+	/ static_cast<float> (this->m_audioContext.getSampleRate ());
+
+    if (pitch > static_cast<float> (MaxPitch)) {
+	this->m_step = MaxPitch << MixerFracBits;
+    } else {
+	this->m_step = std::max<uint32_t> (static_cast<uint32_t> (std::lrint (pitch * MixerFracOne)), 1);
+    }
+
     this->m_queue->mutex = SDL_CreateMutex ();
     this->m_queue->wait = SDL_CreateCond ();
 
@@ -465,153 +463,55 @@ void AudioStream::stop () {
     this->m_initialized = false;
 }
 
-int AudioStream::resampleAudio (uint8_t* out_buf, const int out_size) {
-    int out_linesize = 0;
-    int ret;
-    int out_nb_channels;
-    int out_nb_samples;
-    uint8_t** resampled_data = nullptr;
-    int resampled_data_size;
-
-    const int in_nb_samples = this->m_decodeFrame->nb_samples;
-    if (in_nb_samples <= 0) {
-	sLog.error ("in_nb_samples error.");
-	return -1;
-    }
-
-    int max_out_nb_samples = out_nb_samples = av_rescale_rnd (
-	in_nb_samples, this->m_audioContext.getSampleRate (), this->getContext ()->sample_rate, AV_ROUND_UP
-    );
-
-    if (max_out_nb_samples <= 0) {
-	sLog.error ("av_rescale_rnd error.");
-	return -1;
-    }
-
-#if FF_API_OLD_CHANNEL_LAYOUT
-    int64_t out_channel_layout;
-
-    switch (this->m_audioContext.getChannels ()) {
-	case 1:
-	    out_channel_layout = AV_CH_LAYOUT_MONO;
-	    break;
-	case 2:
-	    out_channel_layout = AV_CH_LAYOUT_STEREO;
-	    break;
-	default:
-	    out_channel_layout = AV_CH_LAYOUT_SURROUND;
-	    break;
-    }
+bool AudioStream::convertFrame () {
+    const int samples = this->m_decodeFrame->nb_samples;
 
-    out_nb_channels = av_get_channel_layout_nb_channels (out_channel_layout);
-#else
-    // Must be the channel count swr_convert() below will actually write, not the input file's
-    // channel count - a mono sound resampled to a stereo driver output would otherwise get a
-    // buffer sized for one channel while swr_convert() writes two, overflowing it.
-    out_nb_channels = this->m_audioContext.getChannels ();
-#endif
-    ret = av_samples_alloc_array_and_samples (
-	&resampled_data, &out_linesize, out_nb_channels, out_nb_samples, this->m_audioContext.getFormat (), 0
-    );
-
-    if (ret < 0) {
-	sLog.error ("av_samples_alloc_array_and_samples() error: Could not allocate destination samples.");
-	return -1;
-    }
-
-    // account for the progressive resampling delay
-    out_nb_samples = av_rescale_rnd (
-	swr_get_delay (this->m_swrctx, this->getContext ()->sample_rate) + in_nb_samples,
-	this->m_audioContext.getSampleRate (), this->getContext ()->sample_rate, AV_ROUND_UP
-    );
-
-    if (out_nb_samples <= 0) {
-	sLog.error ("av_rescale_rnd error");
-	return -1;
+    if (samples <= 0) {
+	return false;
     }
 
-    if (out_nb_samples > max_out_nb_samples) {
-	av_freep (&resampled_data[0]);
-
-	ret = av_samples_alloc (
-	    resampled_data, &out_linesize, out_nb_channels, out_nb_samples, this->m_audioContext.getFormat (), 1
-	);
+    const size_t offset = this->m_source.size ();
 
-	if (ret < 0) {
-	    sLog.error ("av_samples_alloc failed.");
-	    return -1;
-	}
+    this->m_source.resize (offset + static_cast<size_t> (samples) * this->m_channels);
 
-	max_out_nb_samples = out_nb_samples;
-    }
+    auto* out = reinterpret_cast<uint8_t*> (this->m_source.data () + offset);
+    const int converted
+	= swr_convert (this->m_swrctx, &out, samples, const_cast<const uint8_t**> (this->m_decodeFrame->data), samples);
 
-    ret = swr_convert (
-	this->m_swrctx, resampled_data, max_out_nb_samples, const_cast<const uint8_t**> (this->m_decodeFrame->data),
-	this->m_decodeFrame->nb_samples
-    );
+    this->m_source.resize (offset + static_cast<size_t> (std::max (converted, 0)) * this->m_channels);
 
-    if (ret < 0) {
+    if (converted < 0) {
 	sLog.error ("swr_convert_error.");
-	return -1;
     }
 
-    resampled_data_size
-	= av_samples_get_buffer_size (&out_linesize, out_nb_channels, ret, this->m_audioContext.getFormat (), 1);
-
-    if (resampled_data_size < 0) {
-	sLog.error ("av_samples_get_buffer_size error.");
-	return -1;
-    }
-
-    memcpy (out_buf, resampled_data[0], std::min (resampled_data_size, out_size));
-
-    if (resampled_data) {
-	av_freep (&resampled_data[0]);
-    }
-
-    av_freep (&resampled_data);
-
-    return resampled_data_size;
+    return converted > 0;
 }
 
-int AudioStream::flushResampler (uint8_t* out_buf, const int out_size) {
-    const int channels = this->m_audioContext.getChannels ();
+void AudioStream::flushConverter () {
     const int samples = swr_get_out_samples (this->m_swrctx, 0);
 
     if (samples <= 0) {
-	return -1;
-    }
-
-    uint8_t* data = nullptr;
-
-    if (av_samples_alloc (&data, nullptr, channels, samples, this->m_audioContext.getFormat (), 1) < 0) {
-	return -1;
+	return;
     }
 
-    const int converted = swr_convert (this->m_swrctx, &data, samples, nullptr, 0);
-    const int size = converted > 0
-	? av_samples_get_buffer_size (nullptr, channels, converted, this->m_audioContext.getFormat (), 1)
-	: -1;
+    const size_t offset = this->m_source.size ();
 
-    if (size > 0) {
-	memcpy (out_buf, data, std::min (size, out_size));
-    }
+    this->m_source.resize (offset + static_cast<size_t> (samples) * this->m_channels);
 
-    av_freep (&data);
+    auto* out = reinterpret_cast<uint8_t*> (this->m_source.data () + offset);
+    const int converted = swr_convert (this->m_swrctx, &out, samples, nullptr, 0);
 
-    return size > 0 ? std::min (size, out_size) : -1;
+    this->m_source.resize (offset + static_cast<size_t> (std::max (converted, 0)) * this->m_channels);
 }
 
-int AudioStream::decodeFrame (uint8_t* audioBuffer, const int bufferSize) {
+int AudioStream::decodeSource () {
     // runs on the audio callback, so it never waits
     while (this->m_audioContext.getApplicationContext ().state.general.keepRunning) {
 	const int ret = avcodec_receive_frame (this->getContext (), this->m_decodeFrame);
 
 	if (ret == 0) {
-	    const int size = this->resampleAudio (audioBuffer, bufferSize);
-
-	    if (size > 0) {
-		return size;
+	    if (this->convertFrame ()) {
+		return 1;
 	    }
 
 	    continue;
@@ -624,7 +524,8 @@ int AudioStream::decodeFrame (uint8_t* audioBuffer, const int bufferSize) {
 		continue;
 	    }
 
-	    return this->flushResampler (audioBuffer, bufferSize);
+	    this->flushConverter ();
+	    return -1;
 	}
 
 	if (ret != AVERROR (EAGAIN)) {
@@ -654,4 +555,170 @@ int AudioStream::decodeFrame (uint8_t* audioBuffer, const int bufferSize) {
     return -1;
 }
 
-AudioContext& AudioStream::getAudioContext () const { return this->m_audioContext; }
+void AudioStream::fillSource (size_t frames) {
+    while (!this->m_sourceEnded && this->m_source.size () / this->m_channels < this->m_sourcePos + frames) {
+	const int status = this->decodeSource ();
+
+	if (status < 0) {
+	    this->m_sourceEnded = true;
+	} else if (status == 0) {
+	    return;
+	}
+    }
+}
+
+const float* AudioStream::sourceFrame (size_t frame) const {
+    // LoadBufferQueue stops at the queue's end and the rest of the source line repeats the last sample
+    const size_t available = this->m_source.size () / this->m_channels;
+
+    return this->m_source.data () + std::min (frame, available - 1) * this->m_channels;
+}
+
+int AudioStream::read (float* out, const int frames) {
+    if (this->m_ended) {
+	return -1;
+    }
+
+    // the frames this update reads, plus the next one the last of them interpolates towards
+    const uint64_t last = (static_cast<uint64_t> (frames - 1) * this->m_step + this->m_sourceFrac) >> MixerFracBits;
+
+    this->fillSource (static_cast<size_t> (last) + 2);
+
+    const size_t available = this->m_source.size () / this->m_channels;
+
+    if (available == 0) {
+	if (this->m_sourceEnded) {
+	    this->m_ended = true;
+	    return -1;
+	}
+
+	return 0;
+    }
+
+    int written = 0;
+
+    for (; written < frames; written++) {
+	// a voice whose file is over keeps mixing the held last frame until its update is done
+	const bool past = this->m_sourcePos + 1 >= available;
+
+	if (past && !this->m_sourceEnded) {
+	    break;
+	}
+
+	const float* first = this->sourceFrame (this->m_sourcePos);
+	const float* second = this->sourceFrame (this->m_sourcePos + 1);
+	const float mu = static_cast<float> (this->m_sourceFrac) * (1.0f / MixerFracOne);
+
+	for (int channel = 0; channel < this->m_channels; channel++) {
+	    out[written * this->m_channels + channel] = first[channel] + (second[channel] - first[channel]) * mu;
+	}
+
+	this->m_sourceFrac += this->m_step;
+	this->m_sourcePos += this->m_sourceFrac >> MixerFracBits;
+	this->m_sourceFrac &= MixerFracMask;
+    }
+
+    // OpenAL knows where its queue ends: a file running out right at the end of an update ends the voice there too
+    if (this->m_sourcePos >= available) {
+	this->fillSource (1);
+    }
+
+    if (this->m_sourceEnded && this->m_sourcePos >= this->m_source.size () / this->m_channels) {
+	this->m_ended = true;
+    }
+
+    // keep the frame before the position (a stopping voice's history) and what the next update reads
+    if (this->m_sourcePos > 4096) {
+	const size_t drop = std::min (this->m_sourcePos - 1, available - 1);
+
+	this->m_source.erase (
+	    this->m_source.begin (), this->m_source.begin () + static_cast<long> (drop * this->m_channels)
+	);
+	this->m_sourcePos -= drop;
+    }
+
+    return written;
+}
+
+bool AudioStream::ended () const { return this->m_ended; }
+
+std::vector<int> AudioStream::passes (const int frames) const {
+    constexpr uint64_t BufferLineSize = 1024;
+    std::vector<int> result;
+    uint32_t frac = this->m_sourceFrac;
+
+    for (int done = 0; done < frames;) {
+	uint64_t count = static_cast<uint64_t> (frames - done);
+
+	if (this->m_step > MixerFracOne
+	    && ((count * this->m_step + frac) >> MixerFracBits) + MaxResamplerPadding
+		> BufferLineSize + MaxResamplerPadding) {
+	    // a multiple of 4 for the SIMD mixers
+	    const uint64_t fits = ((BufferLineSize << MixerFracBits) - frac) / this->m_step;
+
+	    if (fits < count) {
+		count = fits & ~uint64_t { 3 };
+	    }
+	}
+
+	result.push_back (static_cast<int> (count));
+	frac = static_cast<uint32_t> ((frac + this->m_step * count) & MixerFracMask);
+	done += static_cast<int> (count);
+    }
+
+    return result;
+}
+
+void AudioStream::stopTail (float* out, const int frames) {
+    constexpr size_t Padding = MaxResamplerPadding >> 1;
+    const int channels = this->m_channels;
+
+    this->fillSource (Padding);
+
+    if (this->m_source.empty ()) {
+	std::fill_n (out, static_cast<size_t> (frames) * channels, 0.0f);
+	return;
+    }
+
+    std::vector<float> line (Padding + 1);
+
+    for (int channel = 0; channel < channels; channel++) {
+	// mPrevSamples: the frame before the position (zeros before a voice's first update), then the next Padding
+	const float before = this->m_sourcePos > 0 ? this->sourceFrame (this->m_sourcePos - 1)[channel] : 0.0f;
+	size_t count = 0;
+	size_t quietest = 0;
+
+	for (size_t i = 0; i < Padding; i++) {
+	    line[i] = this->sourceFrame (this->m_sourcePos + i)[channel];
+
+	    if (std::abs (line[i]) < std::abs (line[quietest])) {
+		quietest = i;
+	    }
+	}
+
+	count = quietest;
+
+	const float held = count > 0 ? line[count - 1] : before;
+
+	std::fill (line.begin () + static_cast<long> (count), line.end (), held);
+
+	uint32_t frac = this->m_sourceFrac;
+	size_t pos = 0;
+
+	for (int i = 0; i < frames; i++) {
+	    const float first = line[std::min (pos, Padding)];
+	    const float second = line[std::min (pos + 1, Padding)];
+
+	    out[i * channels + channel]
+		= first + (second - first) * (static_cast<float> (frac) * (1.0f / MixerFracOne));
+
+	    frac += this->m_step;
+	    pos += frac >> MixerFracBits;
+	    frac &= MixerFracMask;
+	}
+    }
+
+    this->m_ended = true;
+}
+
+AudioContext& AudioStream::getAudioContext () const { return this->m_audioContext; }

+ 43 - 8
src/WallpaperEngine/Audio/AudioStream.h

@@ -2,6 +2,7 @@
 
 #include <atomic>
 #include <string>
+#include <vector>
 
 extern "C" {
 #include <libavcodec/avcodec.h>
@@ -96,24 +97,49 @@ public:
     [[nodiscard]] AVRational getTimeBase () const;
 
     /**
-     * Reads a frame from the audio stream, resamples it to the driver's settings
-     * and returns the data ready to be played
+     * Plays the stream at the driver's rate the way an OpenAL Soft 1.21.1 source plays a file at its own rate (WE hands
+     * every sound file to OpenAL as is, mediaextensions64.dll sub_18000D530): linear interpolation over a 12 bit fixed
+     * point position, the step rounded from file rate / device rate. Past the end the last frame is held, like the
+     * padding OpenAL loads after a queue's end.
      *
-     * @return The amount of bytes available, 0 when nothing is decoded yet or < 0 at the end or on error
+     * @param out Interleaved float frames in the driver's channel layout
+     * @return Frames written, 0 when nothing is decoded yet, < 0 once the voice is over
      */
-    int decodeFrame (uint8_t* audioBuffer, int bufferSize);
+    int read (float* out, int frames);
+
+    /**
+     * How OpenAL splits the next update of this many frames into mixing passes (Voice::mix): a step above 1 reads more
+     * source frames than it writes, and one pass loads at most BufferLineSize of them
+     */
+    [[nodiscard]] std::vector<int> passes (int frames) const;
+
+    /** Whether the voice played past the file's end, OpenAL then stops it after the current update */
+    [[nodiscard]] bool ended () const;
+
+    /**
+     * What a stopping voice mixes in its last update when it has no buffer left (alSourceStop, or the natural end): up
+     * to 24 of the upcoming frames, cut per channel before the one closest to zero and held from there (voice.cpp)
+     */
+    void stopTail (float* out, int frames);
 
 private:
     /**
      * Initializes ffmpeg to read the given file
      */
     void loadCustomContent (const char* filename = nullptr);
+    /** Converts the decoded frame to float in the driver's channel layout at the file's rate, onto m_source */
+    bool convertFrame ();
+    /** Converts what the converter still holds once the decoder is drained */
+    void flushConverter ();
     /**
-     * Converts the audio frame from the original format to one supported by the audio driver
+     * Decodes the next frame onto m_source without waiting
+     *
+     * @return 1 when frames were added, 0 when nothing is queued yet, -1 at the end or on an error
      */
-    int resampleAudio (uint8_t* out_buf, const int out_size);
-    /** Converts what the resampler still holds once the decoder is drained */
-    int flushResampler (uint8_t* out_buf, int out_size);
+    int decodeSource ();
+    /** Makes sure m_source holds this many frames past the read position, unless the file ends first */
+    void fillSource (size_t frames);
+    [[nodiscard]] const float* sourceFrame (size_t frame) const;
     bool doQueue (AVPacket* pkt);
     /**
      * Initializes queues and ffmpeg resampling
@@ -136,6 +162,15 @@ private:
 	AVPacket* packet;
     };
 
+    /** decoded frames at the file's rate, interleaved; m_sourcePos and m_sourceFrac are the voice position in it */
+    std::vector<float> m_source;
+    int m_channels = 0;
+    size_t m_sourcePos = 0;
+    uint32_t m_sourceFrac = 0;
+    uint32_t m_step = 0;
+    bool m_sourceEnded = false;
+    bool m_ended = false;
+
     AVPacket* m_decodePacket = nullptr;
     AVFrame* m_decodeFrame = nullptr;
     bool m_loopDrain = false;

+ 23 - 0
src/WallpaperEngine/Audio/Drivers/AudioDriver.h

@@ -6,6 +6,7 @@
 #include "WallpaperEngine/Audio/AudioStream.h"
 #include "WallpaperEngine/Audio/Drivers/Detectors/AudioPlayingDetector.h"
 #include "WallpaperEngine/Audio/Drivers/Recorders/PlaybackRecorder.h"
+#include "WallpaperEngine/Audio/Hrtf.h"
 
 namespace WallpaperEngine {
 namespace Application {
@@ -24,6 +25,12 @@ namespace Audio {
 	    class PulseAudioPlaybackRecorder;
 	}
 
+	/** HRTF filters of a stream, one per input channel it uses: a mono file's first channel, a stereo file's two */
+	struct StreamHrtf {
+	    int channels = 1;
+	    std::array<Hrtf::Filter, 2> filters {};
+	};
+
 	class AudioDriver {
 	public:
 	    explicit AudioDriver (
@@ -63,6 +70,22 @@ namespace Audio {
 	     * A paused stream keeps its position and isn't decoded until it is resumed
 	     */
 	    virtual void setStreamPaused (int streamId, bool paused) = 0;
+	    /**
+	     * Stops a stream the way OpenAL stops a source: one more update without new audio (only an HRTF voice's
+	     * delayed samples fade out), then it is removed; the driver keeps the stream alive until then
+	     */
+	    virtual void stopStream (int streamId, std::unique_ptr<AudioStream> stream) {
+		this->removeStream (streamId);
+	    }
+	    /**
+	     * Mixes the stream through the HRTF renderer with these filters while HRTF is on, nullptr goes back to the
+	     * channel gains
+	     */
+	    virtual void setStreamHrtf (int streamId, const StreamHrtf* hrtf) { }
+	    /**
+	     * @return The HRTF data set at the output rate while headphones rendering is on, nullptr otherwise
+	     */
+	    [[nodiscard]] virtual const Hrtf::Store* getHrtf () const { return nullptr; }
 
 	    /**
 	     * Updates status of the different audio settings

+ 234 - 0
src/WallpaperEngine/Audio/Drivers/Detectors/HeadphonesDetector.cpp

@@ -0,0 +1,234 @@
+#include "HeadphonesDetector.h"
+#include "WallpaperEngine/Logging/Log.h"
+
+#include <cstring>
+
+using namespace WallpaperEngine::Audio::Drivers::Detectors;
+
+namespace {
+constexpr pa_usec_t STARTUP_TIMEOUT_USEC = 2 * PA_USEC_PER_SEC;
+
+bool isHeadphonesFormFactor (const char* value) {
+    return value != nullptr && (std::strcmp (value, "headphone") == 0 || std::strcmp (value, "headset") == 0);
+}
+
+/** WASAPI's Headphones/Headset form factors on a stereo device, in PulseAudio terms */
+bool isHeadphones (const pa_sink_info& info) {
+    if (info.sample_spec.channels != 2) {
+	return false;
+    }
+
+    // PulseAudio's name for it, and PipeWire's own spelling
+    if (isHeadphonesFormFactor (pa_proplist_gets (info.proplist, PA_PROP_DEVICE_FORM_FACTOR))
+	|| isHeadphonesFormFactor (pa_proplist_gets (info.proplist, "device.form-factor"))) {
+	return true;
+    }
+
+    if (info.active_port == nullptr) {
+	return false;
+    }
+
+#if PA_CHECK_VERSION(14, 0, 0)
+    if (info.active_port->type == PA_DEVICE_PORT_TYPE_HEADPHONES
+	|| info.active_port->type == PA_DEVICE_PORT_TYPE_HEADSET) {
+	return true;
+    }
+#endif
+
+    // what OpenAL Soft's own PulseAudio backend checks
+    return std::strcmp (info.active_port->name, "analog-output-headphones") == 0;
+}
+} // namespace
+
+HeadphonesDetector::HeadphonesDetector () {
+    this->m_mainloop = pa_threaded_mainloop_new ();
+
+    // the first connection doesn't wait for a server, the sounds start right after this
+    this->connect (PA_CONTEXT_NOFLAGS);
+
+    if (pa_threaded_mainloop_start (this->m_mainloop) < 0) {
+	sLog.error ("Cannot start the sound server connection, headphones detection is disabled");
+	return;
+    }
+
+    // the first sounds start right after this, so wait for the first answer, but not on a server that never gives one
+    pa_threaded_mainloop_lock (this->m_mainloop);
+
+    pa_mainloop_api* api = pa_threaded_mainloop_get_api (this->m_mainloop);
+    timeval deadline {};
+
+    pa_timeval_add (pa_gettimeofday (&deadline), STARTUP_TIMEOUT_USEC);
+    pa_time_event* timeout = api->time_new (api, &deadline, &HeadphonesDetector::startupTimeout, this);
+
+    while (!this->m_startupExpired) {
+	const pa_context_state_t state = pa_context_get_state (this->m_context);
+
+	if (!PA_CONTEXT_IS_GOOD (state) || (state == PA_CONTEXT_READY && this->m_pending == 0)) {
+	    break;
+	}
+
+	pa_threaded_mainloop_wait (this->m_mainloop);
+    }
+
+    api->time_free (timeout);
+    pa_threaded_mainloop_unlock (this->m_mainloop);
+
+    if (this->m_startupExpired) {
+	sLog.debug ("The sound server didn't answer in time, headphones detection goes on in the background");
+    }
+}
+
+HeadphonesDetector::~HeadphonesDetector () {
+    if (this->m_mainloop != nullptr) {
+	pa_threaded_mainloop_stop (this->m_mainloop);
+    }
+
+    if (this->m_reconnect != nullptr) {
+	pa_threaded_mainloop_get_api (this->m_mainloop)->time_free (this->m_reconnect);
+    }
+
+    if (this->m_context != nullptr) {
+	pa_context_disconnect (this->m_context);
+	pa_context_unref (this->m_context);
+    }
+
+    if (this->m_mainloop != nullptr) {
+	pa_threaded_mainloop_free (this->m_mainloop);
+    }
+}
+
+void HeadphonesDetector::connect (pa_context_flags_t flags) {
+    if (this->m_context != nullptr) {
+	pa_context_set_state_callback (this->m_context, nullptr, nullptr);
+	pa_context_set_subscribe_callback (this->m_context, nullptr, nullptr);
+	pa_context_disconnect (this->m_context);
+	pa_context_unref (this->m_context);
+    }
+
+    this->m_pending = 0;
+    this->m_wasReady = false;
+    this->m_context = pa_context_new (pa_threaded_mainloop_get_api (this->m_mainloop), "wallpaperengine-output");
+
+    pa_context_set_state_callback (this->m_context, &HeadphonesDetector::contextState, this);
+
+    if (pa_context_connect (this->m_context, nullptr, flags, nullptr) < 0) {
+	// the state callback has seen the failure already when the mainloop runs, before that it's the caller's
+	sLog.debug ("Cannot connect to the sound server: ", pa_strerror (pa_context_errno (this->m_context)));
+    }
+}
+
+void HeadphonesDetector::scheduleReconnect (pa_usec_t delay) {
+    pa_mainloop_api* api = pa_threaded_mainloop_get_api (this->m_mainloop);
+    timeval when {};
+
+    pa_timeval_add (pa_gettimeofday (&when), delay);
+
+    // the context can't be replaced from inside its own state callback
+    if (this->m_reconnect != nullptr) {
+	api->time_restart (this->m_reconnect, &when);
+    } else {
+	this->m_reconnect = api->time_new (api, &when, &HeadphonesDetector::reconnectTimer, this);
+    }
+}
+
+void HeadphonesDetector::startupTimeout (pa_mainloop_api*, pa_time_event*, const timeval*, void* userdata) {
+    auto* detector = static_cast<HeadphonesDetector*> (userdata);
+
+    detector->m_startupExpired = true;
+    pa_threaded_mainloop_signal (detector->m_mainloop, 0);
+}
+
+void HeadphonesDetector::reconnectTimer (pa_mainloop_api* api, pa_time_event* event, const timeval*, void* userdata) {
+    auto* detector = static_cast<HeadphonesDetector*> (userdata);
+
+    api->time_free (event);
+    detector->m_reconnect = nullptr;
+    detector->connect (static_cast<pa_context_flags_t> (PA_CONTEXT_NOFAIL));
+}
+
+void HeadphonesDetector::contextState (pa_context* context, void* userdata) {
+    auto* detector = static_cast<HeadphonesDetector*> (userdata);
+
+    switch (pa_context_get_state (context)) {
+	case PA_CONTEXT_READY:
+	    {
+		pa_context_set_subscribe_callback (context, &HeadphonesDetector::subscription, detector);
+
+		if (pa_operation* operation = pa_context_subscribe (
+			context,
+			static_cast<pa_subscription_mask_t> (PA_SUBSCRIPTION_MASK_SINK | PA_SUBSCRIPTION_MASK_SERVER),
+			nullptr, nullptr
+		    )) {
+		    pa_operation_unref (operation);
+		}
+
+		detector->m_wasReady = true;
+		detector->query ();
+		break;
+	    }
+	case PA_CONTEXT_FAILED:
+	case PA_CONTEXT_TERMINATED:
+	    detector->m_headphones.store (false, std::memory_order_relaxed);
+	    pa_threaded_mainloop_signal (detector->m_mainloop, 0);
+	    // a server that went away: reconnect at once, NOFAIL then waits for it on D-Bus. A connection that never
+	    // got anywhere had no way to wait (no D-Bus, PULSE_SERVER), try again later
+	    detector->scheduleReconnect (detector->m_wasReady ? 0 : 2 * PA_USEC_PER_SEC);
+	    break;
+	default:
+	    break;
+    }
+}
+
+void HeadphonesDetector::subscription (pa_context*, pa_subscription_event_type_t, uint32_t, void* userdata) {
+    // a port switch (headphones plugged in) is a sink change, a new default sink a server change
+    static_cast<HeadphonesDetector*> (userdata)->query ();
+}
+
+void HeadphonesDetector::query () {
+    if (pa_operation* operation = pa_context_get_server_info (this->m_context, &HeadphonesDetector::serverInfo, this)) {
+	this->m_pending++;
+	pa_operation_unref (operation);
+    }
+}
+
+void HeadphonesDetector::serverInfo (pa_context* context, const pa_server_info* info, void* userdata) {
+    auto* detector = static_cast<HeadphonesDetector*> (userdata);
+
+    if (info != nullptr && info->default_sink_name != nullptr) {
+	if (pa_operation* operation = pa_context_get_sink_info_by_name (
+		context, info->default_sink_name, &HeadphonesDetector::sinkInfo, detector
+	    )) {
+	    detector->m_pending++;
+	    pa_operation_unref (operation);
+	}
+    } else {
+	detector->m_headphones.store (false, std::memory_order_relaxed);
+    }
+
+    detector->m_pending--;
+    pa_threaded_mainloop_signal (detector->m_mainloop, 0);
+}
+
+void HeadphonesDetector::sinkInfo (pa_context*, const pa_sink_info* info, int eol, void* userdata) {
+    auto* detector = static_cast<HeadphonesDetector*> (userdata);
+
+    if (eol != 0) {
+	detector->m_pending--;
+	pa_threaded_mainloop_signal (detector->m_mainloop, 0);
+	return;
+    }
+
+    if (info == nullptr) {
+	return;
+    }
+
+    const bool headphones = isHeadphones (*info);
+    const std::string report = std::string (info->name) + (headphones ? " (headphones)" : "");
+
+    detector->m_headphones.store (headphones, std::memory_order_relaxed);
+
+    if (report != detector->m_lastReport) {
+	detector->m_lastReport = report;
+	sLog.debug ("Default audio output: ", report);
+    }
+}

+ 51 - 0
src/WallpaperEngine/Audio/Drivers/Detectors/HeadphonesDetector.h

@@ -0,0 +1,51 @@
+#pragma once
+
+#include <atomic>
+#include <pulse/pulseaudio.h>
+#include <string>
+
+namespace WallpaperEngine::Audio::Drivers::Detectors {
+/**
+ * Whether the default output is headphones, the question OpenAL Soft's WASAPI backend asks Windows when WE opens its
+ * audio device (endpoint form factor Headphones or Headset on a stereo device, mediaextensions64.dll sub_180186400).
+ * Here it is the default sink's form factor or active port type. WE reopens the device on every endpoint change while
+ * its "reloadaudio" setting is on (sub_14006CEA0), so the answer follows sink and default sink changes.
+ *
+ * A sound server that goes away (a PipeWire restart) is waited for, not polled: the new context connects with
+ * PA_CONTEXT_NOFAIL, and libpulse then waits for org.pulseaudio.Server to appear on D-Bus, which pipewire-pulse and
+ * PulseAudio claim once they listen. Without D-Bus, or with PULSE_SERVER set, libpulse can't wait that way and the
+ * detector tries again every 2 s.
+ */
+class HeadphonesDetector {
+public:
+    HeadphonesDetector ();
+    ~HeadphonesDetector ();
+
+    HeadphonesDetector (const HeadphonesDetector&) = delete;
+    HeadphonesDetector& operator= (const HeadphonesDetector&) = delete;
+
+    [[nodiscard]] bool headphones () const { return this->m_headphones.load (std::memory_order_relaxed); }
+
+private:
+    static void contextState (pa_context* context, void* userdata);
+    static void subscription (pa_context* context, pa_subscription_event_type_t type, uint32_t index, void* userdata);
+    static void serverInfo (pa_context* context, const pa_server_info* info, void* userdata);
+    static void sinkInfo (pa_context* context, const pa_sink_info* info, int eol, void* userdata);
+    static void startupTimeout (pa_mainloop_api* api, pa_time_event* event, const struct timeval* tv, void* userdata);
+    static void reconnectTimer (pa_mainloop_api* api, pa_time_event* event, const struct timeval* tv, void* userdata);
+
+    void connect (pa_context_flags_t flags);
+    void scheduleReconnect (pa_usec_t delay);
+    void query ();
+
+    pa_threaded_mainloop* m_mainloop = nullptr;
+    pa_context* m_context = nullptr;
+    pa_time_event* m_reconnect = nullptr;
+    std::atomic<bool> m_headphones { false };
+    /** mainloop thread only */
+    std::string m_lastReport;
+    int m_pending = 0;
+    bool m_wasReady = false;
+    bool m_startupExpired = false;
+};
+} // namespace WallpaperEngine::Audio::Drivers::Detectors

+ 397 - 100
src/WallpaperEngine/Audio/Drivers/SDLAudioDriver.cpp

@@ -1,125 +1,306 @@
 #include "SDLAudioDriver.h"
 #include "WallpaperEngine/Logging/Log.h"
 
-// a sound starts at the next callback, so keep it short (WE's OpenAL Soft updates every 20 ms)
+#include <algorithm>
+#include <cfloat>
+#include <cstring>
+
+// how much SDL asks for at once, the mixing itself runs in WE's update size (m_updateFrames)
 #define SDL_AUDIO_BUFFER_SIZE 1024
-#define MAX_AUDIO_FRAME_SIZE 192000
 
 using namespace WallpaperEngine::Audio;
 using namespace WallpaperEngine::Audio::Drivers;
 
 namespace {
-template <typename T>
-void scaleSamples (uint8_t* data, int bytes, int channels, int firstChannel, float left, float right) {
-    auto* samples = reinterpret_cast<T*> (data);
-    const int count = bytes / static_cast<int> (sizeof (T));
+/** a stopping voice without a buffer fades over at most this many samples (voice.cpp Voice::mix) */
+constexpr unsigned StopFadeSamples = 64;
+
+/**
+ * Per channel gain ramp of one update, OpenAL's MixSamples: from the current gains to the target over counter frames,
+ * the target from there on. A step no bigger than FLT_EPSILON goes straight to the target
+ */
+struct GainRamp {
+    float left, right;
+    float targetLeft, targetRight;
+    int counter;
+
+    [[nodiscard]] float at (int channel, int frame) const {
+	if (channel > 1) {
+	    return (this->at (0, frame) + this->at (1, frame)) * 0.5f;
+	}
+
+	const float gain = channel == 0 ? this->left : this->right;
+	const float target = channel == 0 ? this->targetLeft : this->targetRight;
+	const float step = (target - gain) * (this->counter > 0 ? 1.0f / static_cast<float> (this->counter) : 0.0f);
+
+	if (!(std::abs (step) > FLT_EPSILON) || frame >= this->counter) {
+	    return target;
+	}
+
+	return gain + step * static_cast<float> (frame);
+    }
+};
+
+void audio_callback (void* userdata, uint8_t* streamData, int length) {
+    auto* driver = static_cast<SDLAudioDriver*> (userdata);
 
-    for (int i = 0; i < count; i++) {
-	const int channel = (firstChannel + i) % channels;
-	const float gain = channel == 0 ? left : channel == 1 ? right : (left + right) * 0.5f;
+    memset (streamData, 0, length);
 
-	samples[i] = static_cast<T> (static_cast<float> (samples[i]) * gain);
+    // if audio is playing do not do anything here!
+    if (driver->getAudioDetector ().anythingPlaying ()) {
+	return;
     }
+
+    driver->render (
+	reinterpret_cast<float*> (streamData), length / static_cast<int> (sizeof (float)) / driver->getChannels ()
+    );
 }
+} // namespace
+
+void SDLAudioDriver::render (float* out, int frames) {
+    const int channels = this->m_audioSpec.channels;
+    const size_t wanted = static_cast<size_t> (frames) * channels;
 
-/** Copies a chunk of decoded audio with each channel scaled, false when the device format isn't handled */
-bool scaleChunk (
-    std::vector<uint8_t>& out, const uint8_t* data, int bytes, const SDL_AudioSpec& spec, int byteOffset, float left,
-    float right
-) {
-    const int sampleSize = SDL_AUDIO_BITSIZE (spec.format) / 8;
-    const int firstChannel = (byteOffset / sampleSize) % spec.channels;
+    SDL_LockMutex (this->m_streamListMutex);
 
-    out.assign (data, data + bytes);
+    // the WASAPI mixer thread renders an update once that much buffer is free, in chunks of at most BufferLineSize
+    while (this->m_pending.size () < wanted && this->getApplicationContext ().state.general.keepRunning) {
+	for (int done = 0; done < this->m_updateFrames;) {
+	    const int count = std::min (this->m_updateFrames - done, static_cast<int> (Hrtf::BufferLineSize));
+	    const size_t offset = this->m_pending.size ();
 
-    if (SDL_AUDIO_ISBIGENDIAN (spec.format) != (SDL_BYTEORDER == SDL_BIG_ENDIAN)) {
-	return false;
+	    this->m_pending.resize (offset + static_cast<size_t> (count) * channels, 0.0f);
+	    this->mixUpdate (this->m_pending.data () + offset, count);
+	    done += count;
+	}
     }
 
-    if (SDL_AUDIO_ISFLOAT (spec.format) && sampleSize == 4) {
-	scaleSamples<float> (out.data (), bytes, spec.channels, firstChannel, left, right);
-    } else if (SDL_AUDIO_ISSIGNED (spec.format) && sampleSize == 2) {
-	scaleSamples<int16_t> (out.data (), bytes, spec.channels, firstChannel, left, right);
-    } else if (SDL_AUDIO_ISSIGNED (spec.format) && sampleSize == 4) {
-	scaleSamples<int32_t> (out.data (), bytes, spec.channels, firstChannel, left, right);
-    } else {
-	return false;
+    const size_t available = std::min (wanted, this->m_pending.size ());
+
+    for (size_t i = 0; i < available; i++) {
+	out[i] = std::clamp (this->m_pending[i], -1.0f, 1.0f);
     }
 
-    return true;
+    this->m_pending.erase (this->m_pending.begin (), this->m_pending.begin () + static_cast<long> (available));
+
+    // TODO: do we also need to lock while audio is playing, or wait until the stream is unused?
+    SDL_UnlockMutex (this->m_streamListMutex);
 }
-} // namespace
 
-void audio_callback (void* userdata, uint8_t* streamData, int length) {
-    auto* driver = static_cast<SDLAudioDriver*> (userdata);
+void SDLAudioDriver::mixUpdate (float* out, int frames) {
+    const int channels = this->m_audioSpec.channels;
+    Hrtf::Mixer* hrtf = channels >= 2 ? this->getHrtfMixer () : nullptr;
+    auto& update = this->m_update;
 
-    memset (streamData, 0, length);
+    this->m_hrtfVoices.clear ();
 
-    // if audio is playing do not do anything here!
-    if (driver->getAudioDetector ().anythingPlaying ()) {
-	return;
-    }
+    for (auto* buffer : this->m_streams | std::views::values) {
+	if (!buffer->stream->isInitialized () || buffer->finished.load (std::memory_order_relaxed)) {
+	    continue;
+	}
 
-    SDL_LockMutex (driver->getStreamMutex ());
+	// OpenAL's Stopping state: alSourceStop and alSourcePause both mix one more update with the gain going to 0,
+	// and so does a voice whose file ran out in the last update
+	const bool stopping = buffer->stopping.load (std::memory_order_acquire);
+	const bool pausing = !stopping && buffer->paused.load (std::memory_order_relaxed);
+	const bool runOut = !stopping && !pausing && buffer->stream->ended ();
 
-    for (const auto& buffer : driver->getStreams () | std::views::values) {
-	uint8_t* streamDataPointer = streamData;
-	int streamLength = length;
+	if (buffer->over || (stopping && buffer->pauseFaded)) {
+	    if (stopping) {
+		buffer->finished.store (true, std::memory_order_release);
+	    }
 
-	if (!buffer->stream->isInitialized () || buffer->paused.load (std::memory_order_relaxed)) {
 	    continue;
 	}
 
-	while (streamLength > 0 && driver->getApplicationContext ().state.general.keepRunning) {
-	    if (buffer->audio_buf_index >= buffer->audio_buf_size) {
-		int audio_size = buffer->stream->decodeFrame (buffer->audio_buf, sizeof (buffer->audio_buf));
+	if (pausing && buffer->pauseFaded) {
+	    continue;
+	}
+
+	buffer->pauseFaded = false;
+
+	// a stopping voice that never mixed has no gains to fade from (Counter 0), it goes silent right away
+	if ((stopping || runOut) && !buffer->mixed) {
+	    if (stopping) {
+		buffer->finished.store (true, std::memory_order_release);
+	    } else {
+		buffer->over = true;
+	    }
+
+	    continue;
+	}
+
+	const bool ending = stopping || pausing || runOut;
+	// without a buffer the fade is cut short, a paused voice keeps its buffer and fades over the whole update
+	const bool detached = stopping || runOut;
+	bool viaHrtf = false;
+
+	if (hrtf != nullptr) {
+	    std::lock_guard lock (buffer->hrtfMutex);
+
+	    if (buffer->hrtfSet) {
+		buffer->hrtfMixing = buffer->hrtf;
+		viaHrtf = true;
+	    }
+	}
+
+	update.assign (static_cast<size_t> (frames) * channels, 0.0f);
+
+	// a resumed voice replays audio it already read, its passes are not known any more
+	if (viaHrtf) {
+	    buffer->hrtfPasses
+		= !detached && !buffer->replay.empty () ? std::vector { frames } : buffer->stream->passes (frames);
+	}
+
+	if (detached) {
+	    // alSourceStop detaches the buffer before the update (ProcessVoiceChanges), so the voice plays out what it
+	    // loaded last time instead
+	    buffer->stream->stopTail (update.data (), frames);
+	} else {
+	    // this update's audio: what a pause held back first, then newly decoded data
+	    const size_t replayed = std::min (buffer->replay.size (), update.size ());
+
+	    std::copy_n (buffer->replay.begin (), replayed, update.begin ());
+	    buffer->replay.erase (buffer->replay.begin (), buffer->replay.begin () + static_cast<long> (replayed));
+
+	    int filled = static_cast<int> (replayed) / channels;
+
+	    while (filled < frames && this->getApplicationContext ().state.general.keepRunning) {
+		const int read
+		    = buffer->stream->read (update.data () + static_cast<size_t> (filled) * channels, frames - filled);
 
 		// 0: nothing decoded yet, wake the reader
-		if (audio_size <= 0) {
-		    if (audio_size == 0) {
+		if (read <= 0) {
+		    if (read == 0) {
 			SDL_CondSignal (buffer->stream->getWaitCondition ());
 		    }
 
 		    break;
 		}
 
-		buffer->audio_buf_size = audio_size;
-		buffer->audio_buf_index = 0;
+		filled += read;
+	    }
+
+	    // a stopping voice doesn't advance, a resumed one plays this update again
+	    if (pausing) {
+		buffer->replay.insert (
+		    buffer->replay.begin (), update.begin (), update.begin () + static_cast<long> (filled) * channels
+		);
+	    }
+	}
+
+	// mix the audio, using this stream's own volume override if it has one
+	const int streamVolume = buffer->volume.load (std::memory_order_relaxed);
+	const int volume = streamVolume >= 0 ? streamVolume : this->getApplicationContext ().state.audio.volume;
+	const float scale = static_cast<float> (volume) / static_cast<float> (SDL_MIX_MAXVOLUME);
+	const int counter = detached ? std::min (frames, static_cast<int> (StopFadeSamples)) : frames;
+
+	if (viaHrtf) {
+	    for (int channel = 0; channel < buffer->hrtfMixing.channels; channel++) {
+		auto& samples = buffer->hrtfSamples[channel];
+
+		samples.resize (frames);
+
+		for (int i = 0; i < frames; i++) {
+		    samples[i] = update[static_cast<size_t> (i) * channels + channel] * scale;
+		}
+
+		if (ending) {
+		    buffer->hrtfMixing.filters[channel].gain = 0.0f;
+		}
 	    }
 
-	    int len1 = buffer->audio_buf_size - buffer->audio_buf_index;
+	    buffer->hrtfCounter = counter;
+	    this->m_hrtfVoices.push_back (buffer);
+	} else {
+	    const float targetLeft = ending ? 0.0f : buffer->gainLeft.load (std::memory_order_relaxed);
+	    const float targetRight = ending ? 0.0f : buffer->gainRight.load (std::memory_order_relaxed);
 
-	    if (len1 > streamLength) {
-		len1 = streamLength;
+	    // a voice's first update starts at its target gains, the later ones ramp over the update
+	    if (!buffer->mixed) {
+		buffer->currentLeft = targetLeft;
+		buffer->currentRight = targetRight;
 	    }
 
-	    // mix the audio, using this stream's own volume override if it has one
-	    const int streamVolume = buffer->volume.load (std::memory_order_relaxed);
-	    const float left = buffer->gainLeft.load (std::memory_order_relaxed);
-	    const float right = buffer->gainRight.load (std::memory_order_relaxed);
-	    const uint8_t* source = &buffer->audio_buf[buffer->audio_buf_index];
-	    static std::vector<uint8_t> scaled;
-
-	    if ((left != 1.0f || right != 1.0f)
-		&& scaleChunk (
-		    scaled, source, len1, driver->getSpec (), static_cast<int> (buffer->audio_buf_index), left, right
-		)) {
-		source = scaled.data ();
+	    const GainRamp ramp { buffer->currentLeft, buffer->currentRight, targetLeft, targetRight, counter };
+
+	    buffer->currentLeft = targetLeft;
+	    buffer->currentRight = targetRight;
+
+	    for (int i = 0; i < frames; i++) {
+		for (int channel = 0; channel < channels; channel++) {
+		    const size_t index = static_cast<size_t> (i) * channels + channel;
+
+		    out[index] += update[index] * ramp.at (channel, i) * scale;
+		}
 	    }
+	}
 
-	    SDL_MixAudioFormat (
-		streamDataPointer, source, driver->getSpec ().format, len1,
-		streamVolume >= 0 ? streamVolume : driver->getApplicationContext ().state.audio.volume
-	    );
+	buffer->mixed = true;
 
-	    streamLength -= len1;
-	    streamDataPointer += len1;
-	    buffer->audio_buf_index += len1;
+	if (pausing) {
+	    buffer->pauseFaded = true;
+	} else if (stopping) {
+	    buffer->finished.store (true, std::memory_order_release);
+	} else if (runOut) {
+	    buffer->over = true;
 	}
     }
 
-    // TODO: do we also need to lock while audio is playing, or wait until the stream is unused?
-    SDL_UnlockMutex (driver->getStreamMutex ());
+    // the accumulator carries the tail of the last updates, so it runs even with no voice left
+    if (hrtf != nullptr) {
+	this->mixHrtf (this->m_hrtfVoices, out, frames);
+    }
+}
+
+void SDLAudioDriver::mixHrtf (const std::vector<SDLAudioBuffer*>& voices, float* out, int frames) {
+    Hrtf::Mixer& mixer = *this->m_hrtfMixer;
+    const unsigned generation = this->getHrtfGeneration ();
+    const int channels = this->m_audioSpec.channels;
+
+    if (this->m_hrtfMixerGeneration != generation) {
+	this->m_hrtfMixerGeneration = generation;
+	mixer.clear ();
+    }
+
+    auto& [left, right] = this->m_hrtfOutput;
+
+    left.assign (frames, 0.0f);
+    right.assign (frames, 0.0f);
+
+    for (auto* voice : voices) {
+	if (voice->hrtfGeneration != generation) {
+	    voice->hrtfGeneration = generation;
+	    voice->hrtfChannels = {};
+	    voice->hrtfFading = false;
+	}
+
+	unsigned counter = voice->hrtfFading ? static_cast<unsigned> (voice->hrtfCounter) : 0;
+	unsigned outPos = 0;
+
+	for (const int pass : voice->hrtfPasses) {
+	    const auto count = static_cast<unsigned> (pass);
+
+	    for (int channel = 0; channel < voice->hrtfMixing.channels; channel++) {
+		mixer.mix (
+		    voice->hrtfChannels[channel], voice->hrtfMixing.filters[channel],
+		    voice->hrtfSamples[channel].data () + outPos, count, counter, outPos
+		);
+	    }
+
+	    outPos += count;
+	    counter = std::max (count, counter) - count;
+	}
+
+	voice->hrtfFading = true;
+    }
+
+    mixer.finish (left.data (), right.data (), static_cast<unsigned> (frames));
+
+    for (int i = 0; i < frames; i++) {
+	out[static_cast<size_t> (i) * channels] += left[i];
+	out[static_cast<size_t> (i) * channels + 1] += right[i];
+    }
 }
 
 SDLAudioDriver::SDLAudioDriver (
@@ -142,17 +323,29 @@ SDLAudioDriver::SDLAudioDriver (
 					  .callback = audio_callback,
 					  .userdata = this };
 
-    this->m_deviceID
-	= SDL_OpenAudioDevice (nullptr, false, &requestedSpec, &this->m_audioSpec, SDL_AUDIO_ALLOW_ANY_CHANGE);
+    // mixing is done in float like OpenAL's, SDL converts to whatever the device takes
+    this->m_deviceID = SDL_OpenAudioDevice (
+	nullptr, false, &requestedSpec, &this->m_audioSpec,
+	SDL_AUDIO_ALLOW_FREQUENCY_CHANGE | SDL_AUDIO_ALLOW_CHANNELS_CHANGE | SDL_AUDIO_ALLOW_SAMPLES_CHANGE
+    );
 
     if (this->m_deviceID == 0) {
 	sLog.error ("SDL_OpenAudioDevice: ", SDL_GetError ());
 	return;
     }
 
-    SDL_PauseAudioDevice (this->m_deviceID, 0);
+    // WasapiPlayback::resetProxy: OpenAL's 20 ms default update in 100 ns units, rounded to a multiple of the
+    // endpoint's default period (Windows' shared mode default, 10 ms), in frames at the device rate
+    constexpr int64_t updateTime = 10000000LL * 882 / 44100;
+    constexpr int64_t periodTime = 100000;
+    constexpr int64_t periods = std::max<int64_t> ((updateTime + periodTime / 2) / periodTime, 1);
+
+    this->m_updateFrames = static_cast<int> ((periodTime * periods * this->m_audioSpec.freq + 5000000) / 10000000);
 
     this->m_initialized = true;
+    this->updateHrtf ();
+
+    SDL_PauseAudioDevice (this->m_deviceID, 0);
 }
 
 SDLAudioDriver::~SDLAudioDriver () {
@@ -164,6 +357,13 @@ SDLAudioDriver::~SDLAudioDriver () {
 	SDL_CloseAudioDevice (this->m_deviceID);
     }
 
+    // streams still fading out belong to the driver
+    for (const auto* buffer : this->m_streams | std::views::values) {
+	delete buffer;
+    }
+
+    this->m_streams.clear ();
+
     SDL_QuitSubSystem (SDL_INIT_AUDIO);
 }
 
@@ -224,33 +424,130 @@ void SDLAudioDriver::setStreamPaused (int streamId, bool paused) {
     }
 }
 
-const std::map<int, SDLAudioBuffer*>& SDLAudioDriver::getStreams () { return this->m_streams; }
-
-AVSampleFormat SDLAudioDriver::getFormat () const {
-    switch (this->m_audioSpec.format) {
-	case AUDIO_U8:
-	case AUDIO_S8:
-	    return AV_SAMPLE_FMT_U8;
-	case AUDIO_U16MSB:
-	case AUDIO_U16LSB:
-	case AUDIO_S16LSB:
-	case AUDIO_S16MSB:
-	    return AV_SAMPLE_FMT_S16;
-	case AUDIO_S32LSB:
-	case AUDIO_S32MSB:
-	    return AV_SAMPLE_FMT_S32;
-	case AUDIO_F32LSB:
-	case AUDIO_F32MSB:
-	    return AV_SAMPLE_FMT_FLT;
-	default:
-	    sLog.exception ("Cannot convert from SDL format to ffmpeg format, aborting...");
+void SDLAudioDriver::setStreamHrtf (int streamId, const StreamHrtf* hrtf) {
+    // same reasoning as setStreamVolume for the lookup, the filters themselves are copied under the stream's lock
+    if (const auto it = this->m_streams.find (streamId); it != this->m_streams.end ()) {
+	std::lock_guard lock (it->second->hrtfMutex);
+
+	it->second->hrtfSet = hrtf != nullptr;
+
+	if (hrtf != nullptr) {
+	    it->second->hrtf = *hrtf;
+	}
     }
 }
 
-int SDLAudioDriver::getSampleRate () const { return this->m_audioSpec.freq; }
+const Hrtf::Store* SDLAudioDriver::getHrtf () const {
+    return this->m_hrtfEnabled.load (std::memory_order_acquire) ? this->m_hrtfStore.get () : nullptr;
+}
 
-int SDLAudioDriver::getChannels () const { return this->m_audioSpec.channels; }
+Hrtf::Mixer* SDLAudioDriver::getHrtfMixer () const {
+    return this->m_hrtfEnabled.load (std::memory_order_acquire) ? this->m_hrtfMixer.get () : nullptr;
+}
 
-const SDL_AudioSpec& SDLAudioDriver::getSpec () const { return this->m_audioSpec; }
+unsigned SDLAudioDriver::getHrtfGeneration () const { return this->m_hrtfGeneration.load (std::memory_order_acquire); }
 
-SDL_mutex* SDLAudioDriver::getStreamMutex () const { return this->m_streamListMutex; }
+void SDLAudioDriver::update (float dt) {
+    AudioDriver::update (dt);
+    this->releaseFinishedStreams ();
+    this->updateHrtf ();
+}
+
+void SDLAudioDriver::updateHrtf () {
+    if (!this->m_initialized || this->m_hrtfFailed) {
+	return;
+    }
+
+    const auto mode = this->getApplicationContext ().settings.audio.hrtf;
+
+    // created the first time auto is the mode, from the command line or a control file
+    if (mode == Application::ApplicationContext::HRTF_AUTO && this->m_headphonesDetector == nullptr
+	&& this->getApplicationContext ().settings.audio.enabled) {
+	this->m_headphonesDetector = std::make_unique<Detectors::HeadphonesDetector> ();
+    }
+
+    const bool headphones = this->m_headphonesDetector != nullptr && this->m_headphonesDetector->headphones ();
+    // OpenAL Soft only renders HRTF on stereo output
+    const bool wanted = this->m_audioSpec.channels == 2
+	&& (mode == Application::ApplicationContext::HRTF_ON
+	    || (mode == Application::ApplicationContext::HRTF_AUTO && headphones));
+
+    if (wanted == this->m_hrtfEnabled.load (std::memory_order_relaxed)) {
+	return;
+    }
+
+    if (wanted && this->m_hrtfStore == nullptr) {
+	this->m_hrtfStore = Hrtf::loadDefault (static_cast<unsigned> (this->m_audioSpec.freq));
+
+	if (this->m_hrtfStore == nullptr) {
+	    this->m_hrtfFailed = true;
+	    return;
+	}
+
+	this->m_hrtfMixer = std::make_unique<Hrtf::Mixer> (this->m_hrtfStore->irSize);
+    }
+
+    if (wanted) {
+	this->m_hrtfGeneration.fetch_add (1, std::memory_order_release);
+    }
+
+    this->m_hrtfEnabled.store (wanted, std::memory_order_release);
+
+    sLog.out (
+	"Sound objects: HRTF ", wanted ? "on" : "off",
+	mode == Application::ApplicationContext::HRTF_AUTO ? (headphones ? " (headphones)" : " (speakers)")
+							   : " (forced)"
+    );
+}
+
+void SDLAudioDriver::stopStream (int streamId, std::unique_ptr<AudioStream> stream) {
+    SDL_LockMutex (this->m_streamListMutex);
+
+    if (const auto it = this->m_streams.find (streamId); it != this->m_streams.end () && this->m_initialized) {
+	it->second->owned = std::move (stream);
+	it->second->stopping.store (true, std::memory_order_release);
+    }
+
+    SDL_UnlockMutex (this->m_streamListMutex);
+
+    // not registered (or no device): nothing to fade, the stream goes right away
+    if (stream != nullptr) {
+	this->removeStream (streamId);
+    }
+}
+
+void SDLAudioDriver::releaseFinishedStreams () {
+    std::vector<SDLAudioBuffer*> finished;
+
+    // only mixUpdate marks a stopping voice finished; while automute holds the callback back or the device is gone
+    // nothing mixes, and there is no fade to hear anyway
+    const bool mixing = SDL_GetAudioDeviceStatus (this->m_deviceID) == SDL_AUDIO_PLAYING
+	&& !this->getAudioDetector ().anythingPlaying ();
+
+    SDL_LockMutex (this->m_streamListMutex);
+
+    for (auto it = this->m_streams.begin (); it != this->m_streams.end ();) {
+	const bool done = it->second->finished.load (std::memory_order_acquire)
+	    || (!mixing && it->second->stopping.load (std::memory_order_acquire));
+
+	if (done && it->second->owned != nullptr) {
+	    finished.push_back (it->second);
+	    it = this->m_streams.erase (it);
+	} else {
+	    ++it;
+	}
+    }
+
+    SDL_UnlockMutex (this->m_streamListMutex);
+
+    // outside the lock, an AudioStream waits for its reader thread
+    for (const auto* buffer : finished) {
+	delete buffer;
+    }
+}
+
+AVSampleFormat SDLAudioDriver::getFormat () const { return AV_SAMPLE_FMT_FLT; }
+
+int SDLAudioDriver::getSampleRate () const { return this->m_audioSpec.freq; }
+
+int SDLAudioDriver::getChannels () const { return this->m_audioSpec.channels; }

+ 79 - 9
src/WallpaperEngine/Audio/Drivers/SDLAudioDriver.h

@@ -2,26 +2,56 @@
 
 #include <atomic>
 #include <map>
+#include <memory>
+#include <mutex>
 #include <vector>
 
 #include "WallpaperEngine/Audio/AudioStream.h"
 #include "WallpaperEngine/Audio/Drivers/AudioDriver.h"
+#include "WallpaperEngine/Audio/Drivers/Detectors/HeadphonesDetector.h"
+#include "WallpaperEngine/Audio/Hrtf.h"
 
 #include <SDL.h>
 
-#define MAX_AUDIO_FRAME_SIZE 192000
-
 namespace WallpaperEngine::Audio::Drivers {
 struct SDLAudioBuffer {
     AudioStream* stream = nullptr;
-    uint8_t audio_buf[(MAX_AUDIO_FRAME_SIZE * 3) / 2] = { 0 };
-    unsigned int audio_buf_size = 0;
-    unsigned int audio_buf_index = 0;
     /** Per-stream volume override (0-128), -1 = use the driver's global volume */
     std::atomic<int> volume { -1 };
     std::atomic<float> gainLeft { 1.0f };
     std::atomic<float> gainRight { 1.0f };
     std::atomic<bool> paused { false };
+    /** stopStream: one more update fading to silence, then finished and freed by update () with the stream */
+    std::atomic<bool> stopping { false };
+    std::atomic<bool> finished { false };
+    std::unique_ptr<AudioStream> owned;
+    /** audio callback only: the file ran out and its stopping update was mixed, the voice stays silent from here */
+    bool over = false;
+
+    /** audio callback only: OpenAL's voice state for the gain path, set after a voice's first update */
+    bool mixed = false;
+    float currentLeft = 1.0f;
+    float currentRight = 1.0f;
+    /** the update a pause faded out, played again on resume (a stopping OpenAL voice keeps its position) */
+    bool pauseFaded = false;
+    std::vector<float> replay;
+
+    /** set by setStreamHrtf on the render thread */
+    std::mutex hrtfMutex;
+    bool hrtfSet = false;
+    StreamHrtf hrtf {};
+
+    /** audio callback only: the filters of this callback, OpenAL's voice state and the decoded input */
+    StreamHrtf hrtfMixing {};
+    std::array<Hrtf::Channel, 2> hrtfChannels {};
+    /** OpenAL's VoiceIsFading, set after a voice's first update */
+    bool hrtfFading = false;
+    /** this update's fade length once fading: the update, or less for a voice stopping without its buffer */
+    int hrtfCounter = 0;
+    /** this update's mixing passes, see AudioStream::passes */
+    std::vector<int> hrtfPasses;
+    unsigned hrtfGeneration = 0;
+    std::array<std::vector<float>, 2> hrtfSamples {};
 };
 
 class SDLAudioDriver final : public AudioDriver {
@@ -37,14 +67,18 @@ public:
     void setStreamVolume (int streamId, int volume) override;
     void setStreamGains (int streamId, float left, float right) override;
     void setStreamPaused (int streamId, bool paused) override;
-    const std::map<int, SDLAudioBuffer*>& getStreams ();
+    void stopStream (int streamId, std::unique_ptr<AudioStream> stream) override;
+    void setStreamHrtf (int streamId, const StreamHrtf* hrtf) override;
+    [[nodiscard]] const Hrtf::Store* getHrtf () const override;
+
+    void update (float dt) override;
+
+    /** Fills the device buffer from whole updates of m_updateFrames, mixing more as needed (the SDL callback) */
+    void render (float* out, int frames);
 
     [[nodiscard]] AVSampleFormat getFormat () const override;
     [[nodiscard]] int getSampleRate () const override;
     [[nodiscard]] int getChannels () const override;
-    [[nodiscard]] const SDL_AudioSpec& getSpec () const;
-
-    [[nodiscard]] SDL_mutex* getStreamMutex () const;
 
 private:
     SDL_mutex* m_streamListMutex;
@@ -53,5 +87,41 @@ private:
     bool m_initialized = false;
     SDL_AudioSpec m_audioSpec {};
     std::map<int, SDLAudioBuffer*> m_streams {};
+
+    /** The HRTF mixer while headphones rendering is on, nullptr otherwise; for the audio callback */
+    [[nodiscard]] Hrtf::Mixer* getHrtfMixer () const;
+    /** Changes every time HRTF is turned on, voices and the mixer start over then */
+    [[nodiscard]] unsigned getHrtfGeneration () const;
+    /** One OpenAL update (aluMixData) of every stream into out, frames * channels floats */
+    void mixUpdate (float* out, int frames);
+    /** OpenAL's HRTF path for the voices of one update: convolve, then ProcessHrtf, added to out */
+    void mixHrtf (const std::vector<SDLAudioBuffer*>& voices, float* out, int frames);
+
+    /**
+     * Frames OpenAL Soft mixes per update in WE: its default 20 ms period (882 at 44.1 kHz, alcOpenDevice) as a
+     * multiple of the WASAPI endpoint period at the device rate (sub_180186400); the mixer thread renders an update
+     * whenever that much of the WASAPI buffer is free
+     */
+    int m_updateFrames = 960;
+    /** mixed updates the device hasn't taken yet */
+    std::vector<float> m_pending;
+    /** audio callback only */
+    std::vector<float> m_update;
+    std::vector<SDLAudioBuffer*> m_hrtfVoices;
+    std::array<std::vector<float>, 2> m_hrtfOutput;
+    unsigned m_hrtfMixerGeneration = 0;
+
+    /** Frees the streams stopStream faded out */
+    void releaseFinishedStreams ();
+    /** Turns HRTF on or off by the --hrtf mode and the default output, like OpenAL Soft's aluInitRenderer */
+    void updateHrtf ();
+
+    std::unique_ptr<Detectors::HeadphonesDetector> m_headphonesDetector;
+    /** loaded the first time HRTF turns on and kept, the callback may still be using them */
+    std::unique_ptr<Hrtf::Store> m_hrtfStore;
+    std::unique_ptr<Hrtf::Mixer> m_hrtfMixer;
+    bool m_hrtfFailed = false;
+    std::atomic<bool> m_hrtfEnabled { false };
+    std::atomic<unsigned> m_hrtfGeneration { 0 };
 };
 } // namespace WallpaperEngine::Audio::Drivers

+ 550 - 0
src/WallpaperEngine/Audio/Hrtf.cpp

@@ -0,0 +1,550 @@
+#include "Hrtf.h"
+
+#include "WallpaperEngine/Audio/DefaultHrtf.generated.h"
+#include "WallpaperEngine/Logging/Log.h"
+
+#include <algorithm>
+#include <cmath>
+#include <cstring>
+#include <numeric>
+
+using namespace WallpaperEngine::Audio::Hrtf;
+
+namespace {
+constexpr float Pi = 3.14159265358979323846f;
+constexpr float Tau = 6.28318530717958647692f;
+constexpr unsigned MinIrLength = 8;
+constexpr unsigned MaxHrirDelay = HistoryLength - 1;
+constexpr unsigned HrirDelayFracOne = 4;
+/** first value of the pass-through coefficients, for omnidirectional sounds */
+constexpr float PassthruCoeff = 0.707106781187f;
+
+unsigned float2uint (float value) { return static_cast<unsigned> (static_cast<int> (value)); }
+
+/** polyphase_resampler.cpp: Kaiser windowed sinc, only used to bring the HRIRs to the device rate */
+class PolyphaseResampler {
+public:
+    PolyphaseResampler (unsigned srcRate, unsigned dstRate) {
+	const unsigned gcd = std::gcd (srcRate, dstRate);
+	this->m_p = dstRate / gcd;
+	this->m_q = srcRate / gcd;
+
+	const double cutoff = 0.475 / std::max (this->m_p, this->m_q);
+	const double width = 0.05 / std::max (this->m_p, this->m_q);
+	// -180 dB stop band, the left offset rounded up so the transition doesn't widen
+	const unsigned l = (kaiserOrder (180.0, width) + 1) / 2;
+	const double beta = kaiserBeta (180.0);
+
+	this->m_m = l * 2 + 1;
+	this->m_l = l;
+	this->m_filter.resize (this->m_m);
+
+	for (unsigned i = 0; i < this->m_m; i++) {
+	    this->m_filter[i] = sincFilter (l, beta, this->m_p, cutoff, i);
+	}
+    }
+
+    void process (unsigned inN, const double* in, unsigned outN, double* out) const {
+	const unsigned p = this->m_p, q = this->m_q, m = this->m_m, l = this->m_l;
+	const double* f = this->m_filter.data ();
+
+	for (unsigned i = 0; i < outN; i++) {
+	    // input starts at l to drop the filter delay
+	    size_t jf = (l + q * i) % p;
+	    size_t js = (l + q * i) / p;
+	    double r = 0.0;
+
+	    if (jf < m) {
+		size_t length = (m - jf + p - 1) / p;
+
+		if (js + 1 > inN) {
+		    const size_t skip = std::min<size_t> (js + 1 - inN, length);
+
+		    jf += p * skip;
+		    js -= skip;
+		    length -= skip;
+		}
+
+		for (size_t todo = std::min<size_t> (js + 1, length); todo > 0; todo--) {
+		    r += f[jf] * in[js];
+		    jf += p;
+		    --js;
+		}
+	    }
+
+	    out[i] = r;
+	}
+    }
+
+private:
+    static double sinc (double x) {
+	if (std::abs (x) < 1e-9) {
+	    return 1.0;
+	}
+
+	return std::sin (M_PI * x) / (M_PI * x);
+    }
+
+    static double besselI0 (double x) {
+	const double x2 = x / 2.0;
+	double term = 1.0;
+	double sum = 1.0;
+	double last;
+	int k = 1;
+
+	do {
+	    const double y = x2 / k;
+
+	    ++k;
+	    last = sum;
+	    term *= y * y;
+	    sum += term;
+	} while (sum != last);
+
+	return sum;
+    }
+
+    static double kaiser (double b, double k) {
+	if (!(k >= -1.0 && k <= 1.0)) {
+	    return 0.0;
+	}
+
+	return besselI0 (b * std::sqrt (1.0 - k * k)) / besselI0 (b);
+    }
+
+    static unsigned kaiserOrder (double rejection, double transition) {
+	const double wt = 2.0 * M_PI * transition;
+
+	if (rejection > 21.0) {
+	    return static_cast<unsigned> (std::ceil ((rejection - 7.95) / (2.285 * wt)));
+	}
+
+	return static_cast<unsigned> (std::ceil (5.79 / wt));
+    }
+
+    static double kaiserBeta (double rejection) {
+	if (rejection > 50.0) {
+	    return 0.1102 * (rejection - 8.7);
+	}
+
+	if (rejection >= 21.0) {
+	    return 0.5842 * std::pow (rejection - 21.0, 0.4) + 0.07886 * (rejection - 21.0);
+	}
+
+	return 0.0;
+    }
+
+    static double sincFilter (unsigned l, double b, double gain, double cutoff, unsigned i) {
+	const double x = static_cast<double> (i) - l;
+
+	return kaiser (b, x / l) * 2.0 * gain * cutoff * sinc (2.0 * cutoff * x);
+    }
+
+    unsigned m_p, m_q, m_m, m_l;
+    std::vector<double> m_filter;
+};
+
+class Reader {
+public:
+    Reader (const unsigned char* data, size_t size) : m_data (data), m_size (size) { }
+
+    [[nodiscard]] bool good () const { return this->m_good; }
+
+    unsigned read (unsigned bytes) {
+	if (this->m_offset + bytes > this->m_size) {
+	    this->m_good = false;
+	    return 0;
+	}
+
+	unsigned value = 0;
+
+	for (unsigned i = 0; i < bytes; i++) {
+	    value |= static_cast<unsigned> (this->m_data[this->m_offset++]) << (i * 8);
+	}
+
+	return value;
+    }
+
+    /** readle<int,24> */
+    int read24 () {
+	constexpr int signbit = 1 << 23;
+
+	return (static_cast<int> (this->read (3)) ^ signbit) - signbit;
+    }
+
+private:
+    const unsigned char* m_data;
+    size_t m_size;
+    size_t m_offset = 0;
+    bool m_good = true;
+};
+
+/** LoadHrtf03, the format of the built-in set */
+std::unique_ptr<Store> loadHrtf03 (Reader& data) {
+    auto store = std::make_unique<Store> ();
+
+    store->sampleRate = data.read (4);
+    const unsigned channelType = data.read (1);
+    store->irSize = data.read (1);
+    const unsigned fdCount = data.read (1);
+
+    if (!data.good () || channelType > 1 || store->irSize < MinIrLength || store->irSize > HrirLength || fdCount < 1
+	|| fdCount > 16) {
+	return nullptr;
+    }
+
+    for (unsigned f = 0; f < fdCount; f++) {
+	const unsigned distance = data.read (2);
+	const unsigned evCount = data.read (1);
+
+	if (!data.good () || distance < 50 || distance > 2500 || evCount < 5 || evCount > 181) {
+	    return nullptr;
+	}
+
+	store->fields.push_back ({ static_cast<float> (distance) / 1000.0f, static_cast<uint8_t> (evCount) });
+
+	if (f > 0 && store->fields[f].distance > store->fields[f - 1].distance) {
+	    return nullptr;
+	}
+
+	for (unsigned e = 0; e < evCount; e++) {
+	    const auto azCount = static_cast<uint16_t> (data.read (1));
+
+	    if (azCount < 1) {
+		return nullptr;
+	    }
+
+	    store->elevations.push_back ({ azCount, 0 });
+	}
+    }
+
+    if (!data.good ()) {
+	return nullptr;
+    }
+
+    for (size_t e = 1; e < store->elevations.size (); e++) {
+	const auto& last = store->elevations[e - 1];
+
+	store->elevations[e].irOffset = static_cast<uint16_t> (last.azCount + last.irOffset);
+    }
+
+    const auto irTotal = static_cast<size_t> (store->elevations.back ().azCount + store->elevations.back ().irOffset);
+
+    store->coeffs.assign (irTotal, HrirArray {});
+    store->delays.assign (irTotal, {});
+
+    for (auto& hrir : store->coeffs) {
+	for (unsigned k = 0; k < store->irSize; k++) {
+	    hrir[k][0] = static_cast<float> (data.read24 ()) / 8388608.0f;
+
+	    if (channelType == 1) {
+		hrir[k][1] = static_cast<float> (data.read24 ()) / 8388608.0f;
+	    }
+	}
+    }
+
+    for (auto& delay : store->delays) {
+	delay[0] = static_cast<uint8_t> (data.read (1));
+
+	if (channelType == 1) {
+	    delay[1] = static_cast<uint8_t> (data.read (1));
+	}
+    }
+
+    if (!data.good ()) {
+	return nullptr;
+    }
+
+    for (const auto& delay : store->delays) {
+	if (delay[0] > MaxHrirDelay * HrirDelayFracOne || delay[1] > MaxHrirDelay * HrirDelayFracOne) {
+	    return nullptr;
+	}
+    }
+
+    // left ear only: the right ear's response is the left one mirrored around the median plane
+    if (channelType == 0) {
+	for (const auto& elevation : store->elevations) {
+	    for (size_t j = 0; j < elevation.azCount; j++) {
+		const size_t left = elevation.irOffset + j;
+		const size_t right = elevation.irOffset + (elevation.azCount - j) % elevation.azCount;
+
+		for (size_t k = 0; k < HrirLength; k++) {
+		    store->coeffs[right][k][1] = store->coeffs[left][k][0];
+		}
+
+		store->delays[right][1] = store->delays[left][0];
+	    }
+	}
+    }
+
+    return store;
+}
+
+/** GetLoadedHrtf's conversion to the device rate */
+void resample (Store& store, unsigned deviceRate) {
+    std::array<std::array<double, HrirLength>, 2> inout {};
+    const PolyphaseResampler resampler (store.sampleRate, deviceRate);
+
+    for (auto& coeffs : store.coeffs) {
+	for (size_t j = 0; j < 2; j++) {
+	    for (size_t k = 0; k < HrirLength; k++) {
+		inout[0][k] = coeffs[k][j];
+	    }
+
+	    resampler.process (HrirLength, inout[0].data (), HrirLength, inout[1].data ());
+
+	    for (size_t k = 0; k < HrirLength; k++) {
+		coeffs[k][j] = static_cast<float> (inout[1][k]);
+	    }
+	}
+    }
+
+    // delays scaled for the new rate, shrunk together (a smaller head) if one passes the history length
+    const float rateScale = static_cast<float> (deviceRate) / static_cast<float> (store.sampleRate);
+    std::vector<std::array<float, 2>> delays (store.delays.size ());
+    float maxDelay = 0.0f;
+
+    for (size_t i = 0; i < store.delays.size (); i++) {
+	for (size_t j = 0; j < 2; j++) {
+	    const float delay = std::round (static_cast<float> (store.delays[i][j]) * rateScale)
+		/ static_cast<float> (HrirDelayFracOne);
+
+	    maxDelay = std::max (maxDelay, delay);
+	    delays[i][j] = delay;
+	}
+    }
+
+    float delayScale = HrirDelayFracOne;
+
+    if (maxDelay > MaxHrirDelay) {
+	sLog.debug ("HRTF: resampled delay exceeds the maximum (", maxDelay, " > ", MaxHrirDelay, ")");
+	delayScale *= static_cast<float> (MaxHrirDelay) / maxDelay;
+    }
+
+    for (size_t i = 0; i < store.delays.size (); i++) {
+	for (size_t j = 0; j < 2; j++) {
+	    store.delays[i][j] = static_cast<uint8_t> (static_cast<int> (delays[i][j] * delayScale + 0.5f));
+	}
+    }
+
+    const float irSize = std::round (static_cast<float> (store.irSize) * rateScale);
+
+    store.irSize = static_cast<unsigned> (std::min (static_cast<float> (HrirLength), irSize));
+    store.sampleRate = deviceRate;
+}
+
+struct IdxBlend {
+    unsigned idx;
+    float blend;
+};
+
+IdxBlend evIndex (unsigned evCount, float elevation) {
+    elevation = (Pi * 0.5f + elevation) * static_cast<float> (evCount - 1) / Pi;
+    const unsigned idx = float2uint (elevation);
+
+    return { std::min (idx, evCount - 1), elevation - static_cast<float> (idx) };
+}
+
+IdxBlend azIndex (unsigned azCount, float azimuth) {
+    azimuth = (Tau + azimuth) * static_cast<float> (azCount) / Tau;
+    const unsigned idx = float2uint (azimuth);
+
+    return { idx % azCount, azimuth - static_cast<float> (idx) };
+}
+
+/**
+ * ApplyCoeffs. The DLL mixes with the SSE variant (sub_1801A5EA0/sub_1801A6010), which goes through the taps in
+ * pairs: an odd IR size also gets the next tap of the (resampled, so not zero) response
+ */
+void applyCoeffs (std::array<float, 2>* values, unsigned irSize, const HrirArray& coeffs, float left, float right) {
+    const unsigned taps = (irSize + 1) & ~1u;
+
+    for (unsigned c = 0; c < taps; c++) {
+	values[c][0] += coeffs[c][0] * left;
+	values[c][1] += coeffs[c][1] * right;
+    }
+}
+} // namespace
+
+std::unique_ptr<Store> WallpaperEngine::Audio::Hrtf::loadDefault (unsigned deviceRate) {
+    if (sizeof (DEFAULT_HRTF) < 8 || std::memcmp (DEFAULT_HRTF, "MinPHR03", 8) != 0) {
+	sLog.error ("HRTF: the built-in data set has an unknown header");
+	return nullptr;
+    }
+
+    Reader reader (DEFAULT_HRTF + 8, sizeof (DEFAULT_HRTF) - 8);
+    auto store = loadHrtf03 (reader);
+
+    if (store == nullptr) {
+	sLog.error ("HRTF: failed to read the built-in data set");
+	return nullptr;
+    }
+
+    if (store->sampleRate != deviceRate) {
+	resample (*store, deviceRate);
+    }
+
+    sLog.debug ("HRTF: loaded the built-in data set for ", store->sampleRate, "hz, ", store->irSize, "-sample filter");
+
+    return store;
+}
+
+void WallpaperEngine::Audio::Hrtf::getCoeffs (
+    const Store& store, float elevation, float azimuth, float distance, float spread, Filter& out
+) {
+    const float dirfact = 1.0f - spread / Tau;
+
+    // the first field nearer than the distance, the nearest one at most
+    size_t field = 0;
+    size_t ebase = 0;
+
+    while (distance < store.fields[field].distance && field != store.fields.size () - 1) {
+	ebase += store.fields[field].evCount;
+	++field;
+    }
+
+    const unsigned evCount = store.fields[field].evCount;
+    const auto elev0 = evIndex (evCount, elevation);
+    const size_t elev1 = std::min (elev0.idx + 1, evCount - 1);
+    const auto& e0 = store.elevations[ebase + elev0.idx];
+    const auto& e1 = store.elevations[ebase + elev1];
+    const auto az0 = azIndex (e0.azCount, azimuth);
+    const auto az1 = azIndex (e1.azCount, azimuth);
+
+    const size_t idx[4] = { e0.irOffset + az0.idx, e0.irOffset + (az0.idx + 1) % e0.azCount, e1.irOffset + az1.idx,
+			    e1.irOffset + (az1.idx + 1) % e1.azCount };
+    const float blend[4]
+	= { (1.0f - elev0.blend) * (1.0f - az0.blend) * dirfact, (1.0f - elev0.blend) * az0.blend * dirfact,
+	    elev0.blend * (1.0f - az1.blend) * dirfact, elev0.blend * az1.blend * dirfact };
+
+    for (size_t ear = 0; ear < 2; ear++) {
+	float d = static_cast<float> (store.delays[idx[0]][ear]) * blend[0];
+
+	d += static_cast<float> (store.delays[idx[1]][ear]) * blend[1];
+	d += static_cast<float> (store.delays[idx[2]][ear]) * blend[2];
+	d += static_cast<float> (store.delays[idx[3]][ear]) * blend[3];
+	// fastf2u: cvtss2si, rounded to nearest (0x18018AE8D), not truncated like the indices
+	out.delay[ear] = static_cast<unsigned> (std::lrint (d * (1.0f / HrirDelayFracOne)));
+    }
+
+    out.coeffs = {};
+    out.coeffs[0][0] = PassthruCoeff * (1.0f - dirfact);
+    out.coeffs[0][1] = PassthruCoeff * (1.0f - dirfact);
+
+    for (size_t c = 0; c < 4; c++) {
+	const HrirArray& source = store.coeffs[idx[c]];
+
+	for (size_t k = 0; k < HrirLength; k++) {
+	    out.coeffs[k][0] = source[k][0] * blend[c] + out.coeffs[k][0];
+	    out.coeffs[k][1] = source[k][1] * blend[c] + out.coeffs[k][1];
+	}
+    }
+}
+
+Mixer::Mixer (unsigned irSize) :
+    m_irSize (irSize), m_accum (BufferLineSize + HrirLength + DirectDelay), m_samples (HistoryLength + BufferLineSize) {
+}
+
+void Mixer::mix (
+    Channel& channel, const Filter& target, const float* samples, unsigned count, unsigned counter, unsigned outPos
+) {
+    // voice mixing lands after the direct delay, aligned with the device's own HRTF filtering of the dry buffer
+    auto* accum = this->m_accum.data () + DirectDelay + outPos;
+    float* input = this->m_samples.data ();
+
+    std::copy (channel.history.begin (), channel.history.end (), input);
+    std::copy_n (samples, count, input + HistoryLength);
+    std::copy_n (input + count, HistoryLength, channel.history.begin ());
+
+    if (counter == 0) {
+	channel.old = target;
+    }
+
+    unsigned pos = 0;
+    unsigned fademix = 0;
+
+    // fading: the new response fades in while the old one fades out, in the update's first pass only
+    if (counter > 0 && outPos == 0) {
+	fademix = std::min (count, counter);
+
+	float gain = target.gain;
+
+	if (counter > fademix) {
+	    const float a = static_cast<float> (fademix) / static_cast<float> (counter);
+
+	    gain = channel.old.gain + (target.gain - channel.old.gain) * a;
+	}
+
+	const float newGainStep = gain / static_cast<float> (fademix);
+
+	if (channel.old.gain > 0.00001f) {
+	    const float oldGainStep = channel.old.gain / static_cast<float> (fademix);
+	    size_t left = HistoryLength - channel.old.delay[0];
+	    size_t right = HistoryLength - channel.old.delay[1];
+	    auto stepcount = static_cast<float> (fademix);
+
+	    for (unsigned i = 0; i < fademix; i++) {
+		const float g = oldGainStep * stepcount;
+
+		applyCoeffs (accum + i, this->m_irSize, channel.old.coeffs, input[left++] * g, input[right++] * g);
+		stepcount -= 1.0f;
+	    }
+	}
+
+	if (newGainStep * static_cast<float> (fademix) > 0.00001f) {
+	    size_t left = HistoryLength + 1 - target.delay[0];
+	    size_t right = HistoryLength + 1 - target.delay[1];
+	    float stepcount = 1.0f;
+
+	    for (unsigned i = 1; i < fademix; i++) {
+		const float g = newGainStep * stepcount;
+
+		applyCoeffs (accum + i, this->m_irSize, target.coeffs, input[left++] * g, input[right++] * g);
+		stepcount += 1.0f;
+	    }
+	}
+
+	channel.old = target;
+	channel.old.gain = gain;
+	pos = fademix;
+    }
+
+    if (fademix < count) {
+	const unsigned todo = count - fademix;
+	float gain = target.gain;
+
+	if (counter > count) {
+	    const float a = static_cast<float> (todo) / static_cast<float> (counter - fademix);
+
+	    gain = channel.old.gain + (target.gain - channel.old.gain) * a;
+	}
+
+	const float gainStep = (gain - channel.old.gain) / static_cast<float> (todo);
+	const float* source = input + fademix;
+	size_t left = HistoryLength - target.delay[0];
+	size_t right = HistoryLength - target.delay[1];
+	float stepcount = 0.0f;
+
+	for (unsigned i = 0; i < todo; i++) {
+	    const float g = channel.old.gain + gainStep * stepcount;
+
+	    applyCoeffs (accum + pos + i, this->m_irSize, target.coeffs, source[left++] * g, source[right++] * g);
+	    stepcount += 1.0f;
+	}
+
+	channel.old.gain = gain;
+    }
+}
+
+void Mixer::finish (float* left, float* right, unsigned count) {
+    for (unsigned i = 0; i < count; i++) {
+	left[i] = this->m_accum[i][0];
+	right[i] = this->m_accum[i][1];
+    }
+
+    const auto end = std::copy_n (this->m_accum.begin () + count, HrirLength + DirectDelay, this->m_accum.begin ());
+
+    std::fill_n (end, count, std::array<float, 2> {});
+}
+
+void Mixer::clear () { std::ranges::fill (this->m_accum, std::array<float, 2> {}); }

+ 91 - 0
src/WallpaperEngine/Audio/Hrtf.h

@@ -0,0 +1,91 @@
+#pragma once
+
+#include <array>
+#include <cstdint>
+#include <memory>
+#include <vector>
+
+/**
+ * OpenAL Soft 1.21.1's HRTF renderer, the one WE's mediaextensions64.dll links statically (alc/hrtf.cpp,
+ * core/mixer/hrtfbase.h, alc/voice.cpp DoHrtfMix, common/polyphase_resampler.cpp; LGPL, Chris Robinson). WE
+ * creates its context without attributes, so OpenAL turns HRTF on by itself for a stereo headphones/headset endpoint
+ * (aluInitRenderer sub_1801990F0, WASAPI form factor 3 or 5 in sub_180186400) and renders in its default "full" mode:
+ * every voice is convolved with the built-in KEMAR data set (embedded byte for byte in the DLL), resampled to the
+ * device rate.
+ */
+namespace WallpaperEngine::Audio::Hrtf {
+constexpr unsigned HistoryLength = 64;
+constexpr unsigned HrirLength = 128;
+constexpr unsigned DirectDelay = 256;
+/** OpenAL Soft's mixing granularity, the most samples one update mixes */
+constexpr unsigned BufferLineSize = 1024;
+
+using HrirArray = std::array<std::array<float, 2>, HrirLength>;
+
+struct Store {
+    unsigned sampleRate = 0;
+    unsigned irSize = 0;
+
+    struct Field {
+	float distance;
+	uint8_t evCount;
+    };
+
+    struct Elevation {
+	uint16_t azCount;
+	uint16_t irOffset;
+    };
+
+    /** stored backwards like OpenAL: the farthest field first */
+    std::vector<Field> fields;
+    std::vector<Elevation> elevations;
+    std::vector<HrirArray> coeffs;
+    std::vector<std::array<uint8_t, 2>> delays;
+};
+
+/** The built-in data set ("Built-In HRTF") loaded for the given output rate, nullptr if it can't be read */
+std::unique_ptr<Store> loadDefault (unsigned deviceRate);
+
+struct Filter {
+    alignas (16) HrirArray coeffs {};
+    std::array<unsigned, 2> delay {};
+    float gain = 0.0f;
+};
+
+/** GetHrtfCoeffs: blended impulse response and delays for a direction (radians), normalized like OpenAL's */
+void getCoeffs (const Store& store, float elevation, float azimuth, float distance, float spread, Filter& out);
+
+/** Mixing state of one input channel of a voice */
+struct Channel {
+    std::array<float, HistoryLength> history {};
+    Filter old {};
+};
+
+/** The device side: the accumulation buffer every voice convolves into, read out with OpenAL's direct delay */
+class Mixer {
+public:
+    explicit Mixer (unsigned irSize);
+
+    /**
+     * DoHrtfMix for one channel over one mixing pass of count samples (at most BufferLineSize).
+     *
+     * @param counter OpenAL's fade counter: 0 on a voice's first update (no fade), the update size after that, minus
+     * what earlier passes of the update mixed
+     * @param outPos where the pass starts in the update, the IR crossfade only happens in the first pass
+     */
+    void mix (
+	Channel& channel, const Filter& target, const float* samples, unsigned count, unsigned counter,
+	unsigned outPos = 0
+    );
+    /** ProcessHrtf without ambisonic input: count samples of left/right out, then shifts the accumulator */
+    void finish (float* left, float* right, unsigned count);
+    void clear ();
+
+    [[nodiscard]] unsigned irSize () const { return this->m_irSize; }
+
+private:
+    unsigned m_irSize;
+    std::vector<std::array<float, 2>> m_accum;
+    std::vector<float> m_samples;
+};
+} // namespace WallpaperEngine::Audio::Hrtf

+ 6 - 0
src/WallpaperEngine/Audio/resources/DefaultHrtf.generated.h.in

@@ -0,0 +1,6 @@
+// This file is auto-generated from default_hrtf.mhr by CMake (configure_file). Do not edit.
+#pragma once
+
+namespace WallpaperEngine::Audio::Hrtf {
+inline constexpr unsigned char DEFAULT_HRTF[] = { @WPENGINE_DEFAULT_HRTF_BYTES@ };
+} // namespace WallpaperEngine::Audio::Hrtf

BIN
src/WallpaperEngine/Audio/resources/default_hrtf.mhr


+ 2 - 0
src/WallpaperEngine/Data/Model/Object.h

@@ -181,6 +181,8 @@ struct SoundData {
     UserSettingUniquePtr attenuation;
     UserSettingUniquePtr mindistance;
     UserSettingUniquePtr spatialization;
+    /** only means something in WE's editor, scripts can read it */
+    UserSettingUniquePtr muteineditor;
 };
 
 class Sound : public Object, public SoundData {

+ 9 - 0
src/WallpaperEngine/Data/Model/Wallpaper.h

@@ -153,6 +153,15 @@ struct SceneData {
 	UserSettingUniquePtr windDirection;
 	UserSettingUniquePtr windStrength;
     } physics;
+    /** Which of WE's own user properties scripts get with the project's (flags sub_14010DF40 hands sub_140104B60) */
+    struct EngineProperties {
+	/** "volume": an object has a "sound" and no "model" */
+	bool volume;
+	/** "alignment*": "orthogonalprojection" is an object, a 2D scene */
+	bool alignment;
+	/** "cameraparallax": true with a non-zero "cameraparallaxmouseinfluence", user bindings don't count */
+	bool cameraParallax;
+    } engineProperties;
 
     ObjectList objects;
 };

+ 1 - 0
src/WallpaperEngine/Data/Parsers/ObjectParser.cpp

@@ -651,6 +651,7 @@ SoundUniquePtr ObjectParser::parseSound (const JSON& it, const Project& project,
 	    .attenuation = it.user ("attenuation", project.properties, 1.0f),
 	    .mindistance = it.user ("mindistance", project.properties, 1.0f),
 	    .spatialization = it.user ("spatialization", project.properties, false),
+	    .muteineditor = it.user ("muteineditor", project.properties, false),
 	}
     );
 }

+ 37 - 0
src/WallpaperEngine/Data/Parsers/WallpaperParser.cpp

@@ -264,6 +264,42 @@ std::vector<CameraPath> parseCameraPaths (const JSON& camera, const Project& pro
 
     return paths;
 }
+// a general member's value the way sub_14010D850 reads it: {"value": ...} objects unwrapped, nullptr when missing
+const JSON* generalValue (const JSON& general, const char* name) {
+    const auto it = general.find (name);
+
+    if (it == general.end () || !it->is_object ()) {
+	return it == general.end () ? nullptr : &*it;
+    }
+
+    const auto value = it->find ("value");
+    return value == it->end () ? nullptr : &*value;
+}
+
+SceneData::EngineProperties parseEngineProperties (const JSON& general, const JSON& objects, bool perspective) {
+    SceneData::EngineProperties result { .volume = false, .alignment = !perspective, .cameraParallax = false };
+
+    for (const auto& object : objects) {
+	if (!object.is_object ()) {
+	    continue;
+	}
+
+	const auto model = object.find ("model");
+	const auto sound = object.find ("sound");
+
+	if ((model == object.end () || model->is_null ()) && sound != object.end () && !sound->is_null ()) {
+	    result.volume = true;
+	}
+    }
+
+    const auto* parallax = generalValue (general, "cameraparallax");
+    const auto* influence = generalValue (general, "cameraparallaxmouseinfluence");
+
+    result.cameraParallax = parallax != nullptr && parallax->is_boolean () && parallax->get<bool> ()
+	&& influence != nullptr && influence->is_number () && influence->get<float> () != 0.0f;
+
+    return result;
+}
 } // namespace
 
 WallpaperUniquePtr WallpaperParser::parse (const JSON& file, Project& project) {
@@ -374,6 +410,7 @@ SceneUniquePtr WallpaperParser::parseScene (const JSON& file, Project& project)
                 .windDirection = general.user ("winddirection", properties, glm::vec3 (0.70710677f, 0.70710677f, 0.0f)),
                 .windStrength = general.user ("windstrength", properties, 1.0f),
             },
+            .engineProperties = parseEngineProperties (general, objects, perspective),
             .objects = parseObjects (objects, project),
         }
     );

+ 1 - 31
src/WallpaperEngine/Desktop/GnomeShell.cpp

@@ -143,36 +143,6 @@ GnomeShell::GnomeShell () {
     this->m_available = this->queryState ();
 }
 
-namespace {
-int receiveDescriptor (int connection) {
-    char byte = 0;
-    iovec data = { .iov_base = &byte, .iov_len = 1 };
-    union {
-	char buffer[CMSG_SPACE (sizeof (int))];
-	cmsghdr align;
-    } control {};
-    msghdr message = {};
-    message.msg_iov = &data;
-    message.msg_iovlen = 1;
-    message.msg_control = control.buffer;
-    message.msg_controllen = sizeof (control.buffer);
-
-    if (recvmsg (connection, &message, MSG_CMSG_CLOEXEC) != 1) {
-	return -1;
-    }
-
-    const cmsghdr* header = CMSG_FIRSTHDR (&message);
-
-    if (header == nullptr || header->cmsg_level != SOL_SOCKET || header->cmsg_type != SCM_RIGHTS) {
-	return -1;
-    }
-
-    int fd = -1;
-    std::memcpy (&fd, CMSG_DATA (header), sizeof (int));
-    return fd;
-}
-} // namespace
-
 int GnomeShell::openWaylandSocket () {
     const std::string directory = runtimeDirectory ();
 
@@ -182,7 +152,7 @@ int GnomeShell::openWaylandSocket () {
 	return -1;
     }
 
-    const std::string path = directory + "/lwe-gnome-" + std::to_string (getpid ()) + ".sock";
+    const std::string path = directory + "/lwe-gnome-" + processTag () + ".sock";
     sockaddr_un address = {};
     address.sun_family = AF_UNIX;
 

+ 183 - 0
src/WallpaperEngine/Desktop/HostWayland.cpp

@@ -0,0 +1,183 @@
+#include "HostWayland.h"
+
+#include "GnomeShell.h"
+#include "SessionBus.h"
+#include "WallpaperEngine/Logging/Log.h"
+
+#include <atomic>
+#include <cstring>
+#include <filesystem>
+#include <poll.h>
+#include <string_view>
+#include <sys/socket.h>
+#include <sys/stat.h>
+#include <sys/un.h>
+#include <sys/wait.h>
+#include <unistd.h>
+#include <vector>
+#include <wayland-client.h>
+
+namespace {
+constexpr int HELPER_TIMEOUT_MS = 5000;
+constexpr const char* HELPER = "gnome-shell-extension/linux-wallpaperengine@wallpaperenginelover.github.io/"
+			       "linux-wallpaperengine-gnome-helper";
+
+// the helpers live until these close, which is when the engine goes
+std::vector<int> g_helperConnections;
+std::atomic<int> g_helperCounter { 0 };
+
+void onGlobal (void* data, wl_registry*, uint32_t, const char* interface, uint32_t) {
+    if (std::string_view (interface) == "zwlr_layer_shell_v1") {
+	*static_cast<bool*> (data) = true;
+    }
+}
+
+void onGlobalRemove (void*, wl_registry*, uint32_t) { }
+
+constexpr wl_registry_listener probeListener = { .global = onGlobal, .global_remove = onGlobalRemove };
+
+bool sandboxSocketHasLayerShell () {
+    wl_display* display = wl_display_connect (nullptr);
+    if (display == nullptr) {
+	return true;
+    }
+
+    bool found = false;
+    wl_registry* registry = wl_display_get_registry (display);
+    wl_registry_add_listener (registry, &probeListener, &found);
+    wl_display_roundtrip (display);
+    wl_registry_destroy (registry);
+    wl_display_disconnect (display);
+    return found;
+}
+
+/** the helper next to this binary, as the host sees it through the app's deployment folder */
+std::string hostHelperPath () {
+    std::error_code error;
+    const auto exe = std::filesystem::read_symlink ("/proc/self/exe", error);
+    const auto helper = exe.parent_path () / HELPER;
+    const std::string appPath = WallpaperEngine::Desktop::flatpakInfo ("app-path");
+
+    if (error || appPath.empty () || !std::filesystem::exists (helper, error)) {
+	return {};
+    }
+
+    const std::string inside = helper.string ();
+    return inside.starts_with ("/app/") ? appPath + inside.substr (4) : std::string {};
+}
+
+/** flatpak-spawn as a grandchild, so the sandbox's init reaps it and nothing waits here */
+bool spawnDetached (const std::vector<std::string>& arguments) {
+    // built before fork, the children of a threaded process must not allocate
+    std::vector<char*> argv;
+    for (const auto& argument : arguments) {
+	argv.push_back (const_cast<char*> (argument.c_str ()));
+    }
+    argv.push_back (nullptr);
+
+    const pid_t child = fork ();
+
+    if (child < 0) {
+	return false;
+    }
+
+    if (child == 0) {
+	if (fork () == 0) {
+	    execvp (argv[0], argv.data ());
+	}
+	_exit (0);
+    }
+
+    waitpid (child, nullptr, 0);
+    return true;
+}
+
+int hostConnection () {
+    const std::string helper = hostHelperPath ();
+    const std::string directory = WallpaperEngine::Desktop::runtimeDirectory ();
+    const char* display = std::getenv ("WAYLAND_DISPLAY");
+
+    if (helper.empty () || directory.empty ()) {
+	sLog.error ("No Wayland helper to reach the compositor from the host");
+	return -1;
+    }
+
+    // the app's runtime folder is the same path on the host
+    const std::string path = directory + "/lwe-wayland-" + WallpaperEngine::Desktop::processTag () + "-"
+	+ std::to_string (g_helperCounter.fetch_add (1)) + ".sock";
+    sockaddr_un address = {};
+    address.sun_family = AF_UNIX;
+
+    if (path.size () >= sizeof (address.sun_path)) {
+	return -1;
+    }
+
+    std::strncpy (address.sun_path, path.c_str (), sizeof (address.sun_path) - 1);
+    unlink (path.c_str ());
+
+    const int listener = socket (AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0);
+    const mode_t mask = umask (0077);
+    const bool bound = listener >= 0 && bind (listener, reinterpret_cast<sockaddr*> (&address), sizeof (address)) == 0
+	&& listen (listener, 1) == 0;
+    umask (mask);
+
+    int fd = -1;
+
+    if (bound) {
+	// Flatpak keeps the host's name for the sandbox's socket unless it is a path or doesn't start with "wayland-",
+	// then the sandbox gets "wayland-0". That one is left to the host's own WAYLAND_DISPLAY (libwayland's default
+	// is wayland-0 too)
+	const std::string name = std::filesystem::path (display != nullptr ? display : "wayland-0").filename ();
+	const char* runtime = std::getenv ("XDG_RUNTIME_DIR");
+	std::vector<std::string> arguments { "flatpak-spawn", "--host" };
+
+	if (name != "wayland-0") {
+	    arguments.push_back ("--env=WAYLAND_DISPLAY=" + name);
+	}
+
+	arguments.push_back (std::string ("--env=XDG_RUNTIME_DIR=") + (runtime != nullptr ? runtime : ""));
+	arguments.push_back (helper);
+	arguments.push_back (path);
+	spawnDetached (arguments);
+
+	pollfd waiting = { .fd = listener, .events = POLLIN, .revents = 0 };
+	if (poll (&waiting, 1, HELPER_TIMEOUT_MS) == 1) {
+	    const int connection = accept4 (listener, nullptr, nullptr, SOCK_CLOEXEC);
+	    fd = connection >= 0 ? WallpaperEngine::Desktop::receiveDescriptor (connection) : -1;
+
+	    if (fd >= 0) {
+		g_helperConnections.push_back (connection);
+	    } else if (connection >= 0) {
+		close (connection);
+	    }
+	}
+    }
+
+    if (listener >= 0) {
+	close (listener);
+    }
+    unlink (path.c_str ());
+
+    if (fd < 0) {
+	sLog.error ("The host helper never handed over a Wayland connection");
+    }
+
+    return fd;
+}
+} // namespace
+
+bool WallpaperEngine::Desktop::usesHostWayland () {
+    static const bool host
+	= access ("/.flatpak-info", F_OK) == 0 && !isGnomeSession () && !sandboxSocketHasLayerShell ();
+    return host;
+}
+
+wl_display* WallpaperEngine::Desktop::connectWayland () {
+    if (usesHostWayland ()) {
+	if (const int fd = hostConnection (); fd >= 0) {
+	    return wl_display_connect_to_fd (fd);
+	}
+    }
+
+    return wl_display_connect (nullptr);
+}

+ 17 - 0
src/WallpaperEngine/Desktop/HostWayland.h

@@ -0,0 +1,17 @@
+#pragma once
+
+struct wl_display;
+
+namespace WallpaperEngine::Desktop {
+/**
+ * A Wayland connection for the engine. Inside a Flatpak the compositor sees the app through Flatpak's
+ * wp_security_context socket, and Hyprland (and other wlroots compositors) hide zwlr_layer_shell_v1 and the foreign
+ * toplevel list from sandboxed clients. When that socket has no layer shell, the connection comes from the helper
+ * started on the host through flatpak-spawn, which connects to the compositor's own socket and hands it over. The app
+ * can run host commands anyway (org.freedesktop.Flatpak), this gains nothing it didn't have. Null on failure.
+ */
+wl_display* connectWayland ();
+
+/** Whether connectWayland goes through the host helper, decided on first use */
+bool usesHostWayland ();
+} // namespace WallpaperEngine::Desktop

+ 136 - 0
src/WallpaperEngine/Desktop/HyprlandIPC.cpp

@@ -0,0 +1,136 @@
+#include "HyprlandIPC.h"
+
+#include <algorithm>
+#include <cctype>
+#include <cstring>
+#include <filesystem>
+#include <fstream>
+#include <sys/socket.h>
+#include <sys/time.h>
+#include <sys/un.h>
+#include <unistd.h>
+
+namespace {
+int connectTo (const std::string& socketPath) {
+    sockaddr_un addr {};
+    if (socketPath.size () >= sizeof (addr.sun_path)) {
+	return -1;
+    }
+
+    const int fd = socket (AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0);
+    if (fd < 0) {
+	return -1;
+    }
+
+    timeval timeout {};
+    timeout.tv_usec = 50000;
+    addr.sun_family = AF_UNIX;
+    std::strncpy (addr.sun_path, socketPath.c_str (), sizeof (addr.sun_path) - 1);
+
+    if (setsockopt (fd, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof (timeout)) != 0
+	|| setsockopt (fd, SOL_SOCKET, SO_SNDTIMEO, &timeout, sizeof (timeout)) != 0
+	|| connect (fd, reinterpret_cast<sockaddr*> (&addr), sizeof (addr)) != 0) {
+	close (fd);
+	return -1;
+    }
+
+    return fd;
+}
+
+/** the leftover socket of a crashed Hyprland refuses connections */
+bool isLive (const std::string& socketPath) {
+    const int fd = connectTo (socketPath);
+    if (fd < 0) {
+	return false;
+    }
+
+    close (fd);
+    return true;
+}
+
+/** hyprland.lock: the compositor's pid, then its Wayland socket name */
+std::string lockedDisplay (const std::filesystem::path& instance) {
+    std::ifstream lock (instance / "hyprland.lock");
+    std::string pid;
+    std::string display;
+    std::getline (lock, pid);
+    std::getline (lock, display);
+    return display;
+}
+/** XDG_CURRENT_DESKTOP is a colon separated list, Hyprland puts "Hyprland" in it */
+bool onHyprland (const char* currentDesktop) {
+    if (currentDesktop == nullptr) {
+	return false;
+    }
+
+    std::string lowered (currentDesktop);
+    std::ranges::transform (lowered, lowered.begin (), [] (unsigned char c) { return std::tolower (c); });
+    return lowered.find ("hyprland") != std::string::npos;
+}
+} // namespace
+
+std::string WallpaperEngine::Desktop::findHyprlandSocket (
+    const std::string& runtimeDir, const char* signature, const char* waylandDisplay, const char* currentDesktop
+) {
+    if (runtimeDir.empty ()) {
+	return {};
+    }
+
+    const std::filesystem::path instances = std::filesystem::path (runtimeDir) / "hypr";
+    std::error_code error;
+
+    if (signature != nullptr && *signature != '\0') {
+	if (const auto socket = instances / signature / ".socket.sock"; std::filesystem::exists (socket, error)) {
+	    return socket.string ();
+	}
+    }
+
+    // WAYLAND_DISPLAY can be a path, the lock has the bare name
+    const std::string display
+	= waylandDisplay != nullptr ? std::filesystem::path (waylandDisplay).filename ().string () : std::string {};
+    std::string newest;
+    std::filesystem::file_time_type newestTime {};
+
+    for (const auto& entry : std::filesystem::directory_iterator (instances, error)) {
+	const auto socket = entry.path () / ".socket.sock";
+	if (!isLive (socket.string ())) {
+	    continue;
+	}
+
+	if (!display.empty () && lockedDisplay (entry.path ()) == display) {
+	    return socket.string ();
+	}
+
+	const auto time = std::filesystem::last_write_time (entry.path () / "hyprland.lock", error);
+	if (newest.empty () || (!error && time > newestTime)) {
+	    newest = socket.string ();
+	    newestTime = error ? newestTime : time;
+	}
+    }
+
+    return onHyprland (currentDesktop) ? newest : std::string {};
+}
+
+std::optional<std::string>
+WallpaperEngine::Desktop::hyprlandRequest (const std::string& socketPath, const std::string& request) {
+    const int fd = connectTo (socketPath);
+    if (fd < 0) {
+	return std::nullopt;
+    }
+
+    if (send (fd, request.data (), request.size (), MSG_NOSIGNAL) < 0) {
+	close (fd);
+	return std::nullopt;
+    }
+    shutdown (fd, SHUT_WR);
+
+    std::string response;
+    char buffer[256];
+    ssize_t readBytes = 0;
+    while ((readBytes = recv (fd, buffer, sizeof (buffer), 0)) > 0) {
+	response.append (buffer, static_cast<std::size_t> (readBytes));
+    }
+    close (fd);
+
+    return response;
+}

+ 19 - 0
src/WallpaperEngine/Desktop/HyprlandIPC.h

@@ -0,0 +1,19 @@
+#pragma once
+
+#include <optional>
+#include <string>
+
+namespace WallpaperEngine::Desktop {
+/**
+ * The request socket of the Hyprland we run on, empty when there is none. HYPRLAND_INSTANCE_SIGNATURE names it; without
+ * the variable (a Flatpak started outside the session's environment) or when it names a gone instance, the live ones in
+ * $XDG_RUNTIME_DIR/hypr are looked at: the one whose hyprland.lock names our Wayland display, else the newest, but that
+ * one only when XDG_CURRENT_DESKTOP (currentDesktop) names Hyprland, a nested or other session's instance isn't ours
+ */
+std::string findHyprlandSocket (
+    const std::string& runtimeDir, const char* signature, const char* waylandDisplay, const char* currentDesktop
+);
+
+/** Sends one request ("j/cursorpos") and returns the whole reply, nullopt when the socket doesn't answer */
+std::optional<std::string> hyprlandRequest (const std::string& socketPath, const std::string& request);
+} // namespace WallpaperEngine::Desktop

+ 53 - 0
src/WallpaperEngine/Desktop/SessionBus.cpp

@@ -1,7 +1,10 @@
 #include "SessionBus.h"
 
 #include <cstdlib>
+#include <cstring>
 #include <filesystem>
+#include <fstream>
+#include <sys/socket.h>
 #include <unistd.h>
 
 namespace {
@@ -33,6 +36,28 @@ std::string WallpaperEngine::Desktop::runtimeDirectory () {
     return dir;
 }
 
+std::string WallpaperEngine::Desktop::flatpakInfo (const std::string& key) {
+    std::ifstream info ("/.flatpak-info");
+    std::string line;
+
+    while (std::getline (info, line)) {
+	if (line.starts_with (key + "=")) {
+	    return line.substr (key.size () + 1);
+	}
+    }
+
+    return {};
+}
+
+std::string WallpaperEngine::Desktop::processTag () {
+    static const std::string instance = [] {
+	const std::string id = flatpakInfo ("instance-id");
+	return id.empty () ? id : id + "_";
+    }();
+
+    return instance + std::to_string (getpid ());
+}
+
 DBusMessage*
 WallpaperEngine::Desktop::callBlocking (DBusConnection* connection, DBusMessage* call, std::string& error) {
     DBusError dbusError;
@@ -70,3 +95,31 @@ bool WallpaperEngine::Desktop::drainBus (DBusConnection* connection) {
 
     return true;
 }
+
+int WallpaperEngine::Desktop::receiveDescriptor (int connection) {
+    char byte = 0;
+    iovec data = { .iov_base = &byte, .iov_len = 1 };
+    union {
+	char buffer[CMSG_SPACE (sizeof (int))];
+	cmsghdr align;
+    } control {};
+    msghdr message = {};
+    message.msg_iov = &data;
+    message.msg_iovlen = 1;
+    message.msg_control = control.buffer;
+    message.msg_controllen = sizeof (control.buffer);
+
+    if (recvmsg (connection, &message, MSG_CMSG_CLOEXEC) != 1) {
+	return -1;
+    }
+
+    const cmsghdr* header = CMSG_FIRSTHDR (&message);
+
+    if (header == nullptr || header->cmsg_level != SOL_SOCKET || header->cmsg_type != SCM_RIGHTS) {
+	return -1;
+    }
+
+    int fd = -1;
+    std::memcpy (&fd, CMSG_DATA (header), sizeof (int));
+    return fd;
+}

+ 12 - 0
src/WallpaperEngine/Desktop/SessionBus.h

@@ -7,6 +7,18 @@ namespace WallpaperEngine::Desktop {
 /** XDG_RUNTIME_DIR, inside a Flatpak the app's folder in it (the one the host shares); empty when unset */
 std::string runtimeDirectory ();
 
+/** A key of /.flatpak-info's [Instance] group (instance-id, app-path, ...), empty outside a Flatpak or when missing */
+std::string flatpakInfo (const std::string& key);
+
+/**
+ * This process in names other processes see (D-Bus names, KWin scripts, sockets, shm): the pid, inside a Flatpak
+ * "<instance id>_<pid>", since every run of a Flatpak has a pid namespace of its own and pids repeat between them
+ */
+std::string processTag ();
+
+/** The descriptor sent along one byte over a unix socket (SCM_RIGHTS), -1 on failure */
+int receiveDescriptor (int connection);
+
 /** Blocking call with a 2s timeout, takes ownership of call. Null with error set on failure */
 DBusMessage* callBlocking (DBusConnection* connection, DBusMessage* call, std::string& error);
 

+ 3 - 3
src/WallpaperEngine/Input/Drivers/KDECursorInput.cpp

@@ -48,7 +48,7 @@ bool KDECursorInput::initializeDBus () {
     dbus_connection_set_exit_on_disconnect (m_connection, false);
 
     dbus_error_init (&error);
-    const std::string serviceName = std::string (kServiceName) + "_" + std::to_string (getpid ());
+    const std::string serviceName = std::string (kServiceName) + "_" + WallpaperEngine::Desktop::processTag ();
     const auto requestResult
 	= dbus_bus_request_name (m_connection, serviceName.c_str (), DBUS_NAME_FLAG_DO_NOT_QUEUE, &error);
 
@@ -92,7 +92,7 @@ void KDECursorInput::stopDBus () {
 }
 
 bool KDECursorInput::loadKWinScript () {
-    const std::string serviceName = std::string (kServiceName) + "_" + std::to_string (getpid ());
+    const std::string serviceName = std::string (kServiceName) + "_" + WallpaperEngine::Desktop::processTag ();
 
     std::ostringstream script;
     script << "function lweReportCursorPos() {\n"
@@ -104,7 +104,7 @@ bool KDECursorInput::loadKWinScript () {
 	   << "lweReportCursorPos();\n";
 
     this->m_script = std::make_unique<WallpaperEngine::Desktop::KWinScript> (
-	m_connection, "lwe-cursor-input-" + std::to_string (getpid ()), script.str ()
+	m_connection, "lwe-cursor-input-" + WallpaperEngine::Desktop::processTag (), script.str ()
     );
 
     return this->m_script->isLoaded ();

+ 83 - 52
src/WallpaperEngine/Input/Drivers/WaylandMouseInput.cpp

@@ -1,16 +1,13 @@
 #include "WaylandMouseInput.h"
+#include "WallpaperEngine/Desktop/HyprlandIPC.h"
 #include "WallpaperEngine/Input/ForwardedButton.h"
 #include "WallpaperEngine/Render/Drivers/WaylandOpenGLDriver.h"
 #include <chrono>
 #include <cstdlib>
-#include <cstring>
+#include <filesystem>
 #include <glm/common.hpp>
 #include <regex>
 #include <string>
-#include <sys/socket.h>
-#include <sys/time.h>
-#include <sys/un.h>
-#include <unistd.h>
 
 #ifdef ENABLE_X11
 #include <X11/Xlib.h>
@@ -30,6 +27,17 @@ WaylandMouseInput::WaylandMouseInput (const WallpaperEngine::Render::Drivers::Wa
 	this->m_kdeCursor = std::make_unique<KDECursorInput> ();
     }
 #endif /* ENABLE_KDE_FEATURES */
+
+    this->m_hyprlandSocket = findHyprlandSocket ();
+    this->m_lastHyprlandLookup = std::chrono::steady_clock::now ();
+}
+
+std::string WaylandMouseInput::findHyprlandSocket () {
+    const char* runtime = std::getenv ("XDG_RUNTIME_DIR");
+    return WallpaperEngine::Desktop::findHyprlandSocket (
+	runtime != nullptr ? runtime : "", std::getenv ("HYPRLAND_INSTANCE_SIGNATURE"), std::getenv ("WAYLAND_DISPLAY"),
+	std::getenv ("XDG_CURRENT_DESKTOP")
+    );
 }
 
 void WaylandMouseInput::pollForwardedInput () {
@@ -96,14 +104,19 @@ bool WaylandMouseInput::hasGlobalCursor () const {
     }
 #endif /* ENABLE_KDE_FEATURES */
 
-    return std::getenv ("HYPRLAND_INSTANCE_SIGNATURE") != nullptr;
+    return !this->m_hyprlandSocket.empty ();
 }
 
 glm::dvec2
 WaylandMouseInput::positionOn (const WallpaperEngine::Render::Drivers::Output::WaylandOutputViewport& viewport) const {
-    const double scale = viewport.scale;
+    const double scale = viewport.renderScale ();
+    const auto fromDesktop = [&viewport, scale] (const glm::dvec2& desktop) -> glm::dvec2 {
+	const glm::dvec2 local = desktop - glm::dvec2 (viewport.globalPosition);
+	return { local.x * scale, (viewport.size.y - local.y) * scale };
+    };
 
-    // WE maps GetCursorPos to each wallpaper window's client coords (sub_140110630), even off that output
+    // WE maps GetCursorPos to each wallpaper window's client coords (sub_140110630), even off that output: a pointer
+    // on another monitor gives coordinates outside this one (live WE under Wine, tools/wecompare/wine/we_span.sh)
     if (const auto* gnomeShell = this->m_waylandDriver.getGnomeShell ()) {
 	for (const auto& [output, fraction] : gnomeShell->pointer ()) {
 	    if (output == viewport.name) {
@@ -111,7 +124,8 @@ WaylandMouseInput::positionOn (const WallpaperEngine::Render::Drivers::Output::W
 	    }
 	}
 
-	return { 0, 0 };
+	const auto desktop = this->desktopPosition ();
+	return desktop.has_value () ? fromDesktop (*desktop) : glm::dvec2 { 0, 0 };
     }
 
     if (this->m_waylandDriver.viewportInFocus == &viewport) {
@@ -120,8 +134,14 @@ WaylandMouseInput::positionOn (const WallpaperEngine::Render::Drivers::Output::W
 
     // prefer this surface's own position over a stale XWayland one
     if (this->m_globalCursor.has_value () && !(this->m_globalCursorFromX11 && viewport.pointerEntered)) {
-	const glm::dvec2 local = *this->m_globalCursor - glm::dvec2 (viewport.globalPosition);
-	return { local.x * scale, (viewport.size.y - local.y) * scale };
+	return fromDesktop (*this->m_globalCursor);
+    }
+
+    // the pointer is on another output's surface of ours, whose position is as fresh as it gets
+    if (this->m_waylandDriver.viewportInFocus != nullptr) {
+	if (const auto desktop = this->desktopPosition ()) {
+	    return fromDesktop (*desktop);
+	}
     }
 
     return viewport.mousePos;
@@ -158,6 +178,44 @@ WallpaperEngine::Input::MouseClickStatus WaylandMouseInput::leftClick () const {
     return MouseClickStatus::Released;
 }
 
+std::optional<glm::dvec2> WaylandMouseInput::desktopPosition () const {
+    if (!this->m_waylandDriver.getApp ().getContext ().settings.mouse.enabled) {
+	return std::nullopt;
+    }
+
+    if (const auto* gnomeShell = this->m_waylandDriver.getGnomeShell ()) {
+	for (const auto& [output, fraction] : gnomeShell->pointer ()) {
+	    for (const auto* viewport : this->m_waylandDriver.m_screens) {
+		if (viewport && viewport->name == output) {
+		    return glm::dvec2 (viewport->globalPosition) + fraction * glm::dvec2 (viewport->size);
+		}
+	    }
+	}
+
+	return std::nullopt;
+    }
+
+    if (const auto* viewport = this->m_waylandDriver.viewportInFocus) {
+	const glm::dvec2 local = viewport->mousePos / viewport->renderScale ();
+	return glm::dvec2 (viewport->globalPosition) + glm::dvec2 { local.x, viewport->size.y - local.y };
+    }
+
+    return this->m_globalCursor;
+}
+
+WallpaperEngine::Input::MouseClickStatus WaylandMouseInput::desktopLeftClick () const {
+    const auto click = this->leftClick ();
+    const auto* viewport = this->m_waylandDriver.viewportInFocus;
+
+    // leftClick () only looks at the output being rendered, the press may be on another output of the span
+    if (click == MouseClickStatus::Released && viewport != nullptr
+	&& this->m_waylandDriver.getApp ().getContext ().settings.mouse.enabled) {
+	return viewport->leftClick;
+    }
+
+    return click;
+}
+
 const WallpaperEngine::Render::Drivers::Output::WaylandOutputViewport*
 WaylandMouseInput::getActiveOutputViewport () const {
     if (this->m_waylandDriver.viewportInFocus && this->m_waylandDriver.viewportInFocus->rendering) {
@@ -173,55 +231,28 @@ WaylandMouseInput::getActiveOutputViewport () const {
     return nullptr;
 }
 
-std::optional<glm::dvec2> WaylandMouseInput::queryHyprlandCursorPosition () const {
-    const char* signature = std::getenv ("HYPRLAND_INSTANCE_SIGNATURE");
-    const char* runtime = std::getenv ("XDG_RUNTIME_DIR");
-    if (!signature || !runtime) {
-	return std::nullopt;
-    }
+std::optional<glm::dvec2> WaylandMouseInput::queryHyprlandCursorPosition () {
+    std::error_code error;
 
-    const std::string socketPath = std::string (runtime) + "/hypr/" + signature + "/.socket.sock";
-
-    int fd = socket (AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0);
-    if (fd < 0) {
-	return std::nullopt;
-    }
-
-    timeval timeout {};
-    timeout.tv_usec = 50000;
-    if (setsockopt (fd, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof (timeout)) != 0
-	|| setsockopt (fd, SOL_SOCKET, SO_SNDTIMEO, &timeout, sizeof (timeout)) != 0) {
-	close (fd);
-	return std::nullopt;
-    }
-
-    sockaddr_un addr {};
-    addr.sun_family = AF_UNIX;
-    if (socketPath.size () >= sizeof (addr.sun_path)) {
-	close (fd);
-	return std::nullopt;
+    // Hyprland restarted, or it wasn't up yet when the engine started
+    if (this->m_hyprlandSocket.empty () || !std::filesystem::exists (this->m_hyprlandSocket, error)) {
+	const auto now = std::chrono::steady_clock::now ();
+	if (now - this->m_lastHyprlandLookup < std::chrono::seconds (1)) {
+	    return std::nullopt;
+	}
+	this->m_lastHyprlandLookup = now;
+	this->m_hyprlandSocket = findHyprlandSocket ();
     }
-    std::strncpy (addr.sun_path, socketPath.c_str (), sizeof (addr.sun_path) - 1);
 
-    if (connect (fd, reinterpret_cast<sockaddr*> (&addr), sizeof (addr)) != 0) {
-	close (fd);
+    if (this->m_hyprlandSocket.empty ()) {
 	return std::nullopt;
     }
 
-    constexpr const char* request = "j/cursorpos";
-    if (send (fd, request, std::strlen (request), MSG_NOSIGNAL) < 0) {
-	close (fd);
+    const auto reply = WallpaperEngine::Desktop::hyprlandRequest (this->m_hyprlandSocket, "j/cursorpos");
+    if (!reply.has_value ()) {
 	return std::nullopt;
     }
-    shutdown (fd, SHUT_WR);
-
-    std::string response;
-    char buffer[256];
-    ssize_t readBytes = 0;
-    while ((readBytes = recv (fd, buffer, sizeof (buffer), 0)) > 0) {
-	response.append (buffer, static_cast<std::size_t> (readBytes));
-    }
-    close (fd);
+    const std::string& response = *reply;
 
     static const std::regex xRegex (R"("x"\s*:\s*(-?\d+(?:\.\d+)?))");
     static const std::regex yRegex (R"("y"\s*:\s*(-?\d+(?:\.\d+)?))");

+ 8 - 1
src/WallpaperEngine/Input/Drivers/WaylandMouseInput.h

@@ -8,6 +8,7 @@
 #include <glm/vec2.hpp>
 #include <memory>
 #include <optional>
+#include <string>
 
 #ifdef ENABLE_KDE_FEATURES
 #include "KDECursorInput.h"
@@ -30,12 +31,15 @@ public:
     [[nodiscard]] glm::dvec2 position () const override;
     [[nodiscard]] MouseClickStatus leftClick () const override;
     [[nodiscard]] MouseClickStatus rightClick () const override;
+    [[nodiscard]] std::optional<glm::dvec2> desktopPosition () const override;
+    [[nodiscard]] MouseClickStatus desktopLeftClick () const override;
     /** KWin script, Hyprland or the GNOME Shell extension provide it */
     [[nodiscard]] bool hasGlobalCursor () const;
 
 private:
     [[nodiscard]] const Render::Drivers::Output::WaylandOutputViewport* getActiveOutputViewport () const;
-    [[nodiscard]] std::optional<glm::dvec2> queryHyprlandCursorPosition () const;
+    [[nodiscard]] std::optional<glm::dvec2> queryHyprlandCursorPosition ();
+    [[nodiscard]] static std::string findHyprlandSocket ();
 #ifdef ENABLE_X11
     // last-resort fallback: XWayland's root window pointer only tracks the real cursor while it's
     // over an XWayland-backed window, but that's still better than nothing on compositors with no IPC
@@ -54,6 +58,9 @@ private:
     std::chrono::steady_clock::time_point m_lastGlobalCursorQuery = {};
     std::chrono::steady_clock::time_point m_lastForwardedPoll = {};
     bool m_forwardedLeftDown = false;
+    /** empty when not on Hyprland, looked up again (at most once a second) when it goes away */
+    std::string m_hyprlandSocket;
+    std::chrono::steady_clock::time_point m_lastHyprlandLookup = {};
 
 #ifdef ENABLE_KDE_FEATURES
     std::unique_ptr<KDECursorInput> m_kdeCursor;

+ 5 - 0
src/WallpaperEngine/Input/MouseInput.h

@@ -1,6 +1,7 @@
 #pragma once
 
 #include <glm/vec2.hpp>
+#include <optional>
 
 namespace WallpaperEngine::Input {
 enum MouseClickStatus : int { Released = 0, Clicked = 1 };
@@ -25,5 +26,9 @@ public:
     [[nodiscard]] virtual glm::dvec2 position () const = 0;
     [[nodiscard]] virtual MouseClickStatus leftClick () const = 0;
     [[nodiscard]] virtual MouseClickStatus rightClick () const = 0;
+    /** The pointer in the desktop layout (OutputViewport::globalPosition units, y down) when the driver knows it */
+    [[nodiscard]] virtual std::optional<glm::dvec2> desktopPosition () const { return std::nullopt; }
+    /** The left button wherever the pointer is, for a wallpaper spanning several outputs */
+    [[nodiscard]] virtual MouseClickStatus desktopLeftClick () const { return this->leftClick (); }
 };
 } // namespace WallpaperEngine::Input

+ 5 - 0
src/WallpaperEngine/Render/CTexture.cpp

@@ -331,6 +331,11 @@ void CTexture::setupOpenGLParameters (const uint32_t textureID) const {
 }
 
 GLuint CTexture::getTextureID (const uint32_t imageIndex) const {
+    // only asked for to bind it, WE transfers the video frame on every bind (sub_14015F0D0)
+    if (this->m_player) {
+	this->m_player->markUsed ();
+    }
+
     if (imageIndex >= this->m_header->imageCount) {
 	return this->m_textureID[0];
     }

+ 102 - 4
src/WallpaperEngine/Render/CWallpaper.cpp

@@ -379,6 +379,93 @@ void CWallpaper::updateUVs (const glm::ivec4& viewport, const bool vflip) {
     }
 }
 
+void CWallpaper::updateSpanBounds () {
+    auto& span = *this->m_spanInfo;
+    const auto& viewports = this->getContext ().getOutput ().getViewports ();
+    glm::ivec2 low (std::numeric_limits<int>::max ());
+    glm::ivec2 high (std::numeric_limits<int>::min ());
+    double scale = 0.0;
+
+    // a screen that went away leaves the group, like a monitor WE no longer finds
+    for (const auto& screen : span.screens) {
+	const auto it = viewports.find (screen);
+
+	if (it == viewports.end () || it->second->logicalSize.x <= 0 || it->second->logicalSize.y <= 0) {
+	    continue;
+	}
+
+	const auto* output = it->second;
+	low = glm::min (low, output->globalPosition);
+	high = glm::max (high, output->globalPosition + output->logicalSize);
+	scale = std::max (scale, static_cast<double> (output->viewport.z) / output->logicalSize.x);
+    }
+
+    if (scale <= 0.0) {
+	return;
+    }
+
+    const glm::ivec4 bounds { low, high - low };
+
+    GLint maxTexture = 0;
+    GLint maxViewport[2] = { 0, 0 };
+    glGetIntegerv (GL_MAX_TEXTURE_SIZE, &maxTexture);
+    glGetIntegerv (GL_MAX_VIEWPORT_DIMS, maxViewport);
+    const double limit = std::min ({ maxTexture, maxViewport[0], maxViewport[1] });
+
+    if (limit > 0.0) {
+	scale = std::min (scale, limit / std::max (bounds.z, bounds.w));
+    }
+
+    if (bounds != span.totalBounds || scale != span.scale) {
+	sLog.out (
+	    "Span ", span.screens.front (), ": ", bounds.z, "x", bounds.w, " at ", bounds.x, ",", bounds.y,
+	    ", rendered at ", scale, "x"
+	);
+    }
+
+    span.totalBounds = bounds;
+    span.scale = scale;
+}
+
+void CWallpaper::updateSpanCursor (
+    const glm::ivec4& viewport, const glm::ivec2& globalPosition, const glm::ivec2& logicalSize
+) {
+    const auto& span = *this->m_spanInfo;
+    const auto& input = this->getContext ().getInputContext ().getMouseInput ();
+    auto desktop = input.desktopPosition ();
+
+    // otherwise the output being drawn knows where the pointer is relative to itself
+    if (!desktop.has_value () && viewport.z > 0 && viewport.w > 0) {
+	const glm::dvec2 local
+	    = (input.position () - glm::dvec2 (viewport.x, viewport.y)) / glm::dvec2 (viewport.z, viewport.w);
+	desktop = glm::dvec2 (globalPosition) + glm::dvec2 (local.x, 1.0 - local.y) * glm::dvec2 (logicalSize);
+    }
+
+    if (!desktop.has_value ()) {
+	return;
+    }
+
+    // ScreenToClient on the group's window (sub_140110630), in its pixels with y up like MouseInput
+    this->m_spanCursor = glm::dvec2 (
+	(desktop->x - span.totalBounds.x) * span.scale,
+	(span.totalBounds.y + span.totalBounds.w - desktop->y) * span.scale
+    );
+}
+
+glm::dvec2 CWallpaper::cursorPosition () const {
+    if (this->m_spanInfo.has_value ()) {
+	return this->m_spanCursor;
+    }
+
+    return this->getContext ().getInputContext ().getMouseInput ().position ();
+}
+
+WallpaperEngine::Input::MouseClickStatus CWallpaper::cursorLeftClick () const {
+    const auto& input = this->getContext ().getInputContext ().getMouseInput ();
+
+    return this->m_spanInfo.has_value () ? input.desktopLeftClick () : input.leftClick ();
+}
+
 glm::vec4 CWallpaper::getOutputUVs () const {
     if (this->rendersAtOutputSize ()) {
 	return this->m_state.isVFlipped () ? glm::vec4 { 0.0f, 1.0f, 0.0f, 1.0f }
@@ -403,15 +490,26 @@ void CWallpaper::render (
 ) {
     const uint32_t currentFrame = this->getContext ().getDriver ().getFrameCounter ();
     const bool needsSceneRender = (currentFrame != this->m_lastRenderedFrame);
-    const glm::ivec4 sceneViewport = this->m_spanInfo.has_value ()
-	? glm::ivec4 { 0, 0, this->m_spanInfo->totalBounds.z, this->m_spanInfo->totalBounds.w }
-	: viewport;
+    glm::ivec4 sceneViewport = viewport;
+
+    // WE makes a stretch group one more monitor whose rect is the bounding box of its monitors (sub_140061B50),
+    // drawn into one window over that rect: the scene, its cursor and the flip cover the whole group
+    if (this->m_spanInfo.has_value ()) {
+	if (needsSceneRender) {
+	    this->updateSpanBounds ();
+	    this->updateSpanCursor (viewport, globalPosition, logicalSize);
+	}
+
+	const auto& span = *this->m_spanInfo;
+	sceneViewport = { 0, 0, static_cast<int> (std::lround (span.totalBounds.z * span.scale)),
+			  static_cast<int> (std::lround (span.totalBounds.w * span.scale)) };
+    }
 
     this->m_screenSize = { sceneViewport.z, sceneViewport.w };
     this->m_supersampling
 	= this->rendersAtOutputSize () ? this->supersamplingFor ({ sceneViewport.z, sceneViewport.w }) : 1;
     // the scene reads the visible region from these while it renders
-    this->updateUVs (this->m_spanInfo.has_value () ? this->m_spanInfo->totalBounds : viewport, vflip);
+    this->updateUVs (sceneViewport, vflip);
 
 #if !NDEBUG
     glPushDebugGroup (GL_DEBUG_SOURCE_APPLICATION, 0, -1, "Rendering scene");

+ 13 - 1
src/WallpaperEngine/Render/CWallpaper.h

@@ -7,6 +7,7 @@
 #include <optional>
 
 #include "WallpaperEngine/Audio/AudioContext.h"
+#include "WallpaperEngine/Input/MouseInput.h"
 
 #include "WallpaperEngine/Render/CFBO.h"
 #include "WallpaperEngine/Render/Helpers/ContextAware.h"
@@ -41,8 +42,12 @@ class CWallpaper : public Helpers::ContextAware, public FBOProvider, public Type
 public:
     /** One wallpaper shared and rendered across multiple viewports */
     struct SpanInfo {
-	/** Bounding box of the entire span group (x, y, width, height) in global desktop coordinates */
+	/** The group's screens, the bounds follow their current layout */
+	std::vector<std::string> screens;
+	/** Bounding box of the group's outputs (x, y, width, height) in global desktop coordinates, gaps included */
 	glm::ivec4 totalBounds;
+	/** Buffer pixels per desktop unit the group renders at, the highest of its outputs */
+	double scale = 1.0;
     };
 
     virtual ~CWallpaper () override;
@@ -125,6 +130,9 @@ public:
     void setDestinationFramebuffer (GLuint framebuffer);
     void setSpanInfo (const SpanInfo& spanInfo);
     [[nodiscard]] const SpanInfo* getSpanInfo () const;
+    /** Like MouseInput::position, but over the whole group for a span */
+    [[nodiscard]] glm::dvec2 cursorPosition () const;
+    [[nodiscard]] Input::MouseClickStatus cursorLeftClick () const;
 
     [[nodiscard]] virtual int getWidth () const = 0;
     [[nodiscard]] virtual int getHeight () const = 0;
@@ -253,6 +261,10 @@ private:
     int m_supersampling = 1;
     int m_supersamplingLogged = 0;
     std::optional<SpanInfo> m_spanInfo = std::nullopt;
+    /** the cursor in the group's buffer pixels, y up */
+    glm::dvec2 m_spanCursor = { 0, 0 };
+    void updateSpanBounds ();
+    void updateSpanCursor (const glm::ivec4& viewport, const glm::ivec2& globalPosition, const glm::ivec2& logicalSize);
     // Avoids redundant renderFrame calls when the same wallpaper is shared across viewports (span mode)
     uint32_t m_lastRenderedFrame = UINT32_MAX;
     glm::ivec2 m_screenSize = { 0, 0 };

+ 32 - 7
src/WallpaperEngine/Render/Drivers/Detectors/KDEWaylandFullScreenDetector.cpp

@@ -18,7 +18,7 @@ KDEWaylandFullScreenDetector::KDEWaylandFullScreenDetector (
     }
 
     this->m_script = std::make_unique<Desktop::KWinScript> (
-	this->m_connection, "lwe-window-states-" + std::to_string (getpid ()), this->scriptSource ()
+	this->m_connection, "lwe-window-states-" + Desktop::processTag (), this->scriptSource ()
     );
 
     if (!this->m_script->isLoaded ()) {
@@ -52,7 +52,7 @@ bool KDEWaylandFullScreenDetector::initializeDBus () {
     }
 
     dbus_connection_set_exit_on_disconnect (this->m_connection, false);
-    this->m_serviceName = std::string (kServiceName) + "_" + std::to_string (getpid ());
+    this->m_serviceName = std::string (kServiceName) + "_" + Desktop::processTag ();
 
     dbus_error_init (&error);
     const int requested
@@ -89,6 +89,15 @@ std::string KDEWaylandFullScreenDetector::scriptSource () const {
 	+ kUnsupported + "';\n" + R"(
 const MAXIMIZE_FULL = 3;
 let last = '';
+// Plasma 6.7 gives scripts hiddenByShowDesktopChanged but not the property, so it is kept from the signal, which
+// fires on every change (show desktop on, then off again)
+const hiddenByShowDesktop = new Set();
+
+function isHiddenByShowDesktop(window) {
+    if (typeof window.hiddenByShowDesktop === 'boolean')
+        return window.hiddenByShowDesktop;
+    return hiddenByShowDesktop.has(String(window.internalId));
+}
 
 function rootOf(window) {
     while (window && window.transient && window.transientFor)
@@ -97,7 +106,7 @@ function rootOf(window) {
 }
 
 function counts(window) {
-    if (!window || window.deleted || !window.managed || window.minimized || window.hiddenByShowDesktop ||
+    if (!window || window.deleted || !window.managed || window.minimized || isHiddenByShowDesktop(window) ||
         window.pid === enginePid)
         return false;
     if (window.specialWindow || window.popupWindow || window.desktopWindow || window.dock)
@@ -147,8 +156,16 @@ function watch(window) {
     window.desktopsChanged.connect(report);
     window.activitiesChanged.connect(report);
     // connecting a missing signal kills the script
-    if (window.hiddenByShowDesktopChanged)
-        window.hiddenByShowDesktopChanged.connect(report);
+    if (window.hiddenByShowDesktopChanged) {
+        window.hiddenByShowDesktopChanged.connect(() => {
+            const id = String(window.internalId);
+            if (hiddenByShowDesktop.has(id))
+                hiddenByShowDesktop.delete(id);
+            else
+                hiddenByShowDesktop.add(id);
+            report();
+        });
+    }
     // fires every frame while moving, only the active window's size matters
     window.frameGeometryChanged.connect(() => {
         if (window === rootOf(workspace.activeWindow))
@@ -162,8 +179,16 @@ if (typeof workspace.windowList === 'function') {
         watch(window);
         report();
     });
-    workspace.windowRemoved.connect(report);
-    workspace.windowActivated.connect(report);
+    workspace.windowRemoved.connect(window => {
+        hiddenByShowDesktop.delete(String(window.internalId));
+        report();
+    });
+    // activating a window ends show desktop, which also mends a state that started inverted (shown at load)
+    workspace.windowActivated.connect(window => {
+        if (window)
+            hiddenByShowDesktop.delete(String(window.internalId));
+        report();
+    });
     workspace.currentDesktopChanged.connect(report);
     workspace.currentActivityChanged.connect(report);
     report();

+ 226 - 156
src/WallpaperEngine/Render/Drivers/Detectors/WaylandFullScreenDetector.cpp

@@ -6,228 +6,297 @@
 #include "WallpaperEngine/Desktop/KDESession.h"
 #endif
 
+#include "WallpaperEngine/Desktop/HostWayland.h"
 #include "WallpaperEngine/Desktop/WindowState.h"
 #include "WallpaperEngine/Logging/Log.h"
 #include "WallpaperEngine/Render/Drivers/VideoFactories.h"
 #include "WallpaperEngine/Render/Drivers/WaylandOpenGLDriver.h"
 #include "wlr-foreign-toplevel-management-unstable-v1-protocol.h"
-#include <cstdlib>
+#include <algorithm>
 #include <cstring>
-#include <string>
+#include <wayland-client.h>
 
 namespace WallpaperEngine::Render::Drivers::Detectors {
 
 namespace {
 
-    struct FullscreenState {
-	bool pending = false;
-	bool current = false;
-	bool pendingActivated = false;
-	bool currentActivated = false;
-	std::string appId {};
-	WallpaperEngine::Render::Drivers::Detectors::WaylandFullscreenDetectorCallbackData* const data;
+    using Output = WaylandFullScreenDetector::Output;
+    using Toplevel = WaylandFullScreenDetector::Toplevel;
+
+    void
+    outputGeometry (void*, wl_output*, int32_t, int32_t, int32_t, int32_t, int32_t, const char*, const char*, int32_t) {
+    }
+
+    void outputMode (void*, wl_output*, uint32_t, int32_t, int32_t, int32_t) { }
+
+    void outputDone (void*, wl_output*) { }
+
+    void outputScale (void*, wl_output*, int32_t) { }
+
+    void outputName (void* data, wl_output*, const char* name) {
+	if (name) {
+	    static_cast<Output*> (data)->name = name;
+	}
+    }
+
+    void outputDescription (void*, wl_output*, const char*) { }
+
+    constexpr wl_output_listener outputListener = {
+	.geometry = outputGeometry,
+	.mode = outputMode,
+	.done = outputDone,
+	.scale = outputScale,
+	.name = outputName,
+	.description = outputDescription,
     };
 
-    void toplevelHandleTitle (void*, struct zwlr_foreign_toplevel_handle_v1*, const char*) { }
+    void toplevelTitle (void*, zwlr_foreign_toplevel_handle_v1*, const char*) { }
 
-    void toplevelHandleAppId (void* data, struct zwlr_foreign_toplevel_handle_v1*, const char* appId) {
-	const auto state = static_cast<FullscreenState*> (data);
+    void toplevelAppId (void* data, zwlr_foreign_toplevel_handle_v1*, const char* appId) {
 	if (appId) {
-	    state->appId = appId;
+	    static_cast<Toplevel*> (data)->appId = appId;
 	}
     }
 
-    void toplevelHandleOutputEnter (void*, struct zwlr_foreign_toplevel_handle_v1*, struct wl_output*) { }
-
-    void toplevelHandleOutputLeave (void*, struct zwlr_foreign_toplevel_handle_v1*, struct wl_output*) { }
+    void toplevelOutputEnter (void* data, zwlr_foreign_toplevel_handle_v1*, wl_output* output) {
+	static_cast<Toplevel*> (data)->outputs.insert (output);
+    }
 
-    void
-    toplevelHandleParent (void*, struct zwlr_foreign_toplevel_handle_v1*, struct zwlr_foreign_toplevel_handle_v1*) { }
+    void toplevelOutputLeave (void* data, zwlr_foreign_toplevel_handle_v1*, wl_output* output) {
+	static_cast<Toplevel*> (data)->outputs.erase (output);
+    }
 
-    void toplevelHandleState (void* data, struct zwlr_foreign_toplevel_handle_v1*, struct wl_array* state) {
-	const auto toplevel = static_cast<FullscreenState*> (data);
+    void toplevelState (void* data, zwlr_foreign_toplevel_handle_v1*, wl_array* state) {
+	const auto toplevel = static_cast<Toplevel*> (data);
 	const auto begin = static_cast<uint32_t*> (state->data);
 
-	toplevel->pending = false;
-	toplevel->pendingActivated = false;
+	toplevel->fullscreen = false;
+	toplevel->maximized = false;
+	toplevel->activated = false;
 
 	for (auto it = begin; it < begin + state->size / sizeof (uint32_t); ++it) {
-	    if (*it == ZWLR_FOREIGN_TOPLEVEL_HANDLE_V1_STATE_FULLSCREEN) {
-		toplevel->pending = true;
-	    }
-	    if (*it == ZWLR_FOREIGN_TOPLEVEL_HANDLE_V1_STATE_ACTIVATED) {
-		toplevel->pendingActivated = true;
+	    switch (*it) {
+		case ZWLR_FOREIGN_TOPLEVEL_HANDLE_V1_STATE_FULLSCREEN:
+		    toplevel->fullscreen = true;
+		    break;
+		case ZWLR_FOREIGN_TOPLEVEL_HANDLE_V1_STATE_MAXIMIZED:
+		    toplevel->maximized = true;
+		    break;
+		case ZWLR_FOREIGN_TOPLEVEL_HANDLE_V1_STATE_ACTIVATED:
+		    toplevel->activated = true;
+		    break;
+		default:
+		    break;
 	    }
 	}
     }
 
-    bool isRelevant (
-	const WallpaperEngine::Application::ApplicationContext& ctx, const bool fullscreen, const bool activated,
-	const std::string& appId
-    ) {
-	const auto& render = ctx.settings.render;
-	const bool focusPauses = render.pauseOnFocus && activated;
-	const bool fullscreenPauses
-	    = render.pauseOnFullscreen && fullscreen && (!render.pauseOnFullscreenOnlyWhenActive || activated);
-
-	if (!focusPauses && !fullscreenPauses) {
-	    return false;
-	}
+    void toplevelDone (void*, zwlr_foreign_toplevel_handle_v1*) { }
 
-	if (!appId.empty ()) {
-	    for (const auto& ignore : ctx.settings.render.fullscreenPauseIgnoreAppIds) {
-		if (ignore.empty ()) {
-		    continue;
-		}
-		if (Desktop::containsIgnoringCase (appId, ignore)) {
-		    return false;
-		}
-	    }
-	}
-
-	return true;
+    void toplevelClosed (void* data, zwlr_foreign_toplevel_handle_v1*) {
+	const auto toplevel = static_cast<Toplevel*> (data);
+	toplevel->detector->removeToplevel (toplevel);
     }
 
-    bool isFullscreenRelevant (const FullscreenState& toplevel) {
-	const auto& ctx = toplevel.data->detector->getApplicationContext ();
-	return isRelevant (ctx, toplevel.pending, toplevel.pendingActivated, toplevel.appId);
+    void toplevelParent (void*, zwlr_foreign_toplevel_handle_v1*, zwlr_foreign_toplevel_handle_v1*) { }
+
+    constexpr zwlr_foreign_toplevel_handle_v1_listener toplevelListener = {
+	.title = toplevelTitle,
+	.app_id = toplevelAppId,
+	.output_enter = toplevelOutputEnter,
+	.output_leave = toplevelOutputLeave,
+	.state = toplevelState,
+	.done = toplevelDone,
+	.closed = toplevelClosed,
+	.parent = toplevelParent,
+    };
+
+    void managerToplevel (void* data, zwlr_foreign_toplevel_manager_v1*, zwlr_foreign_toplevel_handle_v1* handle) {
+	static_cast<WaylandFullScreenDetector*> (data)->addToplevel (handle);
     }
 
-    bool isCurrentlyRelevant (const FullscreenState& toplevel) {
-	const auto& ctx = toplevel.data->detector->getApplicationContext ();
-	return isRelevant (ctx, toplevel.current, toplevel.currentActivated, toplevel.appId);
+    void managerFinished (void*, zwlr_foreign_toplevel_manager_v1* manager) {
+	zwlr_foreign_toplevel_manager_v1_destroy (manager);
     }
 
-    void toplevelHandleDone (void* data, struct zwlr_foreign_toplevel_handle_v1* handle) {
-	const auto toplevel = static_cast<FullscreenState*> (data);
+    constexpr zwlr_foreign_toplevel_manager_v1_listener managerListener = {
+	.toplevel = managerToplevel,
+	.finished = managerFinished,
+    };
 
-	const bool pendingRelevant = isFullscreenRelevant (*toplevel);
-	const bool currentRelevant = isCurrentlyRelevant (*toplevel);
+    void registryGlobal (void* data, wl_registry* registry, uint32_t name, const char* interface, uint32_t version) {
+	const auto detector = static_cast<WaylandFullScreenDetector*> (data);
 
-	if (currentRelevant != pendingRelevant) {
-	    if (pendingRelevant) {
-		++(*toplevel->data->fullscreenCount);
-	    } else {
-		if (*toplevel->data->fullscreenCount == 0) {
-		    sLog.error ("Fullscreen count underflow!!!");
-		} else {
-		    --(*toplevel->data->fullscreenCount);
-		}
-	    }
+	if (strcmp (interface, wl_output_interface.name) == 0) {
+	    detector->addOutput (registry, name, version);
+	} else if (strcmp (interface, zwlr_foreign_toplevel_manager_v1_interface.name) == 0) {
+	    detector->m_managerGlobal = name;
+	    detector->m_managerVersion = version;
 	}
-
-	toplevel->current = toplevel->pending;
-	toplevel->currentActivated = toplevel->pendingActivated;
     }
 
-    void toplevelHandleClosed (void* data, struct zwlr_foreign_toplevel_handle_v1* handle) {
-	const auto toplevel = static_cast<FullscreenState*> (data);
+    void registryGlobalRemove (void* data, wl_registry*, uint32_t name) {
+	static_cast<WaylandFullScreenDetector*> (data)->removeGlobal (name);
+    }
 
-	// If it was counted as relevant fullscreen, remove it.
-	const bool currentRelevant = isCurrentlyRelevant (*toplevel);
+    constexpr wl_registry_listener registryListener = {
+	.global = registryGlobal,
+	.global_remove = registryGlobalRemove,
+    };
 
-	if (currentRelevant) {
-	    if (*toplevel->data->fullscreenCount == 0) {
-		sLog.error ("Fullscreen count underflow!!!");
-	    } else {
-		--(*toplevel->data->fullscreenCount);
-	    }
-	}
+} // anonymous namespace
 
-	zwlr_foreign_toplevel_handle_v1_destroy (handle);
-	delete toplevel;
+WaylandFullScreenDetector::WaylandFullScreenDetector (
+    Application::ApplicationContext& appContext, WaylandOpenGLDriver* driver
+) : FullScreenDetector (appContext), m_driver (driver) {
+    m_display = Desktop::connectWayland ();
+    if (!m_display) {
+	sLog.exception ("Failed to query wayland display");
     }
 
-    constexpr struct zwlr_foreign_toplevel_handle_v1_listener toplevelHandleListener = {
-	.title = toplevelHandleTitle,
-	.app_id = toplevelHandleAppId,
-	.output_enter = toplevelHandleOutputEnter,
-	.output_leave = toplevelHandleOutputLeave,
-	.state = toplevelHandleState,
-	.done = toplevelHandleDone,
-	.closed = toplevelHandleClosed,
-	.parent = toplevelHandleParent,
-    };
+    m_registry = wl_display_get_registry (m_display);
+    wl_registry_add_listener (m_registry, &registryListener, this);
+    wl_display_roundtrip (m_display);
 
-    void handleToplevel (
-	void* data, struct zwlr_foreign_toplevel_manager_v1* manager, struct zwlr_foreign_toplevel_handle_v1* handle
-    ) {
-	const auto cb
-	    = static_cast<WallpaperEngine::Render::Drivers::Detectors::WaylandFullscreenDetectorCallbackData*> (data);
-	const auto toplevel = new FullscreenState {
-	    .pending = false,
-	    .current = false,
-	    .pendingActivated = false,
-	    .currentActivated = false,
-	    .appId = {},
-	    .data = cb,
-	};
-	zwlr_foreign_toplevel_handle_v1_add_listener (handle, &toplevelHandleListener, toplevel);
+    if (m_managerGlobal == 0) {
+	sLog.out ("Fullscreen detection not supported by your Wayland compositor");
+	return;
     }
 
-    void handleFinished (void* data, struct zwlr_foreign_toplevel_manager_v1* manager) {
-	zwlr_foreign_toplevel_manager_v1_destroy (manager);
+    // bound after the outputs, so the first output_enter events have a wl_output of ours to name
+    m_toplevelManager = static_cast<zwlr_foreign_toplevel_manager_v1*> (wl_registry_bind (
+	m_registry, m_managerGlobal, &zwlr_foreign_toplevel_manager_v1_interface,
+	std::min<uint32_t> (m_managerVersion, 3)
+    ));
+    zwlr_foreign_toplevel_manager_v1_add_listener (m_toplevelManager, &managerListener, this);
+    wl_display_roundtrip (m_display);
+    wl_display_roundtrip (m_display);
+}
+
+WaylandFullScreenDetector::~WaylandFullScreenDetector () {
+    for (const auto* toplevel : m_toplevels) {
+	delete toplevel;
     }
 
-    zwlr_foreign_toplevel_manager_v1_listener toplevelManagerListener = {
-	.toplevel = handleToplevel,
-	.finished = handleFinished,
-    };
+    for (const auto* output : m_outputs) {
+	delete output;
+    }
 
-}; // anonymous namespace
-
-void handleGlobal (void* data, struct wl_registry* registry, uint32_t name, const char* interface, uint32_t version) {
-    const auto detector = static_cast<WaylandFullScreenDetector*> (data);
-    if (strcmp (interface, zwlr_foreign_toplevel_manager_v1_interface.name) == 0) {
-	detector->m_toplevelManager = static_cast<zwlr_foreign_toplevel_manager_v1*> (
-	    wl_registry_bind (registry, name, &zwlr_foreign_toplevel_manager_v1_interface, 3)
-	);
-	if (detector->m_toplevelManager) {
-	    zwlr_foreign_toplevel_manager_v1_add_listener (
-		detector->m_toplevelManager, &toplevelManagerListener, &detector->m_callbackData
-	    );
-	}
+    if (m_display) {
+	wl_display_disconnect (m_display);
     }
 }
 
-void handleGlobalRemoved (void* data, struct wl_registry* registry, uint32_t id) {
-    // todo: outputs
+void WaylandFullScreenDetector::addOutput (wl_registry* registry, uint32_t globalName, uint32_t version) {
+    // wl_output.name is v4, without it the toplevels on this output count everywhere
+    const auto output = new Output {
+	.output = static_cast<wl_output*> (
+	    wl_registry_bind (registry, globalName, &wl_output_interface, std::min<uint32_t> (version, 4))
+	),
+	.globalName = globalName,
+	.name = {},
+    };
+    wl_output_add_listener (output->output, &outputListener, output);
+    m_outputs.push_back (output);
 }
 
-constexpr struct wl_registry_listener registryListener = {
-    .global = handleGlobal,
-    .global_remove = handleGlobalRemoved,
-};
+void WaylandFullScreenDetector::removeGlobal (uint32_t globalName) {
+    const auto it = std::ranges::find (m_outputs, globalName, &Output::globalName);
 
-WaylandFullScreenDetector::WaylandFullScreenDetector (Application::ApplicationContext& appContext) :
-    FullScreenDetector (appContext), m_callbackData { .detector = this, .fullscreenCount = &m_fullscreenCount } {
-    m_display = wl_display_connect (nullptr);
-    if (!m_display) {
-	sLog.exception ("Failed to query wayland display");
+    if (it == m_outputs.end ()) {
+	return;
     }
 
-    const auto registry = wl_display_get_registry (m_display);
-    wl_registry_add_listener (registry, &registryListener, this);
-    wl_display_roundtrip (m_display); // load list of toplevels
-    if (!m_toplevelManager) {
-	sLog.out ("Fullscreen detection not supported by your Wayland compositor");
+    for (auto* toplevel : m_toplevels) {
+	toplevel->outputs.erase ((*it)->output);
+    }
+
+    if (wl_proxy_get_version (reinterpret_cast<wl_proxy*> ((*it)->output)) >= WL_OUTPUT_RELEASE_SINCE_VERSION) {
+	wl_output_release ((*it)->output);
     } else {
-	wl_display_roundtrip (m_display); // load toplevel details
+	wl_output_destroy ((*it)->output);
     }
+
+    delete *it;
+    m_outputs.erase (it);
 }
 
-WaylandFullScreenDetector::~WaylandFullScreenDetector () {
-    if (m_display) {
-	wl_display_disconnect (m_display);
+void WaylandFullScreenDetector::addToplevel (zwlr_foreign_toplevel_handle_v1* handle) {
+    const auto toplevel = new Toplevel { .detector = this, .handle = handle };
+    zwlr_foreign_toplevel_handle_v1_add_listener (handle, &toplevelListener, toplevel);
+    m_toplevels.push_back (toplevel);
+}
+
+void WaylandFullScreenDetector::removeToplevel (Toplevel* toplevel) {
+    zwlr_foreign_toplevel_handle_v1_destroy (toplevel->handle);
+    std::erase (m_toplevels, toplevel);
+    delete toplevel;
+}
+
+const std::string* WaylandFullScreenDetector::outputName (wl_output* output) const {
+    const auto it = std::ranges::find (m_outputs, output, &Output::output);
+
+    if (it == m_outputs.end () || (*it)->name.empty ()) {
+	return nullptr;
     }
+
+    return &(*it)->name;
+}
+
+std::vector<Desktop::WindowState> WaylandFullScreenDetector::windows (const std::vector<std::string>& drawn) const {
+    const bool maximizedPauses = getApplicationContext ().settings.render.pauseOnMaximized;
+    std::vector<Desktop::WindowState> windows;
+
+    for (const auto* toplevel : m_toplevels) {
+	const uint32_t flags = (toplevel->activated ? Desktop::WindowState::Focused : 0)
+	    | (toplevel->maximized && maximizedPauses ? Desktop::WindowState::Maximized : 0)
+	    | (toplevel->fullscreen ? Desktop::WindowState::Fullscreen : 0);
+
+	if (flags == 0) {
+	    continue;
+	}
+
+	bool placed = false;
+
+	for (auto* output : toplevel->outputs) {
+	    if (const auto* name = outputName (output)) {
+		windows.push_back ({ toplevel->appId, *name, flags });
+		placed = true;
+	    }
+	}
+
+	if (!placed) {
+	    for (const auto& name : drawn) {
+		windows.push_back ({ toplevel->appId, name, flags });
+	    }
+	}
+    }
+
+    return windows;
 }
 
 bool WaylandFullScreenDetector::anythingFullscreen () const {
     if (!m_toplevelManager) {
 	return false;
     }
+
     wl_display_roundtrip (m_display);
-    return m_fullscreenCount > 0;
+
+    // a driver that isn't ours has no outputs to tell apart, every window counts there: each named output plus "",
+    // where windows on no named output land
+    std::vector<std::string> drawn { "" };
+
+    if (m_driver) {
+	drawn = m_driver->drawnOutputs ();
+    } else {
+	for (const auto* output : m_outputs) {
+	    if (!output->name.empty ()) {
+		drawn.push_back (output->name);
+	    }
+	}
+    }
+
+    return Desktop::pausesAnyOf (windows (drawn), drawn, getApplicationContext ());
 }
 
 void WaylandFullScreenDetector::reset () { }
@@ -235,20 +304,21 @@ void WaylandFullScreenDetector::reset () { }
 __attribute__ ((constructor)) void registerWaylandFullscreenDetector () {
     sVideoFactories.registerFullscreenDetector (
 	"wayland", [] (ApplicationContext& context, VideoDriver& driver) -> std::unique_ptr<FullScreenDetector> {
-	    if (auto* wayland = dynamic_cast<WaylandOpenGLDriver*> (&driver); wayland && wayland->getGnomeShell ()) {
+	    auto* wayland = dynamic_cast<WaylandOpenGLDriver*> (&driver);
+
+	    if (wayland && wayland->getGnomeShell ()) {
 		return std::make_unique<GnomeFullScreenDetector> (context, *wayland);
 	    }
 #ifdef ENABLE_KDE_FEATURES
-	    if (auto* wayland = dynamic_cast<WaylandOpenGLDriver*> (&driver);
-		wayland && WallpaperEngine::Desktop::isKDESession ()) {
+	    if (wayland && WallpaperEngine::Desktop::isKDESession ()) {
 		auto detector = std::make_unique<KDEWaylandFullScreenDetector> (context, *wayland);
 		if (!detector->isInitialized ()) {
-		    return std::make_unique<WaylandFullScreenDetector> (context);
+		    return std::make_unique<WaylandFullScreenDetector> (context, wayland);
 		}
 		return detector;
 	    }
 #endif
-	    return std::make_unique<WaylandFullScreenDetector> (context);
+	    return std::make_unique<WaylandFullScreenDetector> (context, wayland);
 	}
     );
 }

+ 51 - 15
src/WallpaperEngine/Render/Drivers/Detectors/WaylandFullScreenDetector.h

@@ -2,41 +2,77 @@
 
 #ifdef ENABLE_WAYLAND
 
-#include <glm/vec4.hpp>
+#include <cstdint>
+#include <set>
+#include <string>
+#include <vector>
 
 #include "FullScreenDetector.h"
 
 struct wl_display;
+struct wl_output;
 struct wl_registry;
 struct zwlr_foreign_toplevel_manager_v1;
+struct zwlr_foreign_toplevel_handle_v1;
 
-namespace WallpaperEngine::Render::Drivers::Detectors {
+namespace WallpaperEngine::Render::Drivers {
+class WaylandOpenGLDriver;
+}
 
-class WaylandFullScreenDetector;
+namespace WallpaperEngine::Desktop {
+struct WindowState;
+}
 
-struct WaylandFullscreenDetectorCallbackData {
-    WaylandFullScreenDetector* detector;
-    uint32_t* fullscreenCount;
-};
+namespace WallpaperEngine::Render::Drivers::Detectors {
 
+/**
+ * wlroots foreign toplevel: fullscreen (and with --pause-on-maximized maximized) windows pause the outputs they are on.
+ * A toplevel on no output we know the name of counts everywhere, a compositor that never sends output_enter is no
+ * worse off than before.
+ */
 class WaylandFullScreenDetector final : public FullScreenDetector {
 public:
-    explicit WaylandFullScreenDetector (Application::ApplicationContext& appContext);
+    struct Output {
+	wl_output* output;
+	uint32_t globalName;
+	std::string name;
+    };
+
+    struct Toplevel {
+	WaylandFullScreenDetector* detector;
+	zwlr_foreign_toplevel_handle_v1* handle;
+	std::string appId;
+	std::set<wl_output*> outputs;
+	bool fullscreen = false;
+	bool maximized = false;
+	bool activated = false;
+    };
+
+    WaylandFullScreenDetector (Application::ApplicationContext& appContext, WaylandOpenGLDriver* driver);
     ~WaylandFullScreenDetector () override;
 
     [[nodiscard]] bool anythingFullscreen () const override;
     void reset () override;
 
-private:
-    wl_display* m_display = nullptr;
-    zwlr_foreign_toplevel_manager_v1* m_toplevelManager = nullptr;
+    /** what the pause decision sees, one entry per output a toplevel is on */
+    [[nodiscard]] std::vector<Desktop::WindowState> windows (const std::vector<std::string>& drawn) const;
 
-    uint32_t m_fullscreenCount = 0;
+    void addOutput (wl_registry* registry, uint32_t globalName, uint32_t version);
+    void removeGlobal (uint32_t globalName);
+    void addToplevel (zwlr_foreign_toplevel_handle_v1* handle);
+    void removeToplevel (Toplevel* toplevel);
+    [[nodiscard]] const std::string* outputName (wl_output* output) const;
 
-    WaylandFullscreenDetectorCallbackData m_callbackData {};
+    uint32_t m_managerGlobal = 0;
+    uint32_t m_managerVersion = 0;
 
-    friend void
-    handleGlobal (void* data, struct wl_registry* registry, uint32_t name, const char* interface, uint32_t version);
+private:
+    WaylandOpenGLDriver* m_driver;
+    wl_display* m_display = nullptr;
+    wl_registry* m_registry = nullptr;
+    zwlr_foreign_toplevel_manager_v1* m_toplevelManager = nullptr;
+    std::vector<Output*> m_outputs;
+    std::vector<Toplevel*> m_toplevels;
 };
 } // namespace WallpaperEngine::Render::Drivers::Detectors
 

+ 5 - 3
src/WallpaperEngine/Render/Drivers/Output/WaylandOutput.cpp

@@ -19,9 +19,11 @@ void WaylandOutput::updateViewports () {
 
 	m_viewports[o->name] = o;
 
-	fullw = fullw + glm::ivec2 { o->size.x * o->scale, 0 };
-	if (o->size.y * o->scale > fullw.y) {
-	    fullw.y = o->size.y * o->scale;
+	const glm::ivec2 buffer = o->bufferSize ();
+
+	fullw = fullw + glm::ivec2 { buffer.x, 0 };
+	if (buffer.y > fullw.y) {
+	    fullw.y = buffer.y;
 	}
     }
 

+ 81 - 15
src/WallpaperEngine/Render/Drivers/Output/WaylandOutputViewport.cpp

@@ -9,6 +9,8 @@
 #define static
 extern "C" {
 #include "color-management-v1-protocol.h"
+#include "fractional-scale-v1-protocol.h"
+#include "viewporter-protocol.h"
 #include "wlr-layer-shell-unstable-v1-protocol.h"
 #include "xdg-output-unstable-v1-protocol.h"
 #include "xdg-shell-protocol.h"
@@ -27,8 +29,7 @@ static void handleLSConfigure (void* data, zwlr_layer_surface_v1* surface, uint3
     const auto viewport = static_cast<WaylandOutputViewport*> (data);
     viewport->size = { w, h };
     viewport->logicalSize = { w, h };
-    viewport->viewport = { 0, 0, viewport->size.x * viewport->scale, viewport->size.y * viewport->scale };
-    viewport->resize ();
+    viewport->updateBufferSize ();
 
     zwlr_layer_surface_v1_ack_configure (surface, serial);
 }
@@ -53,8 +54,7 @@ static void handleXdgSurfaceConfigure (void* data, xdg_surface* surface, uint32_
 
     viewport->size = pending;
     viewport->logicalSize = pending;
-    viewport->viewport = { 0, 0, viewport->size.x * viewport->scale, viewport->size.y * viewport->scale };
-    viewport->resize ();
+    viewport->updateBufferSize ();
 }
 
 static void
@@ -102,12 +102,11 @@ static void mode (void* data, wl_output* output, uint32_t flags, int32_t width,
 	return;
     }
 
-    // physical pixels; logicalSize comes from xdg-output or the layer shell configure
-    viewport->size = { width, height };
-    viewport->viewport = { 0, 0, viewport->size.x * viewport->scale, viewport->size.y * viewport->scale };
-
-    if (viewport->hasShellSurface ()) {
-	viewport->resize ();
+    // physical pixels, only a placeholder until the layer shell configure brings the logical size; a mode change
+    // on a live surface comes with a new configure
+    if (!viewport->hasShellSurface ()) {
+	viewport->size = { width, height };
+	viewport->viewport = { 0, 0, width, height };
     }
 
     if (viewport->initialized) {
@@ -123,7 +122,7 @@ static void scale (void* data, wl_output* wl_output, int32_t scale) {
     viewport->scale = scale;
 
     if (viewport->hasShellSurface ()) {
-	viewport->resize ();
+	viewport->updateBufferSize ();
     }
 
     if (viewport->initialized) {
@@ -156,6 +155,20 @@ static void surfaceFrameCallback (void* data, struct wl_callback* cb, uint32_t t
 
 constexpr struct wl_callback_listener frameListener = { .done = surfaceFrameCallback };
 
+static void handlePreferredScale (void* data, wp_fractional_scale_v1*, uint32_t scale) {
+    const auto viewport = static_cast<WaylandOutputViewport*> (data);
+
+    if (scale == viewport->preferredScale120) {
+	return;
+    }
+
+    sLog.out ("Output ", viewport->name, ": drawing at scale ", scale / 120.0);
+    viewport->preferredScale120 = scale;
+    viewport->updateBufferSize ();
+}
+
+constexpr wp_fractional_scale_v1_listener fractionalScaleListener = { .preferred_scale = handlePreferredScale };
+
 constexpr wl_output_listener outputListener
     = { .geometry = geometry, .mode = mode, .done = done, .scale = scale, .name = name, .description = description };
 
@@ -432,13 +445,31 @@ void WaylandOutputViewport::setupToplevel () {
     if (this->size.x <= 0 || this->size.y <= 0 || this->pendingToplevelSize.x <= 0) {
 	this->size = this->logicalSize.x > 0 ? this->logicalSize : this->size / glm::max (this->scale, 1);
 	this->logicalSize = this->size;
-	this->viewport = { 0, 0, this->size.x * this->scale, this->size.y * this->scale };
+	this->viewport = { 0, 0, this->bufferSize () };
     }
 
     this->createEGLSurface ();
 }
 
+void WaylandOutputViewport::setupFractionalScale () {
+    auto* context = m_driver->getWaylandContext ();
+
+    // a fractional buffer needs the viewport to tell the compositor its logical size
+    if (!context->viewporter) {
+	return;
+    }
+
+    this->surfaceViewport = wp_viewporter_get_viewport (context->viewporter, this->surface);
+
+    if (context->fractionalScaleManager) {
+	this->fractionalScale
+	    = wp_fractional_scale_manager_v1_get_fractional_scale (context->fractionalScaleManager, this->surface);
+	wp_fractional_scale_v1_add_listener (this->fractionalScale, &fractionalScaleListener, this);
+    }
+}
+
 void WaylandOutputViewport::prepareSurface () {
+    this->setupFractionalScale ();
     this->setInputRegion (m_driver->getApp ().getContext ().settings.mouse.enabled);
 
     // fully opaque: lets the compositor skip alpha-blending, always a win since wallpapers are the
@@ -456,7 +487,10 @@ void WaylandOutputViewport::prepareSurface () {
 }
 
 void WaylandOutputViewport::createEGLSurface () {
-    eglWindow = wl_egl_window_create (surface, size.x * scale, size.y * scale);
+    const glm::ivec2 buffer = this->bufferSize ();
+
+    this->viewport = { 0, 0, buffer };
+    eglWindow = wl_egl_window_create (surface, buffer.x, buffer.y);
     eglSurface = m_driver->getEGLContext ()->eglCreatePlatformWindowSurfaceEXT (
 	m_driver->getEGLContext ()->display, m_driver->getEGLContext ()->config, eglWindow, nullptr
     );
@@ -578,18 +612,50 @@ void WaylandOutputViewport::swapOutput () {
 
     frameCallback = wl_surface_frame (surface);
     wl_callback_add_listener (frameCallback, &frameListener, this);
+
+    // latched by the commit inside eglSwapBuffers together with the new buffer
+    if (this->surfaceViewport) {
+	wl_surface_set_buffer_scale (surface, 1);
+	wp_viewport_set_destination (this->surfaceViewport, this->size.x, this->size.y);
+    } else {
+	wl_surface_set_buffer_scale (surface, scale);
+    }
+
     eglSwapBuffers (m_driver->getEGLContext ()->display, this->eglSurface);
-    wl_surface_set_buffer_scale (surface, scale);
     wl_surface_damage_buffer (surface, 0, 0, INT32_MAX, INT32_MAX);
     wl_surface_commit (surface);
 }
 
+double WaylandOutputViewport::renderScale () const {
+    if (this->surfaceViewport && this->preferredScale120 > 0) {
+	return this->preferredScale120 / 120.0;
+    }
+
+    return this->scale;
+}
+
+glm::ivec2 WaylandOutputViewport::bufferSize () const {
+    // fractional-scale-v1: the buffer is the logical size times the scale, rounded half away from zero
+    if (this->surfaceViewport && this->preferredScale120 > 0) {
+	return (this->size * static_cast<int> (this->preferredScale120) + 60) / 120;
+    }
+
+    return this->size * this->scale;
+}
+
+void WaylandOutputViewport::updateBufferSize () {
+    this->viewport = { 0, 0, this->bufferSize () };
+    this->resize ();
+}
+
 void WaylandOutputViewport::resize () {
     if (!this->eglWindow) {
 	return;
     }
 
-    wl_egl_window_resize (this->eglWindow, this->size.x * this->scale, this->size.y * this->scale, 0, 0);
+    const glm::ivec2 buffer = this->bufferSize ();
+
+    wl_egl_window_resize (this->eglWindow, buffer.x, buffer.y, 0, 0);
 
     this->getDriver ()->getOutput ().reset ();
 }

+ 16 - 0
src/WallpaperEngine/Render/Drivers/Output/WaylandOutputViewport.h

@@ -22,6 +22,8 @@ struct zxdg_output_v1;
 struct zxdg_output_manager_v1;
 struct wp_color_management_output_v1;
 struct wp_color_management_surface_v1;
+struct wp_fractional_scale_v1;
+struct wp_viewport;
 struct xdg_surface;
 struct xdg_toplevel;
 #ifdef ENABLE_KDE_FEATURES
@@ -41,9 +43,15 @@ namespace Output {
 	WaylandOpenGLDriver* getDriver () const;
 
 	wl_output* output = nullptr;
+	/** logical size, surface coordinates */
 	glm::ivec2 size = {};
 	uint32_t waylandName;
+	/** integer wl_output scale, used when the compositor has no fractional scaling */
 	int scale = 1;
+	/** wp_fractional_scale_v1 preferred scale in 120ths, 0 until the compositor sent one */
+	uint32_t preferredScale120 = 0;
+	wp_viewport* surfaceViewport = nullptr;
+	wp_fractional_scale_v1* fractionalScale = nullptr;
 	bool initialized = false;
 	bool rendering = false;
 	/** layer surface closed or output removed, set during event dispatch and freed by the driver's main loop */
@@ -108,6 +116,13 @@ namespace Output {
 	    uint32_t targetMaxLuminance = 0;
 	} pendingDescription;
 
+	/** buffer pixels per logical pixel */
+	[[nodiscard]] double renderScale () const;
+	/** the surface's buffer size in pixels, the output's native size for a fullscreen surface */
+	[[nodiscard]] glm::ivec2 bufferSize () const;
+	/** recomputes the GL viewport from size and scale, then resizes the EGL window */
+	void updateBufferSize ();
+
 	void makeCurrent () override;
 	void renderFrame ();
 	void swapOutput () override;
@@ -116,6 +131,7 @@ namespace Output {
     private:
 	void prepareSurface ();
 	void setInputRegion (bool everything);
+	void setupFractionalScale ();
 	void createEGLSurface ();
 
 	WaylandOpenGLDriver* m_driver = nullptr;

+ 42 - 6
src/WallpaperEngine/Render/Drivers/WaylandOpenGLDriver.cpp

@@ -1,6 +1,7 @@
 #include "WaylandOpenGLDriver.h"
 #include "VideoFactories.h"
 #include "WallpaperEngine/Application/WallpaperApplication.h"
+#include "WallpaperEngine/Desktop/HostWayland.h"
 #include "WallpaperEngine/Logging/Log.h"
 
 #define class _class
@@ -8,6 +9,8 @@
 #define static
 extern "C" {
 #include "color-management-v1-protocol.h"
+#include "fractional-scale-v1-protocol.h"
+#include "viewporter-protocol.h"
 #include "wlr-layer-shell-unstable-v1-protocol.h"
 #include "xdg-output-unstable-v1-protocol.h"
 #include "xdg-shell-protocol.h"
@@ -44,8 +47,8 @@ static void handlePointerEnter (
 
     driver->viewportInFocus = viewport;
     viewport->pointerEntered = true;
-    viewport->mousePos = { wl_fixed_to_double (surface_x) * viewport->scale,
-			   (viewport->size.y - wl_fixed_to_double (surface_y)) * viewport->scale };
+    viewport->mousePos = { wl_fixed_to_double (surface_x) * viewport->renderScale (),
+			   (viewport->size.y - wl_fixed_to_double (surface_y)) * viewport->renderScale () };
     wl_surface_set_buffer_scale (viewport->cursorSurface, viewport->scale);
     wl_surface_attach (viewport->cursorSurface, wl_cursor_image_get_buffer (viewport->pointer->images[0]), 0, 0);
     wl_pointer_set_cursor (
@@ -82,7 +85,9 @@ static void handlePointerMotion (
     const double viewportHeight = static_cast<double> (driver->viewportInFocus->size.y);
     y = viewportHeight - y;
 
-    driver->viewportInFocus->mousePos = { x * driver->viewportInFocus->scale, y * driver->viewportInFocus->scale };
+    // buffer pixels, WE maps the cursor into the window's physical client area
+    const double scale = driver->viewportInFocus->renderScale ();
+    driver->viewportInFocus->mousePos = { x * scale, y * scale };
 }
 
 static void handlePointerButton (
@@ -116,8 +121,18 @@ constexpr struct wl_pointer_listener pointerListener = { .enter = handlePointerE
 							 .axis = handlePointerAxis };
 
 static void handleCapabilities (void* data, wl_seat* wl_seat, uint32_t capabilities) {
-    if (capabilities & WL_SEAT_CAPABILITY_POINTER) {
-	wl_pointer_add_listener (wl_seat_get_pointer (wl_seat), &pointerListener, data);
+    const auto driver = static_cast<WaylandOpenGLDriver*> (data);
+    auto* context = driver->getWaylandContext ();
+    const bool hasPointer = capabilities & WL_SEAT_CAPABILITY_POINTER;
+
+    // the capability comes and goes with the last pointer device (virtual pointers, unplugged mice)
+    if (hasPointer && !context->pointer) {
+	context->pointer = wl_seat_get_pointer (wl_seat);
+	wl_pointer_add_listener (context->pointer, &pointerListener, data);
+    } else if (!hasPointer && context->pointer) {
+	wl_pointer_destroy (context->pointer);
+	context->pointer = nullptr;
+	driver->viewportInFocus = nullptr;
     }
 }
 
@@ -196,6 +211,13 @@ handleGlobal (void* data, struct wl_registry* registry, uint32_t name, const cha
 	driver->getWaylandContext ()->seat
 	    = static_cast<wl_seat*> (wl_registry_bind (registry, name, &wl_seat_interface, 1));
 	wl_seat_add_listener (driver->getWaylandContext ()->seat, &seatListener, driver);
+    } else if (strcmp (interface, wp_viewporter_interface.name) == 0) {
+	driver->getWaylandContext ()->viewporter
+	    = static_cast<wp_viewporter*> (wl_registry_bind (registry, name, &wp_viewporter_interface, 1));
+    } else if (strcmp (interface, wp_fractional_scale_manager_v1_interface.name) == 0) {
+	driver->getWaylandContext ()->fractionalScaleManager = static_cast<wp_fractional_scale_manager_v1*> (
+	    wl_registry_bind (registry, name, &wp_fractional_scale_manager_v1_interface, 1)
+	);
     } else if (strcmp (interface, zxdg_output_manager_v1_interface.name) == 0) {
 	driver->getWaylandContext ()->xdgOutputManager = static_cast<zxdg_output_manager_v1*> (
 	    wl_registry_bind (registry, name, &zxdg_output_manager_v1_interface, std::min (version, 3u))
@@ -398,6 +420,16 @@ void WaylandOpenGLDriver::onLayerClose (Output::WaylandOutputViewport* viewport)
 	viewport->colorOutput = nullptr;
     }
 
+    if (viewport->fractionalScale) {
+	wp_fractional_scale_v1_destroy (viewport->fractionalScale);
+	viewport->fractionalScale = nullptr;
+    }
+
+    if (viewport->surfaceViewport) {
+	wp_viewport_destroy (viewport->surfaceViewport);
+	viewport->surfaceViewport = nullptr;
+    }
+
     if (viewport->layerSurface) {
 	zwlr_layer_surface_v1_destroy (viewport->layerSurface);
     }
@@ -476,7 +508,11 @@ void WaylandOpenGLDriver::initWaylandRegistry () {
     }
 
     if (!m_waylandContext.display) {
-	m_waylandContext.display = wl_display_connect (nullptr);
+	m_waylandContext.display = Desktop::connectWayland ();
+
+	if (Desktop::usesHostWayland ()) {
+	    sLog.out ("Flatpak's Wayland socket offers no layer shell, connected through the host instead");
+	}
     }
 
     if (!m_waylandContext.display) {

+ 5 - 0
src/WallpaperEngine/Render/Drivers/WaylandOpenGLDriver.h

@@ -29,6 +29,8 @@ struct zxdg_output_manager_v1;
 struct xdg_wm_base;
 struct wp_color_manager_v1;
 struct wp_image_description_v1;
+struct wp_viewporter;
+struct wp_fractional_scale_manager_v1;
 #ifdef ENABLE_KDE_FEATURES
 struct org_kde_plasma_shell;
 #endif
@@ -64,9 +66,12 @@ public:
 	/** GNOME only */
 	xdg_wm_base* xdgWmBase = nullptr;
 	wl_seat* seat = nullptr;
+	wl_pointer* pointer = nullptr;
 	zxdg_output_manager_v1* xdgOutputManager = nullptr;
 	/** Only bound with --hdr */
 	wp_color_manager_v1* colorManager = nullptr;
+	wp_viewporter* viewporter = nullptr;
+	wp_fractional_scale_manager_v1* fractionalScaleManager = nullptr;
 #ifdef ENABLE_KDE_FEATURES
 	org_kde_plasma_shell* plasmaShell = nullptr;
 #endif

+ 102 - 9
src/WallpaperEngine/Render/Objects/CSound.cpp

@@ -11,6 +11,7 @@
 #include <algorithm>
 #include <cfloat>
 #include <cmath>
+#include <limits>
 #include <random>
 
 using namespace WallpaperEngine::Render::Objects;
@@ -61,7 +62,20 @@ glm::vec2 stereoPan (const glm::vec3& direction, float distance) {
 } // namespace
 
 CSound::CSound (Wallpapers::CScene& scene, const Sound& sound) :
-    CObject (scene, sound), m_sound (sound), m_startSilent (sound.startsilent->value->getBool ()) {
+    CObject (scene, sound), ScriptableObject (scene, sound), m_sound (sound),
+    m_startSilent (sound.startsilent->value->getBool ()) {
+    // sub_1401F7090, playbackmode has no value to bind (layer_get reads it)
+    const std::pair<const char*, const UserSettingUniquePtr&> properties[] = {
+	{ "volume", sound.volume },           { "mintime", sound.mintime },
+	{ "maxtime", sound.maxtime },         { "attenuation", sound.attenuation },
+	{ "mindistance", sound.mindistance }, { "muteineditor", sound.muteineditor },
+	{ "startsilent", sound.startsilent }, { "spatialization", sound.spatialization },
+    };
+
+    for (const auto& [name, setting] : properties) {
+	this->registerProperty (name, *setting->value);
+    }
+
     this->m_lastStartSilent = this->m_startSilent;
     this->m_lastVolume
 	= this->m_sound.volume && this->m_sound.volume->value ? this->m_sound.volume->value->getFloat () : 1.0f;
@@ -132,6 +146,7 @@ void CSound::playVoice (Voice& voice, bool loop) {
 
     voice.streamId = audio.addStream (voice.stream.get (), SDL_MIX_MAXVOLUME, gains.x, gains.y);
     voice.state = VoiceState::Playing;
+    this->applyOutput (voice);
 }
 
 void CSound::pauseVoice (Voice& voice) {
@@ -143,8 +158,9 @@ void CSound::pauseVoice (Voice& voice) {
 }
 
 void CSound::stopVoice (Voice& voice) {
+    // alSourceStop: the voice mixes one more update without its buffer (only HRTF delay lines play out)
     if (voice.streamId >= 0) {
-	this->getScene ().getAudioContext ().removeStream (voice.streamId);
+	this->getScene ().getAudioContext ().stopStream (voice.streamId, std::move (voice.stream));
     }
 
     voice.stream.reset ();
@@ -302,6 +318,20 @@ bool CSound::isPlaying () const {
     return this->hasActiveVoice () && !this->m_paused;
 }
 
+void CSound::applyPlayback (Playback playback) {
+    switch (playback) {
+	case Playback::Playing:
+	    this->play ();
+	    break;
+	case Playback::Paused:
+	    this->pause ();
+	    break;
+	case Playback::Stopped:
+	    this->stop ();
+	    break;
+    }
+}
+
 void CSound::volumeChanged () {
     // sub_1401F4C20, also what a master volume change does to every sound (sub_1401816D0)
     const auto mode = this->m_sound.playbackmode;
@@ -423,9 +453,10 @@ glm::vec3 CSound::spatialPosition () const {
     return position;
 }
 
-glm::vec2 CSound::outputGains (const Voice& voice) const {
+CSound::SourceParams CSound::sourceParams (const Voice& voice) const {
     float gain = this->sourceGain ();
-    glm::vec2 channels (1.0f);
+    glm::vec3 direction (0.0f);
+    float distance = 0.0f;
 
     // OpenAL Soft only spatializes mono sources (AL_SOURCE_SPATIALIZE_SOFT defaults to auto), the others go straight
     // to their speakers; the source gain is clamped to AL_MAX_GAIN 1 on both paths
@@ -435,8 +466,8 @@ glm::vec2 CSound::outputGains (const Voice& voice) const {
 	const float reference = this->m_reference;
 	const float rolloff = this->m_rolloff;
 	const float limit = std::max (reference / 1024.0f, FLT_EPSILON);
-	glm::vec3 direction = this->m_position;
-	float distance = 0.0f;
+
+	direction = this->m_position;
 
 	if (glm::dot (direction, direction) > limit * limit) {
 	    distance = std::sqrt (glm::dot (direction, direction));
@@ -453,11 +484,54 @@ glm::vec2 CSound::outputGains (const Voice& voice) const {
 		gain *= reference / scaled;
 	    }
 	}
+    }
+
+    return { std::clamp (gain, 0.0f, 1.0f), direction, distance };
+}
+
+glm::vec2 CSound::outputGains (const Voice& voice) const {
+    const SourceParams source = this->sourceParams (voice);
 
-	channels = stereoPan (direction, distance);
+    if (voice.mono && this->getScene ().getAudioContext ().getChannels () == 2) {
+	return source.gain * stereoPan (source.direction, source.distance);
     }
 
-    return std::clamp (gain, 0.0f, 1.0f) * channels;
+    return glm::vec2 (source.gain);
+}
+
+Audio::Drivers::StreamHrtf CSound::hrtfOutput (const Voice& voice, const Audio::Hrtf::Store& hrtf) const {
+    // alu.cpp CalcPanningAndFilters, RenderMode::Hrtf (sub_180192310 in mediaextensions64.dll)
+    const SourceParams source = this->sourceParams (voice);
+    Audio::Drivers::StreamHrtf output;
+
+    if (voice.mono) {
+	output.channels = 1;
+
+	// a source on the listener plays as a virtual speaker in front, at infinite distance; WE never sets
+	// AL_SOURCE_RADIUS, so the spread is 0
+	if (source.distance > FLT_EPSILON) {
+	    const float elevation = std::asin (std::clamp (source.direction.y, -1.0f, 1.0f));
+	    const float azimuth = std::atan2 (source.direction.x, -source.direction.z);
+
+	    Audio::Hrtf::getCoeffs (hrtf, elevation, azimuth, source.distance, 0.0f, output.filters[0]);
+	} else {
+	    Audio::Hrtf::getCoeffs (hrtf, 0.0f, 0.0f, std::numeric_limits<float>::infinity (), 0.0f, output.filters[0]);
+	}
+
+	output.filters[0].gain = source.gain;
+	return output;
+    }
+
+    // stereo files aren't spatialized, each channel is a virtual speaker at AL_STEREO_ANGLES' default -30/+30 degrees
+    const float angle = 30.0f * glm::pi<float> () / 180.0f;
+
+    output.channels = 2;
+    Audio::Hrtf::getCoeffs (hrtf, 0.0f, -angle, std::numeric_limits<float>::infinity (), 0.0f, output.filters[0]);
+    Audio::Hrtf::getCoeffs (hrtf, 0.0f, angle, std::numeric_limits<float>::infinity (), 0.0f, output.filters[1]);
+    output.filters[0].gain = source.gain;
+    output.filters[1].gain = source.gain;
+
+    return output;
 }
 
 void CSound::applyOutput (const Voice& voice) const {
@@ -465,9 +539,28 @@ void CSound::applyOutput (const Voice& voice) const {
 	return;
     }
 
+    const auto& audio = this->getScene ().getAudioContext ();
+    const auto* hrtf = audio.getHrtf ();
+    const AppliedOutput applied { voice.streamId, hrtf, this->sourceParams (voice) };
+
+    if (voice.applied.streamId == applied.streamId && voice.applied.hrtf == applied.hrtf
+	&& voice.applied.source == applied.source) {
+	return;
+    }
+
+    voice.applied = applied;
+
+    if (hrtf != nullptr) {
+	const auto output = this->hrtfOutput (voice, *hrtf);
+
+	audio.setStreamHrtf (voice.streamId, &output);
+	return;
+    }
+
     const glm::vec2 gains = this->outputGains (voice);
 
-    this->getScene ().getAudioContext ().setStreamGains (voice.streamId, gains.x, gains.y);
+    audio.setStreamHrtf (voice.streamId, nullptr);
+    audio.setStreamGains (voice.streamId, gains.x, gains.y);
 }
 
 void CSound::applyOutput () const {

+ 28 - 4
src/WallpaperEngine/Render/Objects/CSound.h

@@ -7,7 +7,8 @@
 #include <glm/vec3.hpp>
 
 #include "WallpaperEngine/Audio/AudioStream.h"
-#include "WallpaperEngine/Render/CObject.h"
+#include "WallpaperEngine/Audio/Drivers/AudioDriver.h"
+#include "WallpaperEngine/Scripting/ScriptableObject.h"
 
 using namespace WallpaperEngine;
 
@@ -23,9 +24,10 @@ using namespace WallpaperEngine::Data::Model;
  * at a time: play() stops them all and starts a random one. Loop mode loops a single file and otherwise moves on to
  * another random file when the current one is over, random mode waits mintime..maxtime between files, single plays
  * one file once. WE plays them through OpenAL Soft 1.21.1 (mediaextensions64.dll), whose speaker panning and distance
- * attenuation are reproduced here for mono files.
+ * attenuation are reproduced here for mono files. Its properties take scripts like any object's (WE's generic loaders,
+ * sub_1401A4B00 -> sub_1401A4DB0 with the sound as owner).
  */
-class CSound final : public CObject {
+class CSound final : public Scripting::ScriptableObject {
 public:
     CSound (Wallpapers::CScene& scene, const Sound& sound);
     ~CSound () override;
@@ -40,11 +42,27 @@ public:
     void play ();
     void stop ();
     void pause ();
-    [[nodiscard]] bool isPlaying () const;
+    [[nodiscard]] bool isPlaying () const override;
+    void applyPlayback (Playback playback) override;
 
 private:
     enum class VoiceState { Stopped, Paused, Playing };
 
+    struct SourceParams {
+	float gain;
+	glm::vec3 direction;
+	float distance;
+
+	bool operator== (const SourceParams&) const = default;
+    };
+
+    /** What applyOutput last handed the driver, so an unchanged voice skips the HRTF coefficients and the lock */
+    struct AppliedOutput {
+	int streamId = -1;
+	const Audio::Hrtf::Store* hrtf = nullptr;
+	SourceParams source {};
+    };
+
     struct Voice {
 	std::string file;
 	std::unique_ptr<Audio::AudioStream> stream;
@@ -52,6 +70,7 @@ private:
 	float duration = 0.0f;
 	bool mono = false;
 	VoiceState state = VoiceState::Stopped;
+	mutable AppliedOutput applied;
     };
 
     void loadVoices ();
@@ -70,8 +89,13 @@ private:
     [[nodiscard]] float sourceGain () const;
     /** Where WE puts the sound in OpenAL's listener space (sub_1401F5460) */
     [[nodiscard]] glm::vec3 spatialPosition () const;
+    /** What OpenAL's source update works out for a voice: the clamped gain, and for mono files direction and distance
+     */
+    [[nodiscard]] SourceParams sourceParams (const Voice& voice) const;
     /** Left and right gain of a voice: AL_GAIN, and for mono files OpenAL's distance attenuation and panning */
     [[nodiscard]] glm::vec2 outputGains (const Voice& voice) const;
+    /** The voice's HRTF filters while the output renders for headphones (OpenAL's "full" HRTF mode) */
+    [[nodiscard]] Audio::Drivers::StreamHrtf hrtfOutput (const Voice& voice, const Audio::Hrtf::Store& hrtf) const;
     void applyOutput (const Voice& voice) const;
     void applyOutput () const;
 

+ 31 - 10
src/WallpaperEngine/Render/Wallpapers/CScene.cpp

@@ -14,6 +14,7 @@
 #include "CScene.h"
 #include "WallpaperEngine/Logging/Log.h"
 #include "WallpaperEngine/Scripting/ScriptableObject.h"
+#include "WallpaperEngine/VideoPlayback/MPV/GLPlayer.h"
 
 #include "WallpaperEngine/Data/Model/Wallpaper.h"
 #include "WallpaperEngine/Data/Parsers/MaterialParser.h"
@@ -430,25 +431,41 @@ ScriptEngine& CScene::getScriptEngine () const { return *this->m_scriptEngine; }
 Camera& CScene::getCamera () const { return *this->m_camera; }
 
 namespace {
-// with LWE_FRAME_STATS set, any single step of a scene frame slower than this is logged by name
-constexpr double STALL_THRESHOLD_MS = 15.0;
+// with LWE_FRAME_STATS set, any single step of a scene frame slower than this is logged by name, LWE_FRAME_STALL_MS
+// changes it (0 logs every step)
+double stallThresholdMs () {
+    const char* value = std::getenv ("LWE_FRAME_STALL_MS");
+    char* end = nullptr;
+    const double ms = value ? std::strtod (value, &end) : 0.0;
+
+    return end != value && ms >= 0.0 ? ms : 15.0;
+}
 
 template <typename Step> void timeStep (const std::string& label, Step&& step) {
     static const bool enabled = std::getenv ("LWE_FRAME_STATS") != nullptr;
+    static const double threshold = stallThresholdMs ();
 
     if (!enabled) {
 	step ();
 	return;
     }
 
+    GLuint queries[2];
+    glGenQueries (2, queries);
     glFinish ();
     const auto start = std::chrono::steady_clock::now ();
+    glQueryCounter (queries[0], GL_TIMESTAMP);
     step ();
+    glQueryCounter (queries[1], GL_TIMESTAMP);
     glFinish ();
     const double ms = std::chrono::duration<double, std::milli> (std::chrono::steady_clock::now () - start).count ();
+    GLuint64 gpuStart = 0, gpuEnd = 0;
+    glGetQueryObjectui64v (queries[0], GL_QUERY_RESULT, &gpuStart);
+    glGetQueryObjectui64v (queries[1], GL_QUERY_RESULT, &gpuEnd);
+    glDeleteQueries (2, queries);
 
-    if (ms >= STALL_THRESHOLD_MS) {
-	sLog.out ("FRAME-STALL ", label, ": ", ms, "ms");
+    if (ms >= threshold) {
+	sLog.out ("FRAME-STALL ", label, ": ", ms, "ms (gpu ", (gpuEnd - gpuStart) / 1e6, "ms)");
     }
 }
 }
@@ -466,6 +483,7 @@ void CScene::renderFrameSteps (const glm::ivec4& viewport) {
     // wallpaper64.exe sub_14017FA70 counts every frame (scene render object +340, zeroed by sub_14017C6D0) before
     // anything is simulated, boids pick their sample block with it
     this->m_frameCounter++;
+    VideoPlayback::MPV::GLPlayer::advanceFrame ();
     timeStep ("updateMouse", [&] { this->updateMouse (viewport); });
 
     // WE: init () while loading, then the static camera (sub_140186C90), then the first update
@@ -1313,7 +1331,8 @@ void CScene::updateParallax () {
 	    // too, before the smoothing (sub_1401891A0); y up, the cursor is flipped, the eye isn't
 	    const glm::vec2 eye = { this->m_cameraEye.x / static_cast<float> (this->getWidth ()),
 				    this->m_cameraEye.y / static_cast<float> (this->getHeight ()) };
-	    const glm::vec2 cursor = { this->m_mousePosition.x, 1.0f - this->m_mousePosition.y };
+	    const glm::vec2 cursor
+		= glm::clamp (glm::vec2 (this->m_mousePosition.x, 1.0f - this->m_mousePosition.y), 0.0f, 1.0f);
 	    const glm::vec2 target = (cursor - glm::vec2 (0.5f, 0.5f)) * influence + eye;
 	    if (delay <= 0.0f) {
 		this->m_cameraParallax = target;
@@ -1757,8 +1776,7 @@ void CScene::dispatchCursorEvents () {
 	return;
     }
 
-    const bool down
-	= this->getContext ().getInputContext ().getMouseInput ().leftClick () == Input::MouseClickStatus::Clicked;
+    const bool down = this->cursorLeftClick () == Input::MouseClickStatus::Clicked;
     const bool pressed = down && !this->m_cursorLeftDown;
     const bool released = !down && this->m_cursorLeftDown;
     this->m_cursorLeftDown = down;
@@ -1900,12 +1918,15 @@ void CScene::dispatchCursorEvents () {
 }
 
 void CScene::updateMouse (const glm::ivec4& viewport) {
-    const glm::dvec2 position = this->getContext ().getInputContext ().getMouseInput ().position ();
+    const glm::dvec2 position = this->cursorPosition ();
 
     this->m_pointerPositionLast = this->m_pointerPosition;
     this->m_mousePositionViewport = glm::vec2 (position.x - viewport.x, position.y - viewport.y);
 
-    double mouseX = glm::clamp ((position.x - viewport.x) / viewport.z, 0.0, 1.0);
+    // not clamped: WE stores ScreenToClient over the client size as is (sub_140110630, renderer +140/+144), so a
+    // pointer off the window or on another monitor reaches scripts, events and g_PointerPosition outside 0..1; only
+    // the parallax clamps it (sub_1401891A0)
+    double mouseX = (position.x - viewport.x) / viewport.z;
 
     // WE flips by mirroring its projection, so the cursor lands on what is shown under it
     if (this->isFlippedHorizontally ()) {
@@ -1913,7 +1934,7 @@ void CScene::updateMouse (const glm::ivec4& viewport) {
     }
 
     // OpenGL convention (0=bottom, 1=top) - particle code expects 0=bottom as negative Y (down)
-    double normalizedMouseY = glm::clamp ((position.y - viewport.y) / viewport.w, 0.0, 1.0);
+    double normalizedMouseY = (position.y - viewport.y) / viewport.w;
 
     // the scene buffer holds what the output shows, the visible region maps the cursor onto the scene
     const glm::vec4 output = this->getOutputUVs ();

+ 1 - 1
src/WallpaperEngine/Render/Wallpapers/CSplat.cpp

@@ -1101,7 +1101,7 @@ void CSplat::renderFrame (const glm::ivec4& viewport) {
     const auto& settings = this->getContext ().getApp ().getContext ().settings;
 
     if (depthEnabled && !settings.mouse.disableparallax) {
-	const glm::dvec2 mouse = this->getContext ().getInputContext ().getMouseInput ().position ();
+	const glm::dvec2 mouse = this->cursorPosition ();
 	const float sensitivity = static_cast<float> (this->numberProperty ("sensorSensitivity", 4.0)) / 4.0f;
 	const float normalizedX = std::clamp (static_cast<float> ((mouse.x - viewport.x) / viewport.z), 0.0f, 1.0f);
 	const float normalizedY = std::clamp (static_cast<float> ((mouse.y - viewport.y) / viewport.w), 0.0f, 1.0f);

+ 2 - 0
src/WallpaperEngine/Render/Wallpapers/CVideo.cpp

@@ -53,6 +53,8 @@ void CVideo::renderFrame (const glm::ivec4& viewport) {
     this->updateMuteState ();
 
     this->m_presentBackBuffer = false;
+    // WE draws a video wallpaper as the texture of materials/background.json, shown every frame
+    this->m_player->markUsed ();
     this->m_player->render ();
 
     // mpv reallocates the texture at the video's size later, the CFBO was made at 16x16

+ 2 - 2
src/WallpaperEngine/Render/Wallpapers/CWeb.cpp

@@ -466,7 +466,7 @@ void CWeb::updateMedia () {
 void CWeb::updateMouse (const glm::ivec4& viewport) {
     auto& input = this->getContext ().getInputContext ().getMouseInput ();
 
-    const glm::dvec2 position = input.position ();
+    const glm::dvec2 position = this->cursorPosition ();
 
     // Convert from OpenGL coordinates (Y=0 at bottom) to CEF coordinates (Y=0 at top). Written
     // unconditionally every frame - cheap atomic stores, and the host process itself only forwards
@@ -476,7 +476,7 @@ void CWeb::updateMouse (const glm::ivec4& viewport) {
 
     this->m_shm->mouseX.store (static_cast<double> (x), std::memory_order_relaxed);
     this->m_shm->mouseY.store (static_cast<double> (y), std::memory_order_relaxed);
-    this->m_shm->leftClick.store (static_cast<int32_t> (input.leftClick ()), std::memory_order_relaxed);
+    this->m_shm->leftClick.store (static_cast<int32_t> (this->cursorLeftClick ()), std::memory_order_relaxed);
     this->m_shm->rightClick.store (static_cast<int32_t> (input.rightClick ()), std::memory_order_relaxed);
 }
 

+ 185 - 78
src/WallpaperEngine/Scripting/Adapters/ScriptableObjectAdapter.cpp

@@ -282,66 +282,77 @@ void effect_call (const v8::FunctionCallbackInfo<v8::Value>& info, int get) {
     }
 }
 
-// video textures are only ever reached through the player's address, kept alive by the layer's texture for as long as
-// the scene exists
+// the layer's video player, null once the layer or its texture is gone
+WallpaperEngine::VideoPlayback::MPV::GLPlayer* videoPlayerOf (const Layer& layer) {
+    if (layer.object == nullptr || !layer.object->is<CImage> ()) {
+	return nullptr;
+    }
+
+    const auto texture = layer.object->as<CImage> ()->getTexture ();
+
+    return texture == nullptr ? nullptr : texture->getPlayer ();
+}
+
+enum VideoTextureCall {
+    VideoPlay,
+    VideoPause,
+    VideoStop,
+    VideoIsPlaying,
+    VideoSetCurrentTime,
+    VideoGetCurrentTime,
+    VideoAddEndedCallback,
+};
+
+// IVideoTexture methods (wallpaper64 2.8.42 sub_140214050, bodies sub_1401FA510..sub_1401FA730)
 void videotexture_call (const v8::FunctionCallbackInfo<v8::Value>& info, int call) {
-    auto* player = JS::unwrap<WallpaperEngine::VideoPlayback::MPV::GLPlayer> (info.Data ());
+    auto* layer = JS::unwrap<Layer> (info.Data ());
+    auto* player = layer == nullptr ? nullptr : videoPlayerOf (*layer);
     const auto context = info.GetIsolate ()->GetCurrentContext ();
 
+    if (player == nullptr || layer->videoTextureState == nullptr) {
+	return;
+    }
+
+    auto& state = *layer->videoTextureState;
+
     switch (call) {
-	case 0:
+	case VideoPlay:
 	    if (player->hasEnded ()) {
 		player->seek (0.0);
 	    }
 
 	    player->clearPaused ();
 	    return;
-	case 1:
+	case VideoPause:
 	    player->setPaused ();
 	    return;
-	case 2:
+	case VideoStop:
+	    // a looping video would see the jump back as a wrap
+	    if (state.loop) {
+		state.armed = false;
+	    }
+
 	    player->setPaused ();
 	    player->seek (0.0);
 	    return;
-	case 3:
-	    info.GetReturnValue ().Set (!player->isPaused ());
-	    return;
-	case 4:
-	    info.GetReturnValue ().Set (player->isPaused ());
-	    return;
-	case 5:
-	    info.GetReturnValue ().Set (player->isPaused () && player->getPlaybackPosition () < 0.001);
+	case VideoIsPlaying:
+	    info.GetReturnValue ().Set (!player->isPaused () && !player->hasEnded ());
 	    return;
-	case 6:
-	    info.GetReturnValue ().Set (player->getPlaybackPosition ());
-	    return;
-	case 7:
+	case VideoSetCurrentTime:
 	    if (double seconds = 0.0; info.Length () > 0 && info[0]->NumberValue (context).To (&seconds)) {
-		player->seek (std::max (seconds, 0.0));
-	    }
-	    return;
-	case 8:
-	    if (info.Length () > 0) {
-		engineOf (info).addVideoEndedCallback (player, info[0]);
-	    }
-	    return;
-	case 9:
-	    info.GetReturnValue ().Set (player->isLooping ());
-	    return;
-	case 10:
-	    if (info.Length () > 0) {
-		player->setLoop (info[0]->BooleanValue (info.GetIsolate ()));
+		if (state.loop) {
+		    state.armed = false;
+		}
+
+		player->seek (std::max (static_cast<double> (static_cast<float> (seconds)), 0.0));
 	    }
 	    return;
-	case 11:
-	    info.GetReturnValue ().Set (player->getDuration ());
-	    return;
-	case 12:
-	    info.GetReturnValue ().Set (player->getSpeed ());
+	case VideoGetCurrentTime:
+	    info.GetReturnValue ().Set (static_cast<float> (player->getPlaybackPosition ()));
 	    return;
-	case 13:
-	    if (double rate = 0.0; info.Length () > 0 && info[0]->NumberValue (context).To (&rate) && rate > 0.0) {
-		player->setSpeed (rate);
+	case VideoAddEndedCallback:
+	    if (info.Length () > 0 && info[0]->IsFunction ()) {
+		state.endedCallbacks.emplace_back (info.GetIsolate (), info[0].As<v8::Function> ());
 	    }
 	    return;
 	default:
@@ -349,38 +360,6 @@ void videotexture_call (const v8::FunctionCallbackInfo<v8::Value>& info, int cal
     }
 }
 
-v8::Local<v8::Object>
-videotexture_instantiate (ScriptEngine& engine, WallpaperEngine::VideoPlayback::MPV::GLPlayer& player) {
-    auto* isolate = engine.getIsolate ();
-    const auto context = engine.getContext ();
-    const v8::Local<v8::Object> handle = v8::Object::New (isolate);
-    const auto data = JS::external (isolate, &player);
-    const auto method = [&] (const char* name, v8::FunctionCallback callback, int length) {
-	JS::set (context, handle, name, JS::function (context, callback, data, length));
-    };
-    const auto property = [&] (const char* name, v8::FunctionCallback getter, v8::FunctionCallback setter) {
-	handle->SetAccessorProperty (
-	    JS::name (isolate, name), JS::function (context, getter, data), JS::function (context, setter, data, 1)
-	);
-    };
-
-    method ("play", JS::bind<videotexture_call, 0>, 0);
-    method ("pause", JS::bind<videotexture_call, 1>, 0);
-    method ("stop", JS::bind<videotexture_call, 2>, 0);
-    method ("isPlaying", JS::bind<videotexture_call, 3>, 0);
-    method ("isPaused", JS::bind<videotexture_call, 4>, 0);
-    method ("isStopped", JS::bind<videotexture_call, 5>, 0);
-    method ("getCurrentTime", JS::bind<videotexture_call, 6>, 0);
-    method ("setCurrentTime", JS::bind<videotexture_call, 7>, 1);
-    method ("addEndedCallback", JS::bind<videotexture_call, 8>, 1);
-    property ("loop", JS::bind<videotexture_call, 9>, JS::bind<videotexture_call, 10>);
-    // "duration" gets an ignoring setter (14) since strict mode scripts throw on a property with none
-    property ("duration", JS::bind<videotexture_call, 11>, JS::bind<videotexture_call, 14>);
-    property ("rate", JS::bind<videotexture_call, 12>, JS::bind<videotexture_call, 13>);
-
-    return handle;
-}
-
 enum TextureAnimationCall {
     TexturePlay,
     TexturePause,
@@ -1032,16 +1011,13 @@ void layer_animation_layer_call (const v8::FunctionCallbackInfo<v8::Value>& info
 
 // scripts call this on image layers whose material is a video (mp4 texture), everything else gets null
 void video_texture_call (const v8::FunctionCallbackInfo<v8::Value>& info) {
-    auto* image = imageOf (info.Data ());
-    const auto texture = image == nullptr ? nullptr : image->getTexture ();
+    auto* layer = JS::unwrap<Layer> (info.Data ());
 
     info.GetReturnValue ().SetNull ();
 
-    if (texture == nullptr || texture->getPlayer () == nullptr) {
-	return;
+    if (layer != nullptr && videoPlayerOf (*layer) != nullptr) {
+	info.GetReturnValue ().Set (engineOf (info).getAdapters ().object->videoTexture (*layer));
     }
-
-    info.GetReturnValue ().Set (videotexture_instantiate (engineOf (info), *texture->getPlayer ()));
 }
 
 enum BoneCall {
@@ -1712,6 +1688,12 @@ constexpr std::string_view LightProperties[] = {
     "radius",           "lightsourcesize",     "density",    "intensity", "color",        "innercone",
 };
 constexpr std::string_view CameraProperties[] = { "visible", "fov", "zoom", "queuemode" };
+// sub_1401F7090, order and the missing "visible" as live WE lists them (tests/keyorder make_sound.py)
+constexpr std::string_view SoundProperties[] = {
+    "spatialization", "mindistance", "maxtime",      "mintime", "muteineditor",
+    "startsilent",    "attenuation", "playbackmode", "volume",
+};
+constexpr std::string_view SoundMethods[] = { "play", "isPlaying", "pause", "stop" };
 
 struct LayerMember {
     std::string_view name;
@@ -1755,6 +1737,8 @@ std::vector<LayerMember> layerMembers (const ScriptableObject& object) {
 	build (LightProperties, false, none);
     } else if (model.is<SceneCamera> ()) {
 	build (CameraProperties, false, none);
+    } else if (model.is<Sound> ()) {
+	build (SoundProperties, false, SoundMethods);
     } else {
 	build (GroupProperties, false, none);
     }
@@ -1847,6 +1831,10 @@ void layer_get (v8::Local<v8::Name> property, const v8::PropertyCallbackInfo<v8:
 	info.GetReturnValue ().Set (object.getObject ().id);
     } else if (name == "instance" && object.is<CParticle> ()) {
 	info.GetReturnValue ().Set (engine.getAdapters ().object->particleInstance (*layer));
+    } else if (name == "playbackmode" && object.getObject ().is<Sound> ()) {
+	constexpr const char* modes[] = { "single", "loop", "random" };
+
+	info.GetReturnValue ().Set (JS::string (isolate, modes[object.getObject ().as<Sound> ()->playbackmode]));
     } else if (name == "size") {
 	if (const auto size = renderableSize (object)) {
 	    info.GetReturnValue ().Set (engine.getAdapters ().vec2->create (*size));
@@ -1982,6 +1970,8 @@ void ScriptableObjectAdapter::forget (const ScriptableObject& object) {
     it->second->instance.Reset ();
     it->second->textureAnimation.Reset ();
     it->second->particleInstance.Reset ();
+    it->second->videoTexture.Reset ();
+    it->second->videoTextureState.reset ();
     this->m_forgotten.push_back (std::move (it->second));
     this->m_layers.erase (it);
 }
@@ -2106,6 +2096,123 @@ v8::Local<v8::Value> ScriptableObjectAdapter::textureAnimation (Layer& layer) {
     return result;
 }
 
+v8::Local<v8::Value> ScriptableObjectAdapter::videoTexture (Layer& layer) {
+    auto* isolate = this->m_engine.getIsolate ();
+    const auto context = this->m_engine.getContext ();
+
+    if (!layer.videoTexture.IsEmpty ()) {
+	return layer.videoTexture.Get (isolate);
+    }
+
+    layer.videoTextureState = std::make_unique<VideoTexture> ();
+
+    // the properties keep their own values like WE's typed members: a float only takes numbers, a bool only
+    // booleans (sub_1401A4B00, sub_1401A4A20), the change callback runs after every write either way
+    // (sub_1401FA6D0, sub_1401FA700). duration is read only (+96 = 2)
+    Layer* owner = &layer;
+    std::vector<NativeProperty> properties = {
+	{ .name = "rate",
+	  .get = [isolate, owner] () -> v8::Local<v8::Value> {
+	      return v8::Number::New (isolate, owner->videoTextureState ? owner->videoTextureState->rate : 0.0f);
+	  },
+	  .set =
+	      [owner] (v8::Local<v8::Value> value) {
+		  auto* player = videoPlayerOf (*owner);
+
+		  if (player == nullptr || owner->videoTextureState == nullptr) {
+		      return;
+		  }
+
+		  auto& state = *owner->videoTextureState;
+
+		  if (value->IsNumber ()) {
+		      state.rate = static_cast<float> (value.As<v8::Number> ()->Value ());
+		  }
+
+		  // WE hands any rate to the media engine, mpv only plays forwards
+		  if (state.rate > 0.0f) {
+		      player->setSpeed (state.rate);
+		  }
+	      } },
+	{ .name = "loop",
+	  .get = [isolate, owner] () -> v8::Local<v8::Value> {
+	      return v8::Boolean::New (isolate, owner->videoTextureState && owner->videoTextureState->loop);
+	  },
+	  .set =
+	      [owner] (v8::Local<v8::Value> value) {
+		  auto* player = videoPlayerOf (*owner);
+
+		  if (player == nullptr || owner->videoTextureState == nullptr) {
+		      return;
+		  }
+
+		  if (value->IsBoolean ()) {
+		      owner->videoTextureState->loop = value.As<v8::Boolean> ()->Value ();
+		  }
+
+		  player->setLoop (owner->videoTextureState->loop);
+	      } },
+	{ .name = "duration",
+	  .get = [isolate, owner] () -> v8::Local<v8::Value> {
+	      auto* player = videoPlayerOf (*owner);
+	      return v8::Number::New (isolate, player == nullptr ? 0.0f : static_cast<float> (player->getDuration ()));
+	  } },
+    };
+
+    const auto data = JS::external (isolate, &layer);
+    const std::vector<std::pair<std::string, v8::Local<v8::Function>>> methods = {
+	{ "play", JS::function (context, JS::bind<videotexture_call, VideoPlay>, data) },
+	{ "pause", JS::function (context, JS::bind<videotexture_call, VideoPause>, data) },
+	{ "stop", JS::function (context, JS::bind<videotexture_call, VideoStop>, data) },
+	{ "isPlaying", JS::function (context, JS::bind<videotexture_call, VideoIsPlaying>, data) },
+	{ "setCurrentTime", JS::function (context, JS::bind<videotexture_call, VideoSetCurrentTime>, data) },
+	{ "getCurrentTime", JS::function (context, JS::bind<videotexture_call, VideoGetCurrentTime>, data) },
+	{ "addEndedCallback", JS::function (context, JS::bind<videotexture_call, VideoAddEndedCallback>, data) },
+    };
+
+    const auto result = this->makeNativeObject (std::move (properties), methods);
+    layer.videoTexture.Reset (isolate, result);
+    return result;
+}
+
+std::vector<v8::Local<v8::Function>> ScriptableObjectAdapter::takeDueVideoEndedCallbacks () {
+    auto* isolate = this->m_engine.getIsolate ();
+    std::vector<v8::Local<v8::Function>> due;
+
+    for (const auto& [object, layer] : this->m_layers) {
+	auto* player = videoPlayerOf (*layer);
+
+	if (player == nullptr || layer->videoTextureState == nullptr) {
+	    continue;
+	}
+
+	auto& state = *layer->videoTextureState;
+	bool fire = false;
+
+	// looping: the time going back is the end, unless stop () or setCurrentTime () disarmed it this frame
+	if (state.loop) {
+	    const float time = static_cast<float> (player->getPlaybackPosition ());
+
+	    fire = !state.endedCallbacks.empty () && state.lastTime > time && state.armed;
+	    state.armed = true;
+	    state.lastTime = time;
+	} else if (player->hasEnded ()) {
+	    fire = state.armed && !state.endedCallbacks.empty ();
+	    state.armed = false;
+	} else {
+	    state.armed = true;
+	}
+
+	if (fire) {
+	    for (const auto& callback : state.endedCallbacks) {
+		due.push_back (callback.Get (isolate));
+	    }
+	}
+    }
+
+    return due;
+}
+
 v8::Local<v8::Value> ScriptableObjectAdapter::animation (int systemId, int clockId) {
     auto* isolate = this->m_engine.getIsolate ();
     const auto context = this->m_engine.getContext ();

+ 15 - 0
src/WallpaperEngine/Scripting/Adapters/ScriptableObjectAdapter.h

@@ -41,6 +41,15 @@ struct NativeProperty {
     std::function<void (v8::Local<v8::Value>)> set = nullptr;
 };
 
+/** IVideoTexture state, wallpaper64 2.8.42 sub_14020E7B0 (+232..+264 of the object it keeps at layer +1216) */
+struct VideoTexture {
+    float rate = 1.0f;
+    bool loop = true;
+    float lastTime = 0.0f;
+    bool armed = true;
+    std::vector<v8::Global<v8::Function>> endedCallbacks = {};
+};
+
 /** What scripts reach a layer through. Outlives the layer, `object` is cleared when it goes */
 struct Layer {
     ScriptableObject* object;
@@ -51,6 +60,9 @@ struct Layer {
     v8::Global<v8::Object> textureAnimation;
     /** IParticleSystemInstance of a particle layer, the instance override struct (+1912) */
     v8::Global<v8::Object> particleInstance;
+    /** IVideoTexture of an image layer with a video texture, one per layer like WE's */
+    v8::Global<v8::Object> videoTexture;
+    std::unique_ptr<VideoTexture> videoTextureState;
 };
 
 /** IAnimationLayer (wallpaper64 2.8.42 sub_14026C980) for the puppet animation layer with that serial */
@@ -73,6 +85,9 @@ public:
 
     v8::Local<v8::Value> textureAnimation (Layer& layer);
     v8::Local<v8::Value> particleInstance (Layer& layer);
+    v8::Local<v8::Value> videoTexture (Layer& layer);
+    /** Steps every IVideoTexture's ended state for this frame, returns the callbacks due now (sub_1401FDF90) */
+    std::vector<v8::Local<v8::Function>> takeDueVideoEndedCallbacks ();
     /** IEffect of one of an image's effects, one JS object per effect */
     v8::Local<v8::Value> effect (Data::Model::ImageEffect& effect);
     /** one JS object per material, null without one */

+ 10 - 3
src/WallpaperEngine/Scripting/SceneObject.cpp

@@ -137,8 +137,9 @@ void bindSceneSettings (SceneObject& scene, v8::Local<v8::Object> instance, std:
     (bindSceneSetting<indices> (scene, instance), ...);
 }
 
-// Sound objects aren't ScriptableObjects, so getLayer() hands scripts a handle with just the playback calls;
-// it goes through the scene by id because sounds may not exist yet while init() runs. data is [id, startsilent]
+// A sound that doesn't exist yet (init () runs while the scene is still being built) is a handle with just the playback
+// calls, going through the scene by id; once the CSound is there getLayer() returns its layer. data is [id,
+// startsilent]
 void sound_layer_call (const v8::FunctionCallbackInfo<v8::Value>& info, int call) {
     auto& scene = sceneOf (info).getScene ();
     const auto context = info.GetIsolate ()->GetCurrentContext ();
@@ -221,7 +222,13 @@ void get_layer (const v8::FunctionCallbackInfo<v8::Value>& info) {
 
 	for (const auto& data : container.getScene ().getScene ().objects) {
 	    if (data->name == name && data->is<Sound> ()) {
-		info.GetReturnValue ().Set (instantiate_sound_layer (engine, *data->as<Sound> ()));
+		auto* sound = container.getScene ().getObject (data->id);
+
+		info.GetReturnValue ().Set (
+		    sound != nullptr && !container.getScene ().isPendingDestroy (*sound)
+			? instantiate_layer (engine, sound)
+			: instantiate_sound_layer (engine, *data->as<Sound> ())
+		);
 		return;
 	    }
 	}

+ 90 - 120
src/WallpaperEngine/Scripting/ScriptEngine.cpp

@@ -31,6 +31,7 @@
 #include <ctime>
 #include <filesystem>
 #include <future>
+#include <map>
 #include <optional>
 #include <ranges>
 #include <sstream>
@@ -425,7 +426,6 @@ ScriptEngine::~ScriptEngine () {
 
     // every handle has to go before the isolate does
     this->m_scriptModules.clear ();
-    this->m_videoEndedCallbacks.clear ();
     this->m_animationLayerEndedCallbacks.clear ();
     this->m_imports.clear ();
 
@@ -845,7 +845,7 @@ bool ScriptEngine::rebindScript (const std::string& key, DynamicValue& newValue)
 
     // LoadedModule::value is a reference member, so the entry is erased and re-emplaced under the same key,
     // m_runningModule may currently point at the erased entry
-    // the cached thisObject points at the old value, the replacement builds its own
+    // owners other than the layer set their thisObjectFactory again after registering
     LoadedModule replacement { .value = newValue,
 			       .module = std::move (it->second.module),
 			       .object = it->second.object,
@@ -956,45 +956,6 @@ void ScriptEngine::queueScript (
     // init() and the first update() run from tick(), once the whole scene has been constructed
 }
 
-namespace {
-// thisObject.getAnimation(): data is [animation system id, the property's DynamicValue]
-void this_object_get_animation (const v8::FunctionCallbackInfo<v8::Value>& info) {
-    auto* isolate = info.GetIsolate ();
-    const auto context = isolate->GetCurrentContext ();
-    const int systemId = JS::dataAt (info, 0)->Int32Value (context).FromMaybe (0);
-    auto* value = JS::unwrap<DynamicValue> (JS::dataAt (info, 1));
-
-    auto* system = AnimationSystem::find (systemId);
-    auto* clock = system == nullptr || value == nullptr ? nullptr : system->clockOf (*value);
-
-    if (clock == nullptr) {
-	info.GetReturnValue ().SetNull ();
-	return;
-    }
-
-    info.GetReturnValue ().Set (
-	ScriptEngine::from (isolate).getAdapters ().object->animation (systemId, clock->getId ())
-    );
-}
-
-// thisObject.<property name>: lets a listener registered by a property's script write that property
-// from outside (`listener.thisObject['Inner Color'] = color`). data is [the property's DynamicValue, is angles]
-void this_object_property (const v8::FunctionCallbackInfo<v8::Value>& info, int magic) {
-    auto& engine = ScriptEngine::from (info.GetIsolate ());
-    auto* value = JS::unwrap<DynamicValue> (JS::dataAt (info, 0));
-    const std::string_view name = JS::dataAt (info, 1)->IsTrue () ? "angles" : "";
-
-    if (magic == 0) {
-	info.GetReturnValue ().Set (engine.propertyToJs (*value, name));
-	return;
-    }
-
-    if (info.Length () > 0) {
-	engine.assignPropertyJsValue (info[0], *value, name);
-    }
-}
-} // namespace
-
 v8::MaybeLocal<v8::Value> ScriptEngine::findAnimation (const std::string& name, std::optional<int> objectId) {
     const auto group = objectId.has_value () ? std::optional ("obj" + std::to_string (*objectId)) : std::nullopt;
     auto* clock = this->m_animations.findByName (name, group);
@@ -1016,56 +977,30 @@ v8::MaybeLocal<v8::Value> ScriptEngine::findAnimation (const std::string& name,
     return this->m_adapters.object->animation (this->m_animations.getId (), clock->getId ());
 }
 
-v8::Local<v8::Value> ScriptEngine::makeThisObject (DynamicValue& value, const std::string& propertyName) {
-    const auto context = this->getContext ();
-    const v8::Local<v8::Object> handle = v8::Object::New (this->m_isolate);
-
-    JS::set (
-	context, handle, "getAnimation",
-	JS::function (
-	    context, this_object_get_animation,
-	    JS::data (
-		this->m_isolate,
-		{ v8::Integer::New (this->m_isolate, this->m_animations.getId ()),
-		  JS::external (this->m_isolate, &value) }
-	    )
-	)
-    );
-
-    if (!propertyName.empty ()) {
-	const auto data = JS::data (
-	    this->m_isolate,
-	    { JS::external (this->m_isolate, &value), v8::Boolean::New (this->m_isolate, propertyName == "angles") }
-	);
-
-	handle->SetAccessorProperty (
-	    JS::name (this->m_isolate, propertyName), JS::function (context, JS::bind<this_object_property, 0>, data),
-	    JS::function (context, JS::bind<this_object_property, 1>, data, 1)
-	);
-    }
-
-    return handle;
-}
-
 void ScriptEngine::bindThisLayer (ScriptableObject& object, LoadedModule* module) {
     const auto context = this->getContext ();
     const auto global = this->getGlobalThis ();
+    const v8::Local<v8::Value> layer = this->m_adapters.object->instantiate (object);
 
-    JS::set (context, global, "thisLayer", this->m_adapters.object->instantiate (object));
+    JS::set (context, global, "thisLayer", layer);
 
-    // thisObject is the property the running script is attached to (what getAnimation() hangs
-    // off), not the layer
-    if (module == nullptr) {
-	JS::set (context, global, "thisObject", this->m_adapters.object->instantiate (object));
+    // thisObject is the module's owner (scenescript64 sub_18164E4D0 pushes the object given when the script was
+    // created, thisLayer the layer of the call): live WE has thisObject === thisLayer for layer properties
+    if (module == nullptr || !module->thisObjectFactory) {
+	JS::set (context, global, "thisObject", layer);
 	return;
     }
 
     if (module->thisObject.IsEmpty ()) {
-	module->thisObject.Reset (
-	    this->m_isolate,
-	    module->thisObjectFactory ? module->thisObjectFactory (*this)
-				      : this->makeThisObject (module->value, module->propertyName)
-	);
+	const auto owner = module->thisObjectFactory (*this);
+
+	// an effect's material only exists once its passes are set up, ask again next time
+	if (owner->IsNullOrUndefined ()) {
+	    JS::set (context, global, "thisObject", owner);
+	    return;
+	}
+
+	module->thisObject.Reset (this->m_isolate, owner);
     }
 
     JS::set (context, global, "thisObject", module->thisObject.Get (this->m_isolate));
@@ -1115,8 +1050,6 @@ void ScriptEngine::dispatchAnimationEvents () {
 }
 
 void ScriptEngine::initializeModule (const std::string& key, LoadedModule& module) {
-    const auto context = this->getContext ();
-
     module.initialized = true;
 
     // init() receives the property's static/base value exactly once, before update() starts being
@@ -1144,13 +1077,7 @@ void ScriptEngine::initializeModule (const std::string& key, LoadedModule& modul
     // changed ones afterward) - scripts like music selectors rely on that first call to start up
     {
 	const v8::TryCatch tryCatch (this->m_isolate);
-	const v8::Local<v8::Object> userProps = v8::Object::New (this->m_isolate);
-
-	for (const auto& [name, property] : this->m_engineObject->getScene ().getUserProperties ()) {
-	    JS::set (context, userProps, name, this->userPropertyToJs (*property));
-	}
-
-	v8::Local<v8::Value> applyArgs[] = { userProps };
+	v8::Local<v8::Value> applyArgs[] = { this->initialUserProperties () };
 
 	if (this->call (module, "applyUserProperties", 1, applyArgs).IsEmpty ()) {
 	    logJSException (this->m_isolate, tryCatch, key.c_str (), module.value.getScriptSource ());
@@ -1160,6 +1087,70 @@ void ScriptEngine::initializeModule (const std::string& key, LoadedModule& modul
     this->notifyMediaUpdate (this->m_mediaSource.getMediaInfo (), &module);
 }
 
+// the project's properties plus WE's own: sub_14010A520 drops the project's alignment/volume/rate/cameraparallax,
+// sub_140104B60 adds its defaults for the scene's flags (0xD0 plus volume/alignment/cameraparallax, sub_14010DF40)
+// and removes the disabled ones, sub_14010C650 a grey schemecolor. Sorted by name like WE's JSON object
+v8::Local<v8::Object> ScriptEngine::initialUserProperties () {
+    auto* isolate = this->m_isolate;
+    const auto context = this->getContext ();
+    const auto& scene = this->m_engineObject->getScene ();
+    const auto& flags = scene.getScene ().engineProperties;
+    const auto number = [isolate] (int value) -> v8::Local<v8::Value> { return v8::Integer::New (isolate, value); };
+    const auto boolean = [isolate] (bool value) -> v8::Local<v8::Value> { return v8::Boolean::New (isolate, value); };
+
+    struct EngineProperty {
+	const char* name;
+	v8::Local<v8::Value> value;
+	bool enabled;
+	// the project's own value doesn't count
+	bool replaces;
+    };
+
+    const EngineProperty engineProperties[] = {
+	{ "volume", number (50), flags.volume, true },
+	{ "rate", number (100), true, true },
+	{ "cameraparallax", boolean (true), flags.cameraParallax, true },
+	{ "alignment", number (0), flags.alignment, true },
+	{ "alignmentposition", number (50), flags.alignment, false },
+	{ "alignmentx", number (50), flags.alignment, false },
+	{ "alignmenty", number (50), flags.alignment, false },
+	{ "alignmentz", number (100), flags.alignment, false },
+	{ "alignmentfliph", boolean (false), true, false },
+	{ "wcc_v", JS::string (isolate, ""), true, false },
+	{ "wcc_amt", number (100), true, false },
+	{ "wec_e", boolean (false), true, false },
+	{ "wec_brs", number (50), true, false },
+	{ "wec_con", number (50), true, false },
+	{ "wec_sa", number (50), true, false },
+	{ "wec_hue", number (50), true, false },
+	{ "schemecolor", this->m_adapters.vec3->create (glm::vec3 (0.5f)), true, false },
+    };
+
+    std::map<std::string, v8::Local<v8::Value>> values;
+
+    for (const auto& [name, property] : scene.getUserProperties ()) {
+	values.emplace (name, this->userPropertyToJs (*property));
+    }
+
+    for (const auto& property : engineProperties) {
+	if (!property.enabled) {
+	    values.erase (property.name);
+	} else if (property.replaces) {
+	    values.insert_or_assign (property.name, property.value);
+	} else {
+	    values.try_emplace (property.name, property.value);
+	}
+    }
+
+    const v8::Local<v8::Object> result = v8::Object::New (isolate);
+
+    for (const auto& [name, value] : values) {
+	JS::set (context, result, name, value);
+    }
+
+    return result;
+}
+
 namespace {
 constexpr const char* CURSOR_HANDLERS[]
     = { "cursorEnter", "cursorLeave", "cursorMove", "cursorDown", "cursorUp", "cursorClick" };
@@ -1271,16 +1262,6 @@ void ScriptEngine::dispatchCursorEvent (
     this->m_runningModule = nullptr;
 }
 
-void ScriptEngine::addVideoEndedCallback (VideoPlayback::MPV::GLPlayer* player, v8::Local<v8::Value> callback) {
-    if (player == nullptr || !callback->IsFunction ()) {
-	return;
-    }
-
-    this->m_videoEndedCallbacks.push_back (
-	{ .player = player, .callback = v8::Global<v8::Function> (this->m_isolate, callback.As<v8::Function> ()) }
-    );
-}
-
 void ScriptEngine::addAnimationLayerEndedCallback (
     const ScriptableObject& owner, size_t serial, v8::Local<v8::Value> callback
 ) {
@@ -1462,27 +1443,16 @@ void ScriptEngine::tick () {
 
     this->m_engineObject->tick ();
 
-    // index based, a callback is free to register more callbacks (and reallocate the vector)
-    for (size_t index = 0; index < this->m_videoEndedCallbacks.size (); index++) {
-	auto& entry = this->m_videoEndedCallbacks[index];
-
-	if (!entry.player->hasEnded ()) {
-	    entry.notified = false;
-	    continue;
-	}
-
-	if (entry.notified) {
-	    continue;
-	}
-
-	entry.notified = true;
-
+    // collected first, a callback is free to register more callbacks or fetch more video textures
+    {
 	const v8::HandleScope handleScope (this->m_isolate);
-	const v8::TryCatch tryCatch (this->m_isolate);
-	const v8::Local<v8::Function> callback = entry.callback.Get (this->m_isolate);
 
-	if (callback->Call (context, v8::Undefined (this->m_isolate), 0, nullptr).IsEmpty ()) {
-	    logJSException (this->m_isolate, tryCatch, "video ended callback");
+	for (const auto& callback : this->m_adapters.object->takeDueVideoEndedCallbacks ()) {
+	    const v8::TryCatch tryCatch (this->m_isolate);
+
+	    if (callback->Call (context, v8::Undefined (this->m_isolate), 0, nullptr).IsEmpty ()) {
+		logJSException (this->m_isolate, tryCatch, "video ended callback");
+	    }
 	}
     }
 

+ 5 - 15
src/WallpaperEngine/Scripting/ScriptEngine.h

@@ -80,9 +80,10 @@ public:
 	// init()/applyUserProperties() wait for the first tick() so every layer of the scene already
 	// exists when a script looks its siblings up with thisScene.getLayer()
 	bool initialized = false;
-	// cached `thisObject` handle, see makeThisObject()
+	// cached `thisObject` handle built by thisObjectFactory
 	v8::Global<v8::Value> thisObject;
-	// builds thisObject instead of makeThisObject() (animation layer scripts get the IAnimationLayer)
+	// owners that aren't the layer: the pass's IMaterial for effect constants, the IAnimationLayer for animation
+	// layer properties. Without one thisObject is the layer, like thisLayer
 	std::function<v8::Local<v8::Value> (ScriptEngine&)> thisObjectFactory;
 	// name of the property the script is attached to ("origin", an effect constant, ...)
 	std::string propertyName;
@@ -229,16 +230,13 @@ public:
 	const std::optional<std::string>& hitBox
     );
 
-    /** Calls callback (once per playthrough) when player reaches the end of a non-looping video, for
-     * IVideoTexture.addEndedCallback() */
-    void addVideoEndedCallback (VideoPlayback::MPV::GLPlayer* player, v8::Local<v8::Value> callback);
     /** Calls callback every time the puppet animation layer reaches its end, for IAnimationLayer.addEndedCallback() */
     void addAnimationLayerEndedCallback (const ScriptableObject& owner, size_t serial, v8::Local<v8::Value> callback);
     /** Runs the ended callbacks of that animation layer, from the puppet update like WE (sub_1401FDF90) */
     void dispatchAnimationLayerEnded (const ScriptableObject& owner, size_t serial);
     /** Puppet clip event -> animationEvent (sub_140177AD0) with the payload JSON parsed, null if invalid */
     void dispatchClipEvent (const ScriptableObject& owner, const std::string& payload);
-    /** The script queued under key gets thisObject from factory instead of the property handle */
+    /** The script queued under key gets thisObject from factory instead of the layer */
     void setThisObjectFactory (const std::string& key, std::function<v8::Local<v8::Value> (ScriptEngine&)> factory);
 
     AnimationSystem& getAnimations () { return m_animations; }
@@ -282,7 +280,7 @@ private:
     void notifyMediaUpdate (const Media::MediaSource::MediaInfo& media, LoadedModule* only = nullptr);
     void initializeModule (const std::string& key, LoadedModule& module);
     void bindThisLayer (ScriptableObject& object, LoadedModule* module = nullptr);
-    v8::Local<v8::Value> makeThisObject (DynamicValue& value, const std::string& propertyName);
+    v8::Local<v8::Object> initialUserProperties ();
 
 public:
     /** IAnimation of the animation getAnimation (name) finds on objectId's layer, or any layer without one; empty
@@ -318,14 +316,6 @@ private:
     bool m_evaluatingModuleBody = false;
     bool m_runningUpdate = false;
 
-    struct VideoEndedCallback {
-	VideoPlayback::MPV::GLPlayer* player;
-	v8::Global<v8::Function> callback;
-	// set once the callback ran for the current end, cleared when the video is seeked back
-	bool notified = false;
-    };
-    std::vector<VideoEndedCallback> m_videoEndedCallbacks = {};
-
     struct AnimationLayerEndedCallback {
 	const ScriptableObject* owner;
 	size_t serial;

+ 7 - 0
src/WallpaperEngine/Scripting/ScriptableObject.cpp

@@ -72,6 +72,13 @@ void ScriptableObject::registerEffectConstants (const std::vector<ImageEffectUni
 		this->registerProperty (
 		    prefix + constant, *setting->value, "obj" + std::to_string (this->getId ()) + "/" + prefix, constant
 		);
+		// live WE: an effect constant's script gets the pass's IMaterial as thisObject
+		this->getScene ().getScriptEngine ().setThisObjectFactory (
+		    this->m_properties.at (prefix + constant).key,
+		    [&effect = *effects[effectIndex], passIndex] (ScriptEngine& engine) {
+			return engine.getAdapters ().object->material (effect, passIndex);
+		    }
+		);
 	    }
 	}
     }

+ 133 - 0
src/WallpaperEngine/Testing/Cases/HyprlandIPC.cpp

@@ -0,0 +1,133 @@
+#include <catch2/catch_test_macros.hpp>
+
+#include <cstring>
+#include <filesystem>
+#include <fstream>
+#include <sys/socket.h>
+#include <sys/un.h>
+#include <thread>
+#include <unistd.h>
+
+#include "WallpaperEngine/Desktop/HyprlandIPC.h"
+
+using WallpaperEngine::Desktop::findHyprlandSocket;
+using WallpaperEngine::Desktop::hyprlandRequest;
+
+namespace {
+struct RuntimeDir {
+    std::filesystem::path path
+	= std::filesystem::temp_directory_path () / ("lwe-hypr-test-" + std::to_string (getpid ()));
+    std::vector<int> listeners;
+
+    RuntimeDir () { std::filesystem::create_directories (path / "hypr"); }
+
+    ~RuntimeDir () {
+	for (const int fd : listeners) {
+	    close (fd);
+	}
+	std::filesystem::remove_all (path);
+    }
+
+    /** a Hyprland instance folder like 0.4x+ writes it; a dead one leaves its socket file behind */
+    std::string instance (const std::string& signature, const std::string& display, bool live) {
+	const auto dir = path / "hypr" / signature;
+	std::filesystem::create_directories (dir);
+	std::ofstream (dir / "hyprland.lock") << "1234\n" << display << "\n";
+
+	const auto socketPath = (dir / ".socket.sock").string ();
+	const int fd = socket (AF_UNIX, SOCK_STREAM, 0);
+	sockaddr_un addr {};
+	addr.sun_family = AF_UNIX;
+	std::strncpy (addr.sun_path, socketPath.c_str (), sizeof (addr.sun_path) - 1);
+	REQUIRE (bind (fd, reinterpret_cast<sockaddr*> (&addr), sizeof (addr)) == 0);
+	REQUIRE (listen (fd, 4) == 0);
+
+	if (live) {
+	    listeners.push_back (fd);
+	} else {
+	    close (fd);
+	}
+
+	return socketPath;
+    }
+};
+} // namespace
+
+TEST_CASE ("Hyprland socket from the instance signature") {
+    RuntimeDir runtime;
+    const auto first = runtime.instance ("first", "wayland-1", true);
+    const auto second = runtime.instance ("second", "wayland-2", true);
+
+    CHECK (findHyprlandSocket (runtime.path.string (), "second", "wayland-1", "Hyprland") == second);
+    CHECK (findHyprlandSocket (runtime.path.string (), "first", nullptr, "Hyprland") == first);
+}
+
+TEST_CASE ("Hyprland socket without the signature, as in a Flatpak") {
+    RuntimeDir runtime;
+
+    SECTION ("no instance folder") {
+	CHECK (findHyprlandSocket (runtime.path.string (), nullptr, "wayland-1", "Hyprland").empty ());
+	CHECK (findHyprlandSocket ("", nullptr, "wayland-1", "Hyprland").empty ());
+	CHECK (findHyprlandSocket ((runtime.path / "missing").string (), nullptr, nullptr, "Hyprland").empty ());
+    }
+
+    SECTION ("the only live instance") {
+	runtime.instance ("crashed", "wayland-1", false);
+	const auto live = runtime.instance ("live", "wayland-2", true);
+	CHECK (findHyprlandSocket (runtime.path.string (), nullptr, "wayland-1", "Hyprland") == live);
+	CHECK (findHyprlandSocket (runtime.path.string (), nullptr, nullptr, "Hyprland") == live);
+    }
+
+    SECTION ("the instance whose lock names our display, also given as a path") {
+	runtime.instance ("a", "wayland-1", true);
+	const auto ours = runtime.instance ("b", "wayland-2", true);
+	runtime.instance ("c", "wayland-3", true);
+	CHECK (findHyprlandSocket (runtime.path.string (), nullptr, "wayland-2", "Hyprland") == ours);
+	CHECK (findHyprlandSocket (runtime.path.string (), nullptr, "/run/user/1000/wayland-2", "Hyprland") == ours);
+	CHECK (findHyprlandSocket (runtime.path.string (), "", "wayland-2", "Hyprland") == ours);
+    }
+
+    SECTION ("a signature of a gone instance") {
+	const auto live = runtime.instance ("live", "wayland-1", true);
+	CHECK (findHyprlandSocket (runtime.path.string (), "gone", "wayland-1", "Hyprland") == live);
+    }
+
+    SECTION ("another session's instance when we don't run on Hyprland") {
+	runtime.instance ("nested", "wayland-1", true);
+	CHECK (findHyprlandSocket (runtime.path.string (), nullptr, "wayland-0", "sway").empty ());
+	CHECK (findHyprlandSocket (runtime.path.string (), nullptr, "wayland-0", nullptr).empty ());
+	CHECK (findHyprlandSocket (runtime.path.string (), nullptr, "wayland-0", "KDE:Hyprland") != "");
+    }
+
+    SECTION ("only dead sockets") {
+	runtime.instance ("crashed", "wayland-1", false);
+	CHECK (findHyprlandSocket (runtime.path.string (), nullptr, "wayland-1", "Hyprland").empty ());
+    }
+}
+
+TEST_CASE ("Hyprland request and reply") {
+    RuntimeDir runtime;
+    const auto socketPath = runtime.instance ("sig", "wayland-1", true);
+    const int listener = runtime.listeners.back ();
+
+    std::string received;
+    std::thread server ([listener, &received] () {
+	const int client = accept (listener, nullptr, nullptr);
+	char buffer[64];
+	ssize_t length = 0;
+	while ((length = read (client, buffer, sizeof (buffer))) > 0) {
+	    received.append (buffer, static_cast<std::size_t> (length));
+	}
+	const std::string reply = R"({"x": 1520, "y": -12.5})";
+	write (client, reply.data (), reply.size ());
+	close (client);
+    });
+
+    const auto reply = hyprlandRequest (socketPath, "j/cursorpos");
+    server.join ();
+
+    CHECK (received == "j/cursorpos");
+    REQUIRE (reply.has_value ());
+    CHECK (*reply == R"({"x": 1520, "y": -12.5})");
+    CHECK_FALSE (hyprlandRequest ((runtime.path / "nothing.sock").string (), "j/cursorpos").has_value ());
+}

+ 69 - 0
src/WallpaperEngine/Testing/Cases/WebHostFiles.cpp

@@ -0,0 +1,69 @@
+#include <catch2/catch_test_macros.hpp>
+
+#include <chrono>
+#include <fcntl.h>
+#include <filesystem>
+#include <fstream>
+#include <sys/file.h>
+#include <sys/mman.h>
+#include <unistd.h>
+
+#include "WallpaperEngine/Desktop/SessionBus.h"
+#include "WallpaperEngine/WebBrowser/IPC/WebHostSharedMemory.h"
+
+using namespace WallpaperEngine::WebBrowser::IPC;
+
+namespace {
+std::filesystem::path profile (const std::string& name) {
+    return std::filesystem::temp_directory_path () / ("lwe-cef-test" + std::to_string (getpid ()) + "-" + name);
+}
+} // namespace
+
+TEST_CASE ("Process tag outside a Flatpak is the pid") {
+    if (access ("/.flatpak-info", F_OK) == 0) {
+	SKIP ("running inside a Flatpak");
+    }
+
+    CHECK (WallpaperEngine::Desktop::processTag () == std::to_string (getpid ()));
+}
+
+TEST_CASE ("Stale web host files are told apart by their locks, not by pids") {
+    std::string held;
+    auto* memory = createSharedMemory (held, 16, 16);
+    REQUIRE (memory != nullptr);
+
+    // what a killed engine of another pid namespace leaves: a name whose pid means nothing here, no lock
+    const std::string orphan = "/lwe-web-" + std::to_string (getpid ()) + "_1-0";
+    const int orphanFd = shm_open (orphan.c_str (), O_CREAT | O_EXCL | O_RDWR, 0600);
+    REQUIRE (orphanFd >= 0);
+    close (orphanFd);
+
+    const auto dead = profile ("dead");
+    const auto live = profile ("live");
+    const auto fresh = profile ("fresh");
+    for (const auto& dir : { dead, live, fresh }) {
+	std::filesystem::create_directories (dir);
+    }
+    std::ofstream (dead / CEF_PROFILE_LOCK).close ();
+    std::filesystem::last_write_time (dead, std::filesystem::file_time_type::clock::now () - std::chrono::hours (1));
+    const int liveLock = open ((live / CEF_PROFILE_LOCK).c_str (), O_CREAT | O_RDWR, 0600);
+    REQUIRE (flock (liveLock, LOCK_SH) == 0);
+
+    CHECK (isLockedByAnyone ("/dev/shm" + held));
+    CHECK_FALSE (isLockedByAnyone ("/dev/shm" + orphan));
+
+    removeStaleWebHostFiles ();
+
+    CHECK (std::filesystem::exists ("/dev/shm" + held));
+    CHECK_FALSE (std::filesystem::exists ("/dev/shm" + orphan));
+    CHECK_FALSE (std::filesystem::exists (dead));
+    CHECK (std::filesystem::exists (live));
+    // no lock file yet: the host is still setting it up
+    CHECK (std::filesystem::exists (fresh));
+
+    closeSharedMemory (memory, held, 16, 16, true);
+    close (liveLock);
+    CHECK_FALSE (std::filesystem::exists ("/dev/shm" + held));
+    std::filesystem::remove_all (live);
+    std::filesystem::remove_all (fresh);
+}

+ 97 - 18
src/WallpaperEngine/VideoPlayback/MPV/GLPlayer.cpp

@@ -18,6 +18,11 @@ using namespace WallpaperEngine::VideoPlayback::MPV;
 std::unordered_map<std::filesystem::path, GLPlayer*> GLPlayer::s_activePlayers;
 std::unordered_set<GLPlayer*> GLPlayer::s_players;
 double GLPlayer::s_statsMillis = 0.0;
+uint64_t GLPlayer::s_frame = 0;
+
+// wallpaper64.exe 2.8.42 sub_1400F3930: the media engine plays while (+96 + 30) >= frame counter, +96 being the
+// counter at the last transfer
+static constexpr uint64_t UNUSED_FRAMES_BEFORE_PAUSE = 30;
 
 // the synchronous mpv_set_property/mpv_command wait for mpv's core thread, which can take a few hundred ms
 // while it's busy, and these are called from the render thread (scripts pausing/seeking videos on click)
@@ -160,17 +165,39 @@ void GLPlayer::setHwdecForAll (const std::string& value) {
 
 void GLPlayer::setPaused () {
     this->m_paused = true;
-
-    if (this->m_handle) {
-	setPropertyAsync (this->m_handle, "pause", "yes");
-    }
+    this->applyPause ();
 }
 
 void GLPlayer::clearPaused () {
     this->m_paused = false;
+    this->applyPause ();
+}
 
-    if (this->m_handle) {
-	setPropertyAsync (this->m_handle, "pause", "no");
+void GLPlayer::markUsed () const {
+    this->m_lastUsedFrame = s_frame;
+
+    // the frame counter only moves while a scene renders, a player paused for going unused can't wait for that
+    if (this->m_enginePaused && !this->m_paused) {
+	this->applyPause ();
+    }
+}
+
+void GLPlayer::applyPause () const {
+    const bool paused = this->m_paused || this->m_lastUsedFrame + UNUSED_FRAMES_BEFORE_PAUSE < s_frame;
+
+    if (this->m_handle == nullptr || paused == this->m_enginePaused) {
+	return;
+    }
+
+    this->m_enginePaused = paused;
+    setPropertyAsync (this->m_handle, "pause", paused ? "yes" : "no");
+}
+
+void GLPlayer::advanceFrame () {
+    s_frame++;
+
+    for (GLPlayer* player : s_players) {
+	player->applyPause ();
     }
 }
 
@@ -185,6 +212,7 @@ void GLPlayer::setLoop (bool loop) {
 // eof-reached uses 0
 static constexpr uint64_t TIME_POS_OBSERVER = 1;
 static constexpr uint64_t FPS_OBSERVER = 2;
+static constexpr uint64_t POSITION_OBSERVER = 3;
 
 // with ab-loop-b unset mpv's own loop restarts the file from 0 instead of going back to A, so an open end is a B
 // past the end of any video
@@ -278,6 +306,7 @@ std::optional<double> GLPlayer::skipTarget (const double position) const {
 
 void GLPlayer::seek (const double seconds) {
     this->m_ended = false;
+    this->m_position = seconds;
 
     if (this->m_handle == nullptr || !this->m_fileLoaded) {
 	this->m_pendingSeek = seconds;
@@ -321,6 +350,14 @@ void GLPlayer::render () const {
 	if (event->event_id == MPV_EVENT_PROPERTY_CHANGE) {
 	    const auto* property = static_cast<const mpv_event_property*> (event->data);
 
+	    if (event->reply_userdata == POSITION_OBSERVER) {
+		if (property->format == MPV_FORMAT_DOUBLE) {
+		    this->m_position = *static_cast<const double*> (property->data);
+		}
+
+		continue;
+	    }
+
 	    if (event->reply_userdata == FPS_OBSERVER) {
 		const double fps
 		    = property->format == MPV_FORMAT_DOUBLE ? *static_cast<const double*> (property->data) : 0.0;
@@ -402,16 +439,50 @@ void GLPlayer::render () const {
 	    GL_TEXTURE_2D, 0, this->m_linearOutput ? GL_RGBA16F : GL_RGBA8, this->m_width, this->m_height, 0, GL_RGBA,
 	    this->m_linearOutput ? GL_HALF_FLOAT : GL_UNSIGNED_BYTE, nullptr
 	);
+
+	// stays empty like WE's zero filled one (sub_1400EB570) until a frame is drawn below, a paused texture gets
+	// none
+	if (this->m_doWeOwnFramebuffer) {
+	    this->clearTexture ();
+	}
     }
 
     // mpv only hands out its next frame once the update flags were collected, without this playback stalls
     const uint64_t updateFlags = mpv_render_context_update (this->m_renderContext);
 
     if (this->m_doWeOwnFramebuffer) {
+	// WE's pause stops the thread that copies frames into the texture (sub_1400F3030), so a seek or stop while
+	// paused keeps showing the last frame until play
+	if (this->m_paused) {
+	    return;
+	}
+
 	if (!(updateFlags & MPV_RENDER_UPDATE_FRAME) && !this->m_needsRedraw) {
 	    return;
 	}
 
+	// before the first decoded frame mpv only queues redraws of nothing, which it draws black. WE's texture
+	// keeps its zeros until the first TransferVideoFrame (sub_1400F3480). They still have to be consumed, or
+	// mpv's VO waits 200 ms for each one
+	if (!this->m_hasFrame) {
+	    mpv_render_frame_info info {};
+	    mpv_render_context_get_info (this->m_renderContext, { MPV_RENDER_PARAM_NEXT_FRAME_INFO, &info });
+
+	    if ((info.flags & MPV_RENDER_FRAME_INFO_PRESENT) && !(info.flags & MPV_RENDER_FRAME_INFO_REDRAW)) {
+		this->m_hasFrame = true;
+	    } else {
+		int skip = 1;
+		mpv_render_param params[]
+		    = { { MPV_RENDER_PARAM_SKIP_RENDERING, &skip }, { MPV_RENDER_PARAM_INVALID, nullptr } };
+
+		if (info.flags & MPV_RENDER_FRAME_INFO_PRESENT) {
+		    mpv_render_context_render (this->m_renderContext, params);
+		}
+
+		return;
+	    }
+	}
+
 	this->m_needsRedraw = false;
     }
 
@@ -448,16 +519,6 @@ void GLPlayer::render () const {
 int GLPlayer::getWidth () const { return this->m_width; }
 int GLPlayer::getHeight () const { return this->m_height; }
 
-double GLPlayer::getPlaybackPosition () const {
-    double position = 0.0;
-
-    if (this->m_handle != nullptr) {
-	mpv_get_property (this->m_handle, "time-pos", MPV_FORMAT_DOUBLE, &position);
-    }
-
-    return position;
-}
-
 void GLPlayer::prepareGL () {
     if (!this->m_doWeOwnFramebuffer || this->m_fbo != GL_NONE) {
 	return;
@@ -478,13 +539,22 @@ void GLPlayer::prepareGL () {
 	sLog.exception ("Framebuffers are not properly set");
     }
 
-    glClear (GL_COLOR_BUFFER_BIT);
+    this->clearTexture ();
+}
+
+void GLPlayer::clearTexture () const {
+    constexpr GLfloat transparent[4] = { 0.0f, 0.0f, 0.0f, 0.0f };
+
+    glBindFramebuffer (GL_FRAMEBUFFER, this->m_fbo);
+    glClearBufferfv (GL_COLOR, 0, transparent);
 }
 
 void GLPlayer::init () {
     this->m_fileLoaded = false;
+    this->m_hasFrame = false;
     this->m_ended = false;
     this->m_skipping = false;
+    this->m_position = 0.0;
     this->m_handle = mpv_create ();
 
     if (this->m_handle == nullptr) {
@@ -518,6 +588,9 @@ void GLPlayer::init () {
     if (this->m_doWeOwnFramebuffer) {
 	// without the blocking wait in render() a frame would otherwise show up to 50ms early
 	mpv_set_option_string (this->m_handle, "video-timing-offset", "0");
+	// after every seek, the loop's included, mpv holds its clock until the scene has drawn the first new frame,
+	// which lost 1-3 frames per loop at 15 fps. Media Foundation's loop in live WE on Windows loses ~0.3
+	mpv_set_option_string (this->m_handle, "video-latency-hacks", "yes");
     }
 
     if (mpv_initialize (this->m_handle) < 0) {
@@ -528,6 +601,8 @@ void GLPlayer::init () {
     // back to the start. Observed rather than polled: mpv_get_property waits for mpv's core thread, and polling
     // it every frame stalled the render thread ~160-200ms every few seconds on a paused video
     mpv_observe_property (this->m_handle, 0, "eof-reached", MPV_FORMAT_FLAG);
+    // scripts read the position every frame (IVideoTexture ended callbacks), a synchronous get would stall the same way
+    mpv_observe_property (this->m_handle, POSITION_OBSERVER, "time-pos", MPV_FORMAT_DOUBLE);
 
     const auto& hwdec = this->getContext ().getApp ().getContext ().settings.render.hwdec;
 
@@ -565,7 +640,8 @@ void GLPlayer::init () {
     }
 
     mpv_set_property_string (this->m_handle, "mute", this->m_muted ? "yes" : "no");
-    mpv_set_property_string (this->m_handle, "pause", this->m_paused ? "yes" : "no");
+    this->m_enginePaused = this->m_paused;
+    mpv_set_property_string (this->m_handle, "pause", this->m_enginePaused ? "yes" : "no");
 }
 
 void GLPlayer::setSource (const std::filesystem::path& file) { this->m_file = file; }
@@ -581,6 +657,8 @@ void GLPlayer::play () {
 	sLog.exception ("Cannot play a GLPlayer without a source");
     }
 
+    // sub_1400F2510 counts the texture as used when it's handed to the player
+    this->m_lastUsedFrame = s_frame;
     this->init ();
 
     if (this->m_file.has_value ()) {
@@ -608,6 +686,7 @@ void GLPlayer::play () {
 	// start at the first part. An option, not a loadfile argument: mpv 0.38 changed that form
 	if (start.has_value ()) {
 	    mpv_set_property_string (this->m_handle, "start", std::to_string (*start).c_str ());
+	    this->m_position = *start;
 	}
 
 	const char* command[] = { "loadfile", path.c_str (), "replace", nullptr };

+ 20 - 2
src/WallpaperEngine/VideoPlayback/MPV/GLPlayer.h

@@ -65,12 +65,19 @@ public:
 
     void render () const;
     void requestRedraw () const { this->m_needsRedraw = true; }
+    /** The texture was bound for a draw this frame, keeps playback running (WE's transfer on bind, sub_14015F0D0) */
+    void markUsed () const;
+    /**
+     * Once per scene frame, like the counter wallpaper64.exe 2.8.42 sub_14017FA70 bumps. A video whose texture went
+     * unused for 30 of them is paused until it's drawn again (sub_1400F3930)
+     */
+    static void advanceFrame ();
 
     int getWidth () const;
     int getHeight () const;
 
-    /** Current playback position in seconds, or 0 if playback hasn't started yet */
-    double getPlaybackPosition () const;
+    /** Current playback position in seconds as mpv last reported it, or 0 if playback hasn't started yet */
+    double getPlaybackPosition () const { return this->m_position; }
 
     /** Comma separated backend names only, so no other mpv option gets injected */
     static bool isValidHwdec (const std::string& value);
@@ -81,6 +88,8 @@ public:
 
 private:
     void prepareGL ();
+    /** to transparent black, the texture must be one we own */
+    void clearTexture () const;
     /** mpv keeps seeking back to an A past the end, so those parts are dropped once the length is known */
     bool dropSegmentsPastEnd () const;
     /** only while there are gaps */
@@ -88,6 +97,8 @@ private:
     /** nullopt inside a part or past the last */
     std::optional<double> skipTarget (double position) const;
     void init ();
+    /** mpv runs while not paused and the texture was used lately */
+    void applyPause () const;
     void play ();
     void setSource (MemoryStreamProtocolUniquePtr source);
     void setSource (const std::filesystem::path& file);
@@ -106,12 +117,18 @@ protected:
     bool m_muted = false;
     bool m_untimed = false;
     bool m_paused = false;
+    /** what mpv was last told, m_paused or unused */
+    mutable bool m_enginePaused = false;
+    mutable uint64_t m_lastUsedFrame = 0;
+    mutable double m_position = 0.0;
     bool m_loop = true;
     bool m_audio = true;
     bool m_linearOutput = false;
     // a texture we own only needs redrawing when mpv has a new frame, or after its size changed
     mutable bool m_needsRedraw = true;
     mutable bool m_fileLoaded = false;
+    /** mpv drew a decoded frame since init, before that its redraws are an empty black picture */
+    mutable bool m_hasFrame = false;
     mutable bool m_ended = false;
     mutable std::optional<double> m_pendingSeek;
     mutable VideoSegments m_segments;
@@ -128,6 +145,7 @@ protected:
     // instead of always restarting from zero
     static std::unordered_map<std::filesystem::path, GLPlayer*> s_activePlayers;
     static std::unordered_set<GLPlayer*> s_players;
+    static uint64_t s_frame;
 };
 
 using GLPlayerUniquePtr = std::unique_ptr<GLPlayer>;

+ 15 - 1
src/WallpaperEngine/WebBrowser/CEF/BrowserApp.cpp

@@ -7,6 +7,7 @@
 #include <cstdlib>
 #include <sstream>
 #include <string>
+#include <string_view>
 
 using namespace WallpaperEngine::WebBrowser::CEF;
 
@@ -45,8 +46,21 @@ void BrowserApp::OnBeforeCommandLineProcessing (const CefString& process_type, C
     command_line->AppendSwitch ("--disable-field-trial-config");
     command_line->AppendSwitch ("--no-experiments");
 
+    const char* extra = std::getenv ("LWE_CEF_SWITCHES");
+
+    // Chromium starts its X11 platform even for windowless browsers and exits without an X server: a Flatpak on
+    // Wayland (fallback-x11 hides X when Wayland is there) or a session without Xwayland. The headless platform with
+    // ANGLE on EGL renders the same, WebGL on the GPU included
+    const char* display = std::getenv ("DISPLAY");
+    if ((display == nullptr || *display == '\0')
+	&& (extra == nullptr || std::string_view (extra).find ("--ozone-platform") == std::string_view::npos)) {
+	command_line->AppendSwitchWithValue ("--ozone-platform", "headless");
+	command_line->AppendSwitchWithValue ("--use-gl", "angle");
+	command_line->AppendSwitchWithValue ("--use-angle", "gl-egl");
+    }
+
     // debugging: extra Chromium switches, e.g. swiftshader where the GPU process can't start
-    if (const char* extra = std::getenv ("LWE_CEF_SWITCHES"); extra != nullptr) {
+    if (extra != nullptr) {
 	std::istringstream stream (extra);
 	std::string word;
 

+ 83 - 21
src/WallpaperEngine/WebBrowser/IPC/WebHostSharedMemory.cpp

@@ -1,7 +1,10 @@
 #include "WebHostSharedMemory.h"
 
+#include <algorithm>
 #include <atomic>
+#include <cctype>
 #include <cerrno>
+#include <chrono>
 #include <climits>
 #include <csignal>
 #include <cstring>
@@ -9,11 +12,15 @@
 #include <fcntl.h>
 #include <filesystem>
 #include <linux/futex.h>
+#include <map>
+#include <mutex>
 #include <new>
+#include <sys/file.h>
 #include <sys/mman.h>
 #include <sys/syscall.h>
 #include <unistd.h>
 
+#include "WallpaperEngine/Desktop/SessionBus.h"
 #include "WallpaperEngine/Logging/Log.h"
 
 using namespace WallpaperEngine::WebBrowser::IPC;
@@ -22,7 +29,31 @@ namespace {
 std::atomic<uint32_t> g_nameCounter { 0 };
 
 std::string generateName () {
-    return "/lwe-web-" + std::to_string (getpid ()) + "-" + std::to_string (g_nameCounter.fetch_add (1));
+    return "/lwe-web-" + WallpaperEngine::Desktop::processTag () + "-" + std::to_string (g_nameCounter.fetch_add (1));
+}
+
+// a shared flock on an open descriptor marks a segment in use for as long as the descriptor stays open: unlike a pid
+// in its name this works across pid namespaces (every Flatpak run has its own, /dev/shm is the host's)
+std::mutex g_heldMutex;
+std::map<std::string, int> g_held;
+
+void hold (const std::string& name, int fd) {
+    if (flock (fd, LOCK_SH) != 0) {
+	close (fd);
+	return;
+    }
+
+    const std::scoped_lock lock (g_heldMutex);
+    g_held[name] = fd;
+}
+
+void release (const std::string& name) {
+    const std::scoped_lock lock (g_heldMutex);
+
+    if (const auto it = g_held.find (name); it != g_held.end ()) {
+	close (it->second);
+	g_held.erase (it);
+    }
 }
 } // namespace
 
@@ -46,36 +77,48 @@ uint32_t WebHostSharedMemory::waitForFrameRequest (const uint32_t lastSeen, cons
 }
 
 namespace {
-// "<prefix><pid>-<rest>" -> pid, or 0 if the name isn't ours
-pid_t pidFromName (const std::string& name, const std::string& prefix) {
+/**
+ * Engines from before the locks never take one, so an unlocked name tagged with a plain pid (no Flatpak instance) of a
+ * process that still runs is left alone
+ */
+bool pidOwnerAlive (const std::string& name, const std::string& prefix) {
     if (!name.starts_with (prefix)) {
-	return 0;
+	return false;
     }
 
     const std::size_t end = name.find ('-', prefix.size ());
+    const std::string tag = name.substr (prefix.size (), end == std::string::npos ? 0 : end - prefix.size ());
 
-    if (end == std::string::npos || end == prefix.size ()) {
-	return 0;
+    if (tag.empty () || tag.size () > 9
+	|| !std::ranges::all_of (tag, [] (unsigned char c) { return std::isdigit (c); })) {
+	return false;
     }
 
-    try {
-	return static_cast<pid_t> (std::stol (name.substr (prefix.size (), end - prefix.size ())));
-    } catch (...) {
-	return 0;
-    }
+    const auto pid = static_cast<pid_t> (std::stol (tag));
+    return pid > 0 && (kill (pid, 0) == 0 || errno == EPERM);
 }
-
-bool processExists (pid_t pid) { return kill (pid, 0) == 0 || errno == EPERM; }
 } // namespace
 
+bool WallpaperEngine::WebBrowser::IPC::isLockedByAnyone (const std::string& path) {
+    const int fd = open (path.c_str (), O_RDONLY | O_CLOEXEC);
+
+    if (fd < 0) {
+	return false;
+    }
+
+    const bool locked = flock (fd, LOCK_EX | LOCK_NB) != 0 && errno == EWOULDBLOCK;
+    close (fd);
+    return locked;
+}
+
 void WallpaperEngine::WebBrowser::IPC::removeStaleWebHostFiles () {
     std::error_code error;
 
     for (const auto& entry : std::filesystem::directory_iterator ("/dev/shm", error)) {
 	const std::string name = entry.path ().filename ().string ();
-	const pid_t pid = pidFromName (name, "lwe-web-");
 
-	if (pid > 0 && !processExists (pid)) {
+	if (name.starts_with ("lwe-web-") && !isLockedByAnyone (entry.path ().string ())
+	    && !pidOwnerAlive (name, "lwe-web-")) {
 	    shm_unlink (("/" + name).c_str ());
 	}
     }
@@ -83,12 +126,25 @@ void WallpaperEngine::WebBrowser::IPC::removeStaleWebHostFiles () {
     error.clear ();
 
     for (const auto& entry : std::filesystem::directory_iterator (std::filesystem::temp_directory_path (), error)) {
-	const pid_t pid = pidFromName (entry.path ().filename ().string (), "lwe-cef-");
+	const std::string name = entry.path ().filename ().string ();
 
-	if (pid > 0 && !processExists (pid)) {
-	    std::error_code removeError;
-	    std::filesystem::remove_all (entry.path (), removeError);
+	if (!name.starts_with ("lwe-cef-") || pidOwnerAlive (name, "lwe-cef-")) {
+	    continue;
 	}
+
+	// the host locks it right after creating the folder, give one that has no lock file yet a minute
+	const auto lockFile = entry.path () / CEF_PROFILE_LOCK;
+	std::error_code timeError;
+	const auto age = std::filesystem::file_time_type::clock::now ()
+	    - std::filesystem::last_write_time (entry.path (), timeError);
+
+	if (isLockedByAnyone (lockFile.string ())
+	    || (!std::filesystem::exists (lockFile, timeError) && age < std::chrono::minutes (1))) {
+	    continue;
+	}
+
+	std::error_code removeError;
+	std::filesystem::remove_all (entry.path (), removeError);
     }
 }
 
@@ -115,14 +171,16 @@ WallpaperEngine::WebBrowser::IPC::createSharedMemory (std::string& outName, uint
     }
 
     void* mapping = mmap (nullptr, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
-    close (fd);
 
     if (mapping == MAP_FAILED) {
 	sLog.error ("Failed to map shared memory segment ", outName);
+	close (fd);
 	shm_unlink (outName.c_str ());
 	return nullptr;
     }
 
+    hold (outName, fd);
+
     auto* mem = new (mapping) WebHostSharedMemory ();
     mem->maxWidth = width;
     mem->maxHeight = height;
@@ -141,13 +199,15 @@ WallpaperEngine::WebBrowser::IPC::attachSharedMemory (const std::string& name, u
     }
 
     void* mapping = mmap (nullptr, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
-    close (fd);
 
     if (mapping == MAP_FAILED) {
 	sLog.error ("Failed to map shared memory segment ", name);
+	close (fd);
 	return nullptr;
     }
 
+    hold (name, fd);
+
     return static_cast<WebHostSharedMemory*> (mapping);
 }
 
@@ -158,6 +218,8 @@ void WallpaperEngine::WebBrowser::IPC::closeSharedMemory (
 	munmap (mem, WebHostSharedMemory::totalSize (width, height));
     }
 
+    release (name);
+
     if (unlinkSegment) {
 	shm_unlink (name.c_str ());
     }

+ 11 - 2
src/WallpaperEngine/WebBrowser/IPC/WebHostSharedMemory.h

@@ -112,10 +112,19 @@ struct WebHostSharedMemory {
 WebHostSharedMemory* createSharedMemory (std::string& outName, uint32_t maxWidth, uint32_t maxHeight);
 
 // Removes what web host processes of engine processes that no longer exist left behind: shm segments named
-// "lwe-web-<pid>-<n>" and CEF profile directories named "lwe-cef-<pid>-<uuid>" in the temp directory (the pid is
-// the one that created it). Segments are 3 frames each, so a few killed engines add up to hundreds of MB of RAM.
+// "lwe-web-<tag>-<n>" and CEF profile directories named "lwe-cef-<tag>-<uuid>" in the temp directory
+// (Desktop::processTag of the creator). Both sides of a segment and the host of a profile keep a shared flock on it
+// (CEF_PROFILE_LOCK in a profile), what nobody locks is stale, unless its tag is the pid of a running process (engines
+// from before the locks never take one). Segments are 3 frames each, so a few killed engines
+// add up to hundreds of MB of RAM.
 void removeStaleWebHostFiles ();
 
+// The file in a CEF profile directory its host process keeps locked
+inline constexpr const char* CEF_PROFILE_LOCK = "lwe-host.lock";
+
+// Whether some process holds a flock on the file
+bool isLockedByAnyone (const std::string& path);
+
 // Attaches to a segment created by createSharedMemory() elsewhere (a different process). maxWidth
 // and maxHeight must match what the creator used. Returns nullptr on failure.
 WebHostSharedMemory* attachSharedMemory (const std::string& name, uint32_t maxWidth, uint32_t maxHeight);

+ 23 - 2
src/WallpaperEngine/WebBrowser/WebBrowserContext.cpp

@@ -1,8 +1,10 @@
 #include "WebBrowserContext.h"
 #include "CEF/BrowserApp.h"
 #include "WallpaperEngine/Application/WallpaperApplication.h"
+#include "WallpaperEngine/Desktop/SessionBus.h"
 #include "WallpaperEngine/Logging/Log.h"
 #include "WallpaperEngine/WebBrowser/CEF/SubprocessApp.h"
+#include "WallpaperEngine/WebBrowser/IPC/WebHostSharedMemory.h"
 #include "include/cef_app.h"
 #include "include/cef_render_handler.h"
 #include <cerrno>
@@ -13,6 +15,7 @@
 #include <random>
 #include <sched.h>
 #include <string_view>
+#include <sys/file.h>
 #include <sys/stat.h>
 #include <sys/wait.h>
 #include <unistd.h>
@@ -143,10 +146,11 @@ WebBrowserContext::WebBrowserContext (WallpaperEngine::Application::WallpaperApp
     this->m_browserApplication = new CEF::BrowserApp (wallpaperApplication);
 
     CefSettings settings;
-    // the pid in the name lets a later engine run tell this profile is stale if we get killed before cleaning up
+    // a later engine run removes it if we get killed before cleaning up, unless something still holds its lock
     this->m_cachePath = (std::filesystem::temp_directory_path ()
-			 / ("lwe-cef-" + std::to_string (getpid ()) + "-" + uuid::generate_uuid_v4 ()))
+			 / ("lwe-cef-" + Desktop::processTag () + "-" + uuid::generate_uuid_v4 ()))
 			    .string ();
+    this->lockProfile ();
     cef_string_utf8_to_utf16 (this->m_cachePath.c_str (), this->m_cachePath.length (), &settings.root_cache_path);
     settings.windowless_rendering_enabled = true;
 
@@ -188,4 +192,21 @@ WebBrowserContext::~WebBrowserContext () {
 	std::error_code error;
 	std::filesystem::remove_all (this->m_cachePath, error);
     }
+
+    if (this->m_profileLock >= 0) {
+	close (this->m_profileLock);
+    }
+}
+
+void WebBrowserContext::lockProfile () {
+    std::error_code error;
+    std::filesystem::create_directories (this->m_cachePath, error);
+
+    const auto lockFile = std::filesystem::path (this->m_cachePath) / IPC::CEF_PROFILE_LOCK;
+    this->m_profileLock = open (lockFile.c_str (), O_CREAT | O_RDWR | O_CLOEXEC, 0600);
+
+    if (this->m_profileLock >= 0 && flock (this->m_profileLock, LOCK_SH) != 0) {
+	close (this->m_profileLock);
+	this->m_profileLock = -1;
+    }
 }

+ 4 - 0
src/WallpaperEngine/WebBrowser/WebBrowserContext.h

@@ -26,10 +26,14 @@ public:
     static int runSubprocess (int argc, char* argv[]);
 
 private:
+    /** creates the profile folder with a lock file held until this process ends, the mark that it is in use */
+    void lockProfile ();
+
     CefRefPtr<CefApp> m_browserApplication = nullptr;
     CefRefPtr<CefCommandLine> m_commandLine = nullptr;
     // Chromium profile of this process, created under the temp directory and removed once CEF is shut down
     std::string m_cachePath;
+    int m_profileLock = -1;
     WallpaperEngine::Application::WallpaperApplication& m_wallpaperApplication;
 };
 } // namespace WallpaperEngine::WebBrowser

+ 38 - 5
src/gnome_wayland_helper.c

@@ -1,8 +1,10 @@
 /*
  * linux-wallpaperengine-gnome-helper <socket path>
  *
- * GNOME 45-48 only make desktop windows of a client the Shell spawned (MetaWaylandClient owns_window). The extension
- * spawns this, it passes WAYLAND_SOCKET to the engine on <socket path> and lives until the engine closes it.
+ * Hands the engine a Wayland connection made outside of it, over <socket path>, and lives until the engine closes it.
+ * GNOME 45-48 only make desktop windows of a client the Shell spawned (MetaWaylandClient owns_window): the extension
+ * spawns this with WAYLAND_SOCKET set. A Flatpak engine starts it on the host through flatpak-spawn when its own
+ * socket (Flatpak's security context) hides the layer shell: then it connects to WAYLAND_DISPLAY itself.
  */
 #include <errno.h>
 #include <stdio.h>
@@ -12,6 +14,37 @@
 #include <sys/un.h>
 #include <unistd.h>
 
+/* what libwayland's wl_display_connect does: an absolute WAYLAND_DISPLAY, else one in XDG_RUNTIME_DIR */
+static int connect_display (void) {
+    const char* display = getenv ("WAYLAND_DISPLAY");
+    const char* runtime = getenv ("XDG_RUNTIME_DIR");
+    struct sockaddr_un address = { .sun_family = AF_UNIX };
+
+    if (!display || !*display) {
+	display = "wayland-0";
+    }
+
+    const int written = display[0] == '/'
+	? snprintf (address.sun_path, sizeof (address.sun_path), "%s", display)
+	: snprintf (address.sun_path, sizeof (address.sun_path), "%s/%s", runtime ? runtime : "", display);
+
+    if (written < 0 || (size_t)written >= sizeof (address.sun_path) || (display[0] != '/' && !runtime)) {
+	return -1;
+    }
+
+    const int fd = socket (AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0);
+
+    if (fd < 0 || connect (fd, (struct sockaddr*)&address, sizeof (address)) != 0) {
+	fprintf (stderr, "cannot connect to %s: %s\n", address.sun_path, strerror (errno));
+	if (fd >= 0) {
+	    close (fd);
+	}
+	return -1;
+    }
+
+    return fd;
+}
+
 int main (int argc, char** argv) {
     if (argc != 2) {
 	fprintf (stderr, "usage: %s <socket path>\n", argv[0]);
@@ -20,10 +53,10 @@ int main (int argc, char** argv) {
 
     const char* wayland = getenv ("WAYLAND_SOCKET");
     char* end = NULL;
-    const long fd = wayland ? strtol (wayland, &end, 10) : -1;
+    const long fd = wayland ? strtol (wayland, &end, 10) : connect_display ();
 
-    if (fd < 0 || !end || *end != '\0') {
-	fprintf (stderr, "no WAYLAND_SOCKET from the compositor\n");
+    if (fd < 0 || (wayland && (!end || *end != '\0'))) {
+	fprintf (stderr, "no WAYLAND_SOCKET from the compositor and no WAYLAND_DISPLAY to connect to\n");
 	return 2;
     }
 

+ 4 - 0
src/main.cpp

@@ -44,6 +44,10 @@ int main (int argc, char* argv[]) {
 
 	initLogging ();
 
+	// we_manager reads our output through pipes and the engine outlives it: after the app quits, the next log line
+	// (a hotswap logs right away) would end the engine with SIGPIPE
+	std::signal (SIGPIPE, SIG_IGN);
+
 	WallpaperEngine::Application::ApplicationContext appContext (argc, argv);
 
 	appContext.loadSettingsFromArgv ();

+ 1 - 0
tests/desktops/fixtures/posprobe/project.json

@@ -0,0 +1 @@
+{"file": "scene.json", "type": "scene", "title": "pointer position probe", "general": {"properties": {}}}

+ 32 - 0
tests/desktops/fixtures/posprobe/scene.json

@@ -0,0 +1,32 @@
+{
+ "version": 3,
+ "camera": {
+  "center": "0 0 -1",
+  "eye": "0 0 0",
+  "up": "0 1 0"
+ },
+ "general": {
+  "orthogonalprojection": {
+   "width": 1920,
+   "height": 1080
+  },
+  "clearcolor": "0 0 0",
+  "bloom": false,
+  "cameraparallax": false
+ },
+ "objects": [
+  {
+   "id": 1,
+   "name": "probe",
+   "image": "models/util/solidlayer.json",
+   "size": "1920 1080",
+   "origin": "960 540 0",
+   "color": "0.2 0.4 0.6",
+   "visible": true,
+   "alpha": {
+    "script": "'use strict';\nexport function cursorMove(event) { console.log('LWE-POS ' + input.cursorScreenPosition.x.toFixed(1) + ' ' + input.cursorScreenPosition.y.toFixed(1)); }\nexport function update(value) { return value; }\n",
+    "value": 1.0
+   }
+  }
+ ]
+}

+ 98 - 0
tests/desktops/test_fractional_scale.py

@@ -0,0 +1,98 @@
+import re
+import time
+from pathlib import Path
+
+import pytest
+
+from conftest import Unsupported
+
+POSITION_PROBE = Path(__file__).parent / "fixtures/posprobe"
+
+# WE 2.8.42 is per monitor DPI aware and sizes its swap chain from the client rect, so it draws every monitor at its
+# native pixel size whatever the scaling; on a 1.5x output that takes wp_fractional_scale_v1 + wp_viewporter
+SCALE = 1.5
+
+SESSIONS = ["sway", "labwc", "wayfire", "hyprland", "niri", "kde", "gnome"]
+# the ones with zwlr_virtual_pointer_manager_v1
+POINTER_SESSIONS = ["sway", "hyprland", "niri"]
+
+BUFFER = re.compile(r"create_immed\(new id wl_buffer#\d+, (\d+), (\d+),")
+DESTINATION = re.compile(r"wp_viewport#\d+\.set_destination\((\d+), (\d+)\)")
+
+
+def _set_scale(desktop):
+    try:
+        desktop.set_scale(SCALE)
+    except Unsupported as error:
+        pytest.skip(str(error))
+    except Exception:
+        # some outputs may have changed before the failure, the session is shared with the next tests
+        desktop.set_scale(1)
+        raise
+
+
+@pytest.mark.parametrize("desktop", SESSIONS, indirect=True)
+def test_buffer_has_the_output_pixel_size(desktop, engine, tmp_path):
+    _set_scale(desktop)
+
+    log = tmp_path / "engine.log"
+    process = None
+    try:
+        process = desktop.client([engine["binary"], "--assets-dir", engine["assets"], "--screen-root",
+                                  desktop.output_names()[0], "--silent", "--fps", "30", engine["wallpaper"]],
+                                 log=log, env={"WAYLAND_DEBUG": "1"})
+        width, height = desktop.size
+        logical = (round(width / SCALE), round(height / SCALE))
+        deadline = time.monotonic() + 40
+        buffers, destinations = [], []
+        while time.monotonic() < deadline and not (buffers and destinations):
+            time.sleep(2)
+            assert process.poll() is None, f"the engine exited with {process.returncode}:\n{log.read_text()[-1500:]}"
+            text = log.read_text(errors="replace")
+            buffers = [tuple(map(int, found)) for found in BUFFER.findall(text)]
+            destinations = [tuple(map(int, found)) for found in DESTINATION.findall(text)]
+        assert buffers, f"no buffer was attached on {desktop.name}"
+        assert buffers[-1] == (width, height), f"{desktop.name} at {SCALE}x got {buffers[-1]} buffers"
+        assert destinations and destinations[-1] == logical, f"viewport destination {destinations[-1:]}"
+    finally:
+        if process is not None:
+            process.terminate()
+            process.wait(10)
+        desktop.set_scale(1)
+
+
+@pytest.mark.parametrize("desktop", POINTER_SESSIONS, indirect=True)
+def test_pointer_is_in_buffer_pixels(desktop, engine, tmp_path):
+    """WE gives scripts the cursor in the window's physical client pixels"""
+    _set_scale(desktop)
+
+    log = tmp_path / "engine.log"
+    pointer = process = None
+    try:
+        pointer = desktop.virtual_pointer()
+        process = desktop.client([engine["binary"], "--assets-dir", engine["assets"], "--screen-root",
+                                  desktop.output_names()[0], "--silent", "--fps", "30", str(POSITION_PROBE)],
+                                 log=log, env={"LWE_SCRIPT_LOG": "1"})
+        width, height = desktop.size
+        logical = (round(width / SCALE), round(height / SCALE))
+        expected = f"LWE-POS {width / 4:.1f} {height / 4:.1f}"
+        deadline = time.monotonic() + 40
+        seen = []
+        while time.monotonic() < deadline and expected not in seen:
+            assert process.poll() is None, f"the engine exited with {process.returncode}:\n{log.read_text()[-1500:]}"
+            # a quarter of the logical output from the top left, nudged so every round is a motion
+            for x in (logical[0] // 4 + 1, logical[0] // 4):
+                pointer.stdin.write(f"abs {x} {logical[1] // 4} {logical[0]} {logical[1]}\n")
+                pointer.stdin.flush()
+                pointer.stdout.readline()
+                time.sleep(0.3)
+            seen = re.findall(r"LWE-POS [-\d.]+ [-\d.]+", log.read_text(errors="replace"))
+        assert expected in seen, f"{desktop.name} at {SCALE}x: {seen[-3:]}"
+    finally:
+        if pointer is not None:
+            pointer.stdin.close()
+            pointer.wait(10)
+        if process is not None:
+            process.terminate()
+            process.wait(10)
+        desktop.set_scale(1)

+ 3 - 1
tests/desktops/test_gnome.py

@@ -55,10 +55,12 @@ def _window(desktop, mode, name=None):
     any input (focus stealing prevention), and WE counts only the focused window as fullscreen"""
     process = desktop.spawn(name or f"{mode}-probe", ["python3", str(REPO / "tools/desktops/wayland_window.py"), mode])
     title = f"lwe-{mode}-probe"
+    # Mutter 17 (GNOME 49) drops an activation that comes before the window is shown, so ask until it has the focus
     for _ in range(40):
         time.sleep(0.25)
         if desktop.eval(f"const w = global.display.list_all_windows().find(w => w.get_title() === '{title}');"
-                        "if (w) w.activate(global.display.get_current_time_roundtrip()); !!w") == "true":
+                        "if (w && !w.has_focus()) w.activate(global.display.get_current_time_roundtrip());"
+                        "!!w && w.has_focus()") == "true":
             break
     return process
 

+ 114 - 0
tests/desktops/test_span.py

@@ -0,0 +1,114 @@
+"""--screen-span on two outputs: WE makes a stretch group one monitor with the bounding box of its monitors
+(wallpaper64.exe 2.8.42 sub_140061B50), so the cursor is in that box's pixels wherever it is (sub_140110630)."""
+import json
+import os
+import signal
+import time
+
+import pytest
+
+from test_fractional_scale import POSITION_PROBE
+
+LAYOUTS = {
+    # name: (outputs as (x, y, scale), pointer positions in the layout)
+    "side": (((0, 0, 1), (1280, 0, 1)), ((100, 100), (1290, 100), (2550, 710))),
+    "gap": (((0, 0, 1), (1480, 200, 1)), ((100, 100), (1490, 300), (2750, 910))),
+    "mixed": (((0, 0, 1), (1280, 0, 2)), ((100, 100), (1290, 100), (1910, 350))),
+}
+
+
+@pytest.fixture
+def sway(desktop_factory):
+    return desktop_factory("sway-dual")
+
+
+def _swaymsg(sway, *command):
+    result = sway.run(["swaymsg", *command], sway.extra)
+    assert result.returncode == 0, result.stderr or result.stdout
+    return result.stdout
+
+
+def _layout(sway, outputs):
+    for index, (x, y, scale) in enumerate(outputs, 1):
+        _swaymsg(sway, f"output HEADLESS-{index} enable mode 1280x720 pos {x} {y} scale {scale}")
+
+
+def _engine(sway, engine, log, wallpaper, *extra):
+    return sway.client([engine["binary"], "--assets-dir", engine["assets"], "--silent", "--fps", "30", *extra,
+                        "--screen-span", "HEADLESS-1,HEADLESS-2", "--bg", str(wallpaper)],
+                       log=log, env={"LWE_SCRIPT_LOG": "1"})
+
+
+@pytest.mark.parametrize("layout", LAYOUTS)
+def test_cursor_is_in_group_pixels(sway, engine, tmp_path, layout):
+    outputs, points = LAYOUTS[layout]
+    log = tmp_path / "engine.log"
+    pointer = sway.virtual_pointer()
+    process = None
+    try:
+        _layout(sway, outputs)
+        rects = [output["rect"] for output in json.loads(_swaymsg(sway, "-t", "get_outputs", "-r"))]
+        left, top = min(rect["x"] for rect in rects), min(rect["y"] for rect in rects)
+        width = max(rect["x"] + rect["width"] for rect in rects)
+        height = max(rect["y"] + rect["height"] for rect in rects)
+        scale = max(scale for _, _, scale in outputs)
+
+        process = _engine(sway, engine, log, POSITION_PROBE)
+        time.sleep(8)
+        for x, y in points:
+            expected = f"LWE-POS {(x - left) * scale:.1f} {(y - top) * scale:.1f}"
+            seen = None
+            for _ in range(10):
+                assert process.poll() is None, f"the engine exited with {process.returncode}"
+                for dx in (1, 0):
+                    pointer.stdin.write(f"abs {x + dx} {y} {width} {height}\n")
+                    pointer.stdin.flush()
+                    pointer.stdout.readline()
+                    time.sleep(0.3)
+                lines = [line for line in log.read_text(errors="replace").splitlines() if "LWE-POS" in line]
+                seen = lines[-1].strip() if lines else None
+                if seen == expected:
+                    break
+            assert seen == expected, f"pointer at {x},{y} in the {layout} layout"
+    finally:
+        pointer.stdin.write("quit\n")
+        pointer.stdin.flush()
+        if process is not None:
+            process.terminate()
+            process.wait(10)
+        _layout(sway, LAYOUTS["side"][0])
+
+
+def test_group_survives_hotswap_resize_and_unplug(sway, engine, tmp_path):
+    _layout(sway, LAYOUTS["side"][0])
+    log = tmp_path / "engine.log"
+    control = tmp_path / "control"
+    process = _engine(sway, engine, log, engine["wallpaper"], "--control-file", str(control))
+
+    def spans():
+        return [line for line in log.read_text(errors="replace").splitlines() if line.startswith("Span ")]
+
+    try:
+        time.sleep(8)
+        steps = [
+            ("output HEADLESS-2 mode 1920x1080", "3200x1080 at 0,0, rendered at 1x"),
+            ("output HEADLESS-2 mode 1280x720 scale 2", "1920x720 at 0,0, rendered at 2x"),
+            ("output HEADLESS-2 scale 1", "2560x720 at 0,0, rendered at 1x"),
+            ("output HEADLESS-1 disable", "1280x720 at 1280,0, rendered at 1x"),
+            ("output HEADLESS-1 enable", "2560x720 at 0,0, rendered at 1x"),
+        ]
+        for command, expected in steps:
+            _swaymsg(sway, command)
+            time.sleep(4)
+            assert process.poll() is None, f"the engine exited with {process.returncode} after {command}"
+            assert spans() and spans()[-1].endswith(expected), f"after {command}: {spans()[-1:]}"
+
+        # the group's one wallpaper is replaced on both outputs, the old project must not be read afterwards
+        control.write_text(f"path={POSITION_PROBE}\n")
+        os.kill(process.pid, signal.SIGUSR1)
+        time.sleep(6)
+        assert process.poll() is None, f"the engine exited with {process.returncode} after the hotswap"
+    finally:
+        process.terminate()
+        process.wait(10)
+        _layout(sway, LAYOUTS["side"][0])

+ 90 - 0
tests/desktops/test_wlroots_pause.py

@@ -0,0 +1,90 @@
+"""wlroots compositors: the foreign toplevel detector pauses only the outputs a window is on."""
+import time
+
+import pytest
+
+from conftest import REPO
+from test_kde import _engine, _renders
+from desktops.runner import Userland, terminate
+
+DUAL_SESSIONS = ["sway-dual", "labwc-dual"]
+
+
+def _engines(desktop, engine, tmp_path, *extra):
+    outputs = desktop.output_names()
+    assert len(outputs) == 2, outputs
+    logs = [tmp_path / f"engine-{output}.log" for output in outputs]
+    # one engine per screen, like we_manager
+    return logs, [_engine(desktop, engine, log, output, *extra) for log, output in zip(logs, outputs)]
+
+
+def _window(desktop, mode):
+    # GTK from the image, the Arch rootfs has no PyGObject
+    return desktop.spawn(f"{mode}-probe", ["python3", str(REPO / "tools/desktops/wayland_window.py"), mode],
+                         userland=Userland("native"))
+
+
+def _stop(probe, processes):
+    if probe is not None:
+        terminate([probe.pid])
+    for process in processes:
+        process.terminate()
+        process.wait(10)
+
+
+@pytest.mark.parametrize("desktop", DUAL_SESSIONS, indirect=True)
+def test_fullscreen_pauses_its_output_only(desktop, engine, tmp_path):
+    logs, processes = _engines(desktop, engine, tmp_path)
+    probe = None
+    try:
+        time.sleep(8)
+        assert all(_renders(log) for log in logs), "the engines do not render"
+        probe = _window(desktop, "fullscreen")
+        time.sleep(4)
+        rendering = [_renders(log) for log in logs]
+        assert rendering.count(False) == 1, f"a fullscreen window should pause exactly its own output: {rendering}"
+        terminate([probe.pid])
+        probe = None
+        time.sleep(4)
+        assert all(_renders(log) for log in logs), "rendering did not resume after the fullscreen window"
+    finally:
+        _stop(probe, processes)
+
+
+@pytest.mark.parametrize("pause_on_maximized", [False, True])
+def test_maximized_window(desktop_factory, engine, tmp_path, pause_on_maximized):
+    labwc = desktop_factory("labwc-dual")
+    logs, processes = _engines(labwc, engine, tmp_path, *(["--pause-on-maximized"] if pause_on_maximized else []))
+    probe = None
+    try:
+        time.sleep(8)
+        probe = _window(labwc, "maximized")
+        time.sleep(4)
+        rendering = [_renders(log) for log in logs]
+        if pause_on_maximized:
+            assert rendering.count(False) == 1, f"a maximized window should pause exactly its own output: {rendering}"
+        else:
+            assert all(rendering), f"a maximized window paused without --pause-on-maximized: {rendering}"
+    finally:
+        _stop(probe, processes)
+
+
+def test_fullscreen_follows_its_window(desktop_factory, engine, tmp_path):
+    sway = desktop_factory("sway-dual")
+    logs, processes = _engines(sway, engine, tmp_path)
+    outputs = sway.output_names()
+    probe = None
+    try:
+        time.sleep(8)
+        probe = _window(sway, "fullscreen")
+        time.sleep(4)
+        first = [_renders(log) for log in logs]
+        assert first.count(False) == 1, first
+        other = outputs[first.index(True)]
+        moved = sway.run(["swaymsg", "[app_id=org.lwe.Probe] move container to output " + other], sway.extra)
+        assert moved.returncode == 0, moved.stderr or moved.stdout
+        time.sleep(4)
+        second = [_renders(log) for log in logs]
+        assert second == [not was for was in first], f"the pause did not move with the window: {first} -> {second}"
+    finally:
+        _stop(probe, processes)

+ 1 - 1
tools/desktops/__init__.py

@@ -1 +1 @@
-"""Headless desktop sessions for the integration tests: see session.py and the tools list in CLAUDE.md."""
+"""Headless desktop sessions for the integration tests: see session.py"""

+ 1 - 1
tools/desktops/rootfs-ubuntu-kde5.txt

@@ -1,2 +1,2 @@
 kwin-wayland kscreen dbus dbus-x11 xwayland wayland-utils plasma-wayland-protocols
-gir1.2-gtk-4.0 python3-gi python3-dbus python3-dbusmock
+gir1.2-gtk-4.0 python3-gi python3-dbus python3-dbusmock python3-pil

+ 73 - 1
tools/desktops/session.py

@@ -214,6 +214,30 @@ class Session:
     def _x_outputs(self):
         return []
 
+    def set_scale(self, scale):
+        """the scale of every output, fractional where the desktop has it"""
+        raise Unsupported(f"no way to set the output scale on {self.name} yet")
+
+    def virtual_pointer(self):
+        """a pointer that stays while it runs (wlroots-style compositors): write "abs x y width height" lines to its stdin"""
+        tool = BASE / "wlr_virtual_pointer"
+        source = REPO / "tools/desktops/wlr_virtual_pointer.c"
+        if not tool.exists() or tool.stat().st_mtime < source.stat().st_mtime:
+            build = BASE / "wlr-virtual-pointer"
+            build.mkdir(parents=True, exist_ok=True)
+            xml = REPO / "tools/desktops/wlr-virtual-pointer-unstable-v1.xml"
+            for mode, out in (("client-header", "wlr-virtual-pointer-unstable-v1-client-protocol.h"),
+                              ("private-code", "wlr-virtual-pointer.c")):
+                subprocess.run(["wayland-scanner", mode, str(xml), str(build / out)], check=True)
+            subprocess.run(["cc", "-o", str(tool), str(source), str(build / "wlr-virtual-pointer.c"), f"-I{build}",
+                            "-lwayland-client"], check=True)
+        return subprocess.Popen([str(tool)], stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True,
+                                env={**self.client_env(), "PATH": os.environ.get("PATH", "")})
+
+    def _check(self, result, what):
+        if result.returncode != 0:
+            raise RuntimeError(f"{what} failed: {result.stderr.strip() or result.stdout.strip()}")
+
     def windows(self):
         return []
 
@@ -288,6 +312,10 @@ class Wlroots(Session):
         if result.returncode != 0:
             raise RuntimeError(f"grim failed: {result.stderr.strip()}")
 
+    def set_scale(self, scale):
+        for output in self.output_names():
+            self._check(self.run(["wlr-randr", "--output", output, "--scale", str(scale)]), "wlr-randr --scale")
+
 
 class Sway(Wlroots):
     name, short, program, desktop = "sway", "s", "sway", "sway"
@@ -323,6 +351,26 @@ class Labwc(Wlroots):
         return ["-C", str(config)]
 
 
+class SwayDual(Sway):
+    """two headless outputs, for what happens per output; Arch's sway first, 1.11 sends no output_enter for a
+    window that maps fullscreen (fixed in 1.12 by 81246fc6dc)"""
+
+    name, short = "sway-dual", "s2"
+    userlands = ("arch", "native", "fedora")
+
+    def __init__(self, size=(1280, 720), outputs=2):
+        super().__init__(size, outputs)
+
+
+class LabwcDual(Labwc):
+    """two headless outputs, for what happens per output"""
+
+    name, short = "labwc-dual", "l2"
+
+    def __init__(self, size=(1280, 720), outputs=2):
+        super().__init__(size, outputs)
+
+
 class Wayfire(Wlroots):
     name, short, program, desktop = "wayfire", "w", "wayfire", "wayfire"
     needs = ("wayfire", "wlr-randr", "grim")
@@ -396,6 +444,14 @@ class Hyprland(Nested):
         for _ in range(self.outputs):
             self.run(["hyprctl", "output", "create", "headless"], self.extra)
 
+    def set_scale(self, scale):
+        width, height = self.size
+        for index, output in enumerate(sorted(self.output_names())):
+            # the layout position is in logical pixels
+            x = round(width / scale) * index
+            self._check(self.run(["hyprctl", "keyword", "monitor", f"{output},{width}x{height}@60,{x}x0,{scale}"]),
+                        "hyprctl keyword monitor")
+
 
 class Niri(Nested):
     name, short, program, desktop = "niri", "n", "niri", "niri"
@@ -409,6 +465,10 @@ class Niri(Nested):
         super()._wait()
         self.extra["NIRI_SOCKET"] = wait_for("niri's IPC socket", lambda: self._socket("niri.*.sock"), 30)
 
+    def set_scale(self, scale):
+        for output in self.output_names():
+            self._check(self.run(["niri", "msg", "output", output, "scale", str(scale)]), "niri msg output scale")
+
 
 class Cosmic(Nested):
     name, short, program, desktop = "cosmic", "c", "cosmic-comp", "COSMIC"
@@ -440,6 +500,10 @@ class Kde(Session):
         self.wait_socket("lwe-kde")
         wait_for("KWin on the session bus", lambda: self._bus_name("org.kde.KWin"), 40)
 
+    def set_scale(self, scale):
+        for output in self.output_names():
+            self._check(self.run(["kscreen-doctor", f"output.{output}.scale.{scale}"]), "kscreen-doctor")
+
     def pointer(self, *commands):
         """KWin's pointer through fake input: "move", x, y (logical, global), "down"/"up", evdev button"""
         tool = self.dir / "kwin_fake_input"
@@ -533,6 +597,14 @@ class Gnome(Session):
         wait_for("the lab extension", self._unsafe_mode, 40)
         wait_for("the overview to close", lambda: self.eval("Main.overview.hide(); Main.overview.visible") == "false", 20)
 
+    def set_scale(self, scale):
+        argv = ["gdctl", "set"]
+        outputs = self.output_names()
+        for index, output in enumerate(outputs):
+            place = ["--primary"] if index == 0 else ["--right-of", outputs[index - 1]]
+            argv += ["--logical-monitor", *place, "--scale", str(scale), "--monitor", output]
+        self._check(self.run(argv), "gdctl set")
+
     def _unsafe_mode(self):
         reply = self.eval("global.context.unsafe_mode")
         return reply == "true"
@@ -748,5 +820,5 @@ WM_CLASSES = [
 
 KINDS = {
     kind.name: kind
-    for kind in (Sway, Labwc, Wayfire, River, Hyprland, Niri, Cosmic, Kde, KdeDual, Kde5, Gnome, Gnome45, Gnome46, Gnome47, Gnome48, Gnome49, GnomeDing, Gnome45Ding, Gnome46Ding, Xfce, Cinnamon, Mate, Lxqt, *WM_CLASSES)
+    for kind in (Sway, SwayDual, Labwc, LabwcDual, Wayfire, River, Hyprland, Niri, Cosmic, Kde, KdeDual, Kde5, Gnome, Gnome45, Gnome46, Gnome47, Gnome48, Gnome49, GnomeDing, Gnome45Ding, Gnome46Ding, Xfce, Cinnamon, Mate, Lxqt, *WM_CLASSES)
 }

+ 152 - 0
tools/desktops/wlr-virtual-pointer-unstable-v1.xml

@@ -0,0 +1,152 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<protocol name="wlr_virtual_pointer_unstable_v1">
+  <copyright>
+    Copyright © 2019 Josef Gajdusek
+
+    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="zwlr_virtual_pointer_v1" version="2">
+    <description summary="virtual pointer">
+      This protocol allows clients to emulate a physical pointer device. The
+      requests are mostly mirror opposites of those specified in wl_pointer.
+    </description>
+
+    <enum name="error">
+      <entry name="invalid_axis" value="0"
+        summary="client sent invalid axis enumeration value" />
+      <entry name="invalid_axis_source" value="1"
+        summary="client sent invalid axis source enumeration value" />
+    </enum>
+
+    <request name="motion">
+      <description summary="pointer relative motion event">
+        The pointer has moved by a relative amount to the previous request.
+
+        Values are in the global compositor space.
+      </description>
+      <arg name="time" type="uint" summary="timestamp with millisecond granularity"/>
+      <arg name="dx" type="fixed" summary="displacement on the x-axis"/>
+      <arg name="dy" type="fixed" summary="displacement on the y-axis"/>
+    </request>
+
+    <request name="motion_absolute">
+      <description summary="pointer absolute motion event">
+        The pointer has moved in an absolute coordinate frame.
+
+        Value of x can range from 0 to x_extent, value of y can range from 0
+        to y_extent.
+      </description>
+      <arg name="time" type="uint" summary="timestamp with millisecond granularity"/>
+      <arg name="x" type="uint" summary="position on the x-axis"/>
+      <arg name="y" type="uint" summary="position on the y-axis"/>
+      <arg name="x_extent" type="uint" summary="extent of the x-axis"/>
+      <arg name="y_extent" type="uint" summary="extent of the y-axis"/>
+    </request>
+
+    <request name="button">
+      <description summary="button event">
+        A button was pressed or released.
+      </description>
+      <arg name="time" type="uint" summary="timestamp with millisecond granularity"/>
+      <arg name="button" type="uint" summary="button that produced the event"/>
+      <arg name="state" type="uint" enum="wl_pointer.button_state" summary="physical state of the button"/>
+    </request>
+
+    <request name="axis">
+      <description summary="axis event">
+        Scroll and other axis requests.
+      </description>
+      <arg name="time" type="uint" summary="timestamp with millisecond granularity"/>
+      <arg name="axis" type="uint" enum="wl_pointer.axis" summary="axis type"/>
+      <arg name="value" type="fixed" summary="length of vector in touchpad coordinates"/>
+    </request>
+
+    <request name="frame">
+      <description summary="end of a pointer event sequence">
+        Indicates the set of events that logically belong together.
+      </description>
+    </request>
+
+    <request name="axis_source">
+      <description summary="axis source event">
+        Source information for scroll and other axis.
+      </description>
+      <arg name="axis_source" type="uint" enum="wl_pointer.axis_source" summary="source of the axis event"/>
+    </request>
+
+    <request name="axis_stop">
+      <description summary="axis stop event">
+        Stop notification for scroll and other axes.
+      </description>
+      <arg name="time" type="uint" summary="timestamp with millisecond granularity"/>
+      <arg name="axis" type="uint" enum="wl_pointer.axis" summary="the axis stopped with this event"/>
+    </request>
+
+    <request name="axis_discrete">
+      <description summary="axis click event">
+        Discrete step information for scroll and other axes.
+
+        This event allows the client to extend data normally sent using the axis
+        event with discrete value.
+      </description>
+      <arg name="time" type="uint" summary="timestamp with millisecond granularity"/>
+      <arg name="axis" type="uint" enum="wl_pointer.axis" summary="axis type"/>
+      <arg name="value" type="fixed" summary="length of vector in touchpad coordinates"/>
+      <arg name="discrete" type="int" summary="number of steps"/>
+    </request>
+
+    <request name="destroy" type="destructor" since="1">
+      <description summary="destroy the virtual pointer object"/>
+    </request>
+  </interface>
+
+  <interface name="zwlr_virtual_pointer_manager_v1" version="2">
+    <description summary="virtual pointer manager">
+      This object allows clients to create individual virtual pointer objects.
+    </description>
+
+    <request name="create_virtual_pointer">
+      <description summary="Create a new virtual pointer">
+        Creates a new virtual pointer. The optional seat is a suggestion to the
+        compositor.
+      </description>
+      <arg name="seat" type="object" interface="wl_seat" allow-null="true"/>
+      <arg name="id" type="new_id" interface="zwlr_virtual_pointer_v1"/>
+    </request>
+
+    <request name="destroy" type="destructor" since="1">
+      <description summary="destroy the virtual pointer manager"/>
+    </request>
+
+    <!-- Version 2 additions -->
+    <request name="create_virtual_pointer_with_output" since="2">
+      <description summary="Create a new virtual pointer">
+        Creates a new virtual pointer. The seat and the output arguments are
+        optional. If the seat argument is set, the compositor should assign the
+        input device to the requested seat. If the output argument is set, the
+        compositor should map the input device to the requested output.
+      </description>
+      <arg name="seat" type="object" interface="wl_seat" allow-null="true"/>
+      <arg name="output" type="object" interface="wl_output" allow-null="true"/>
+      <arg name="id" type="new_id" interface="zwlr_virtual_pointer_v1"/>
+    </request>
+  </interface>
+</protocol>

+ 66 - 0
tools/desktops/wlr_virtual_pointer.c

@@ -0,0 +1,66 @@
+// One virtual pointer for wlroots-style compositors (sway, labwc, Hyprland, niri), kept for as long as stdin is open:
+// wlrctl makes a new device per call and the seat's pointer capability comes and goes with it.
+// stdin lines: "abs <x> <y> <width> <height>" (position within a layout extent), "quit"; each answered with "ok"
+#include <stdio.h>
+#include <string.h>
+#include <wayland-client.h>
+
+#include "wlr-virtual-pointer-unstable-v1-client-protocol.h"
+
+static struct zwlr_virtual_pointer_manager_v1* manager;
+static struct wl_seat* seat;
+
+static void global (void* data, struct wl_registry* registry, uint32_t name, const char* interface, uint32_t version) {
+    if (strcmp (interface, zwlr_virtual_pointer_manager_v1_interface.name) == 0) {
+	manager = wl_registry_bind (registry, name, &zwlr_virtual_pointer_manager_v1_interface, 1);
+    } else if (strcmp (interface, wl_seat_interface.name) == 0) {
+	seat = wl_registry_bind (registry, name, &wl_seat_interface, 1);
+    }
+}
+
+static void global_remove (void* data, struct wl_registry* registry, uint32_t name) { }
+
+static const struct wl_registry_listener registry_listener = { global, global_remove };
+
+int main (void) {
+    struct wl_display* display = wl_display_connect (NULL);
+
+    if (!display) {
+	fprintf (stderr, "no wayland display\n");
+	return 1;
+    }
+
+    wl_registry_add_listener (wl_display_get_registry (display), &registry_listener, NULL);
+    wl_display_roundtrip (display);
+
+    if (!manager) {
+	fprintf (stderr, "the compositor has no zwlr_virtual_pointer_manager_v1\n");
+	return 1;
+    }
+
+    struct zwlr_virtual_pointer_v1* pointer = zwlr_virtual_pointer_manager_v1_create_virtual_pointer (manager, seat);
+    char line[256];
+    uint32_t time = 1;
+
+    wl_display_roundtrip (display);
+
+    while (fgets (line, sizeof line, stdin)) {
+	unsigned x, y, width, height;
+
+	if (sscanf (line, "abs %u %u %u %u", &x, &y, &width, &height) == 4) {
+	    zwlr_virtual_pointer_v1_motion_absolute (pointer, time++, x, y, width, height);
+	    zwlr_virtual_pointer_v1_frame (pointer);
+	} else if (strncmp (line, "quit", 4) == 0) {
+	    break;
+	}
+
+	wl_display_roundtrip (display);
+	printf ("ok\n");
+	fflush (stdout);
+    }
+
+    zwlr_virtual_pointer_v1_destroy (pointer);
+    wl_display_roundtrip (display);
+    wl_display_disconnect (display);
+    return 0;
+}

+ 55 - 0
tools/gpu_meter.sh

@@ -0,0 +1,55 @@
+#!/bin/bash
+# Measures how much of the GPU (and CPU) one wallpaper takes, from the engine's own amdgpu/i915/xe per-client
+# counters (/proc/<pid>/fdinfo drm-engine-gfx/render), so other programs on the same GPU don't skew it.
+# Renders headlessly through headless_render.sh, waits WARMUP seconds, then samples for SECONDS.
+#
+# Usage: tools/gpu_meter.sh <engine binary> <workshop item dir> [WxH] [engine args...]
+# Env: WARMUP (default 15), SECONDS_SAMPLED (default 15), LWE_ASSETS_DIR. Don't set LWE_FRAME_STATS, its glFinish
+# and timer queries roughly triple the numbers.
+set -euo pipefail
+
+BINARY=$(readlink -f "$1")
+ITEM=$2
+shift 2
+SIZE=3840x2160
+if [[ ${1:-} =~ ^[0-9]+x[0-9]+$ ]]; then
+    SIZE=$1
+    shift
+fi
+WARMUP=${WARMUP:-15}
+SAMPLED=${SECONDS_SAMPLED:-15}
+OUT=$(mktemp -d)
+RUNNER=
+trap '[ -n "$RUNNER" ] && kill "$RUNNER" 2>/dev/null; rm -rf "$OUT"' EXIT
+
+ulimit -c 0
+HEADLESS_RENDER_KEEP_RUNNING=1 HEADLESS_RENDER_SIZE=$SIZE HEADLESS_RENDER_DELAY=5000 \
+    HEADLESS_RENDER_TIMEOUT=$((WARMUP + SAMPLED + 10)) \
+    "$(dirname "$0")/headless_render.sh" "$BINARY" "$OUT/shot.png" \
+    ${LWE_ASSETS_DIR:+--assets-dir "$LWE_ASSETS_DIR"} "$@" "$ITEM" > "$OUT/log" 2>&1 &
+RUNNER=$!
+sleep "$WARMUP"
+
+PID=$(pgrep -f "^$BINARY --window 0x0x$SIZE" | head -1 || true)
+if [ -z "$PID" ]; then
+    echo "engine did not start, log:" >&2
+    cat "$OUT/log" >&2
+    exit 1
+fi
+
+gpu_ns () {
+    # one fd per DRM client can be listed several times, count each client id once
+    cat /proc/"$PID"/fdinfo/* 2>/dev/null |
+        awk '/^drm-client-id/ { c = $2 } /^drm-engine-(gfx|render):/ { if (!(c in s)) { s[c] = 1; t += $2 } } END { print t + 0 }'
+}
+cpu_ticks () { awk '{ print $14 + $15 }' /proc/"$PID"/stat; }
+
+g0=$(gpu_ns); c0=$(cpu_ticks); t0=$(date +%s.%N)
+sleep "$SAMPLED"
+g1=$(gpu_ns); c1=$(cpu_ticks); t1=$(date +%s.%N)
+
+awk -v g="$((g1 - g0))" -v c="$((c1 - c0))" -v t0="$t0" -v t1="$t1" -v hz="$(getconf CLK_TCK)" \
+    'BEGIN { dt = t1 - t0; printf "gpu %.1f%%  cpu %.1f%% of one core\n", g / 1e9 / dt * 100, c / hz / dt * 100 }'
+
+kill "$RUNNER" 2>/dev/null || true
+wait "$RUNNER" 2>/dev/null || true

+ 76 - 0
tools/linuxvm/cdp.py

@@ -0,0 +1,76 @@
+#!/usr/bin/env python3
+# cdp.py [--port N] <js expression> - evaluates JavaScript in an Electron app's page over the DevTools protocol and
+# prints the (awaited) result as JSON. Start the app with --remote-debugging-port=N (default 9222). Standard library
+# only, so it runs in a bare VM: e.g. `cdp.py "window.electronAPI.lwe.killAll()"` against we_manager.
+import base64, json, os, socket, struct, sys, urllib.request
+
+
+def recv_exact(s, n):
+    data = b''
+    while len(data) < n:
+        chunk = s.recv(n - len(data))
+        if not chunk:
+            raise EOFError('DevTools connection closed')
+        data += chunk
+    return data
+
+
+def send_frame(s, text):
+    payload = text.encode()
+    header = bytes([0x81])
+    if len(payload) < 126:
+        header += bytes([0x80 | len(payload)])
+    elif len(payload) < 65536:
+        header += bytes([0x80 | 126]) + struct.pack('>H', len(payload))
+    else:
+        header += bytes([0x80 | 127]) + struct.pack('>Q', len(payload))
+    mask = os.urandom(4)
+    s.sendall(header + mask + bytes(b ^ mask[i % 4] for i, b in enumerate(payload)))
+
+
+def recv_message(s):
+    message = b''
+    while True:
+        first, second = recv_exact(s, 2)
+        length = second & 0x7f
+        if length == 126:
+            length = struct.unpack('>H', recv_exact(s, 2))[0]
+        elif length == 127:
+            length = struct.unpack('>Q', recv_exact(s, 8))[0]
+        message += recv_exact(s, length)
+        if first & 0x80:
+            return message.decode()
+
+
+def main():
+    args = sys.argv[1:]
+    port = 9222
+    if args[:1] == ['--port']:
+        port, args = int(args[1]), args[2:]
+    targets = json.load(urllib.request.urlopen('http://127.0.0.1:%d/json' % port))
+    page = next(t for t in targets if t.get('type') == 'page')
+    host_port, path = page['webSocketDebuggerUrl'].split('://', 1)[1].split('/', 1)
+    host, ws_port = host_port.split(':')
+    s = socket.create_connection((host, int(ws_port)))
+    key = base64.b64encode(os.urandom(16)).decode()
+    s.sendall(('GET /%s HTTP/1.1\r\nHost: %s\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n'
+               'Sec-WebSocket-Key: %s\r\nSec-WebSocket-Version: 13\r\n\r\n' % (path, host_port, key)).encode())
+    response = b''
+    while b'\r\n\r\n' not in response:
+        response += s.recv(1)
+    if b' 101 ' not in response.split(b'\r\n')[0]:
+        raise RuntimeError(response.decode(errors='replace'))
+    send_frame(s, json.dumps({'id': 1, 'method': 'Runtime.evaluate', 'params': {
+        'expression': args[0], 'awaitPromise': True, 'returnByValue': True}}))
+    while True:
+        reply = json.loads(recv_message(s))
+        if reply.get('id') == 1:
+            break
+    result = reply.get('result', {})
+    if 'exceptionDetails' in result:
+        print(json.dumps(result['exceptionDetails'].get('exception', result['exceptionDetails'])), file=sys.stderr)
+        sys.exit(1)
+    print(json.dumps(result.get('result', {}).get('value')))
+
+
+main()

+ 128 - 0
tools/linuxvm/linuxvm.sh

@@ -0,0 +1,128 @@
+#!/bin/bash
+# linuxvm.sh <command> <vm> - Linux desktop VMs (KVM) for what the container can't run: Flatpak (bwrap needs user
+# namespaces), a real KMS session of a desktop. A VM is a cloud image overlay set up by cloud-init with user "lab"
+# (uid 1000, password "lab", passwordless sudo), reached over ssh on a localhost port. The guest GPU is virtio-vga-gl
+# with QEMU's egl-headless display on the container's render node (virgl), so nothing ever shows on the desktop's
+# display; screenshots and pointer input go through QMP. No audio device.
+#   fetch                 downloads the cloud images (Fedora 44, Arch)
+#   create <vm> <image>   new VM from images/<image>.qcow2 (fedora-44, arch), 60G overlay
+#   start <vm>            boots it (LINUXVM_CPUS, LINUXVM_MEM, LINUXVM_SIZE=WxH for the display)
+#   ssh <vm> [cmd]        runs a command as lab (or a shell)
+#   scp <vm> <src> <dst>  copies into the VM (dst relative to /home/lab)
+#   shot <vm> <png>       screenshot through the VNC socket (vncshot.py); pointer/click/keys/type/raw go to qmp.py
+#   stop | kill <vm>      ACPI power off | kill QEMU
+# QEMU's virtio-gpu and egl-headless modules are not in the image's qemu-system-x86-core: `fetch` unpacks the Fedora
+# RPMs (plus virglrenderer) into $LINUXVM/root and QEMU_MODULE_DIR points there.
+LINUXVM=${LINUXVM:-$HOME/.local/share/linuxvm}
+HERE=$(cd "$(dirname "$0")" && pwd)
+QMP="python3 $HERE/../wecompare/winvm/qmp.py"
+KEY=$LINUXVM/id_ed25519
+ulimit -c 0
+
+vmdir () { echo "$LINUXVM/vms/$1"; }
+port () { cat "$(vmdir "$1")/port"; }
+
+ssh_vm () {
+    local vm=$1
+    shift
+    ssh -i "$KEY" -p "$(port "$vm")" -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o LogLevel=ERROR \
+        -o ConnectTimeout=5 lab@127.0.0.1 "$@"
+}
+
+case $1 in
+fetch)
+    mkdir -p "$LINUXVM/images" "$LINUXVM/rpms" "$LINUXVM/root"
+    cd "$LINUXVM/images" || exit 1
+    [ -f fedora-44.qcow2 ] || curl -fLo fedora-44.qcow2 \
+        https://download.fedoraproject.org/pub/fedora/linux/releases/44/Cloud/x86_64/images/Fedora-Cloud-Base-Generic-44-1.7.x86_64.qcow2
+    [ -f arch.qcow2 ] || curl -fLo arch.qcow2 https://geo.mirror.pkgbuild.com/images/latest/Arch-Linux-x86_64-cloudimg.qcow2
+    cd "$LINUXVM/rpms" && dnf download --arch x86_64 qemu-device-display-virtio-gpu qemu-device-display-virtio-gpu-gl \
+        qemu-device-display-virtio-gpu-pci qemu-device-display-virtio-gpu-pci-gl qemu-device-display-virtio-vga \
+        qemu-device-display-virtio-vga-gl qemu-ui-egl-headless qemu-ui-opengl virglrenderer
+    cd "$LINUXVM/root" && for rpm in "$LINUXVM"/rpms/*.rpm; do rpm2cpio "$rpm" | cpio -idm 2>/dev/null; done
+    [ -f "$KEY" ] || ssh-keygen -q -t ed25519 -N '' -f "$KEY"
+    ;;
+create)
+    vm=$2 image=$LINUXVM/images/$3.qcow2 dir=$(vmdir "$2")
+    [ -f "$image" ] || { echo "no $image, run fetch"; exit 1; }
+    [ -e "$dir" ] && { echo "$dir exists"; exit 1; }
+    mkdir -p "$dir/seed"
+    qemu-img create -q -f qcow2 -F qcow2 -b "$image" "$dir/disk.qcow2" 60G
+    # a free localhost port per VM
+    used=$(cat "$LINUXVM"/vms/*/port 2>/dev/null)
+    p=2250
+    while echo "$used" | grep -qx $p; do p=$((p + 1)); done
+    echo $p > "$dir/port"
+    cat > "$dir/seed/meta-data" <<EOF
+instance-id: $vm
+local-hostname: $vm
+EOF
+    cat > "$dir/seed/user-data" <<EOF
+#cloud-config
+users:
+  - name: lab
+    uid: "1000"
+    groups: [wheel, video, render, input]
+    shell: /bin/bash
+    sudo: ALL=(ALL) NOPASSWD:ALL
+    lock_passwd: false
+    plain_text_passwd: lab
+    ssh_authorized_keys:
+      - $(cat "$KEY.pub")
+growpart:
+  mode: auto
+  devices: ['/']
+EOF
+    xorriso -as mkisofs -quiet -J -r -V cidata -o "$dir/seed.iso" "$dir/seed"
+    cp /usr/share/edk2/ovmf/OVMF_VARS.fd "$dir/vars.fd"
+    echo "created $vm (ssh port $p)"
+    ;;
+start)
+    vm=$2 dir=$(vmdir "$2")
+    [ -f "$dir/qemu.pid" ] && kill -0 "$(cat "$dir/qemu.pid")" 2>/dev/null && { echo running; exit 0; }
+    size=${LINUXVM_SIZE:-1920x1080}
+    QEMU_MODULE_DIR=$LINUXVM/root/usr/lib64/qemu LD_LIBRARY_PATH=$LINUXVM/root/usr/lib64 \
+    qemu-system-x86_64 -name "$vm" -machine q35 -accel kvm -cpu host -smp "${LINUXVM_CPUS:-8}" -m "${LINUXVM_MEM:-8G}" \
+        -drive if=pflash,format=raw,readonly=on,file=/usr/share/edk2/ovmf/OVMF_CODE.fd \
+        -drive if=pflash,format=raw,file="$dir/vars.fd" \
+        -drive file="$dir/disk.qcow2",if=virtio,format=qcow2,cache=unsafe,discard=unmap \
+        -drive file="$dir/seed.iso",media=cdrom,if=none,id=seed,readonly=on -device ide-cd,drive=seed \
+        -nic user,model=virtio-net-pci,hostfwd=tcp:127.0.0.1:"$(port "$vm")"-:22 \
+        -device virtio-vga-gl,xres="${size%x*}",yres="${size#*x}" \
+        -display egl-headless,rendernode="${LINUXVM_RENDERNODE:-/dev/dri/renderD128}" \
+        -vnc unix:"$dir/vnc.sock" -device qemu-xhci -device usb-tablet \
+        -qmp unix:"$dir/qmp.sock",server=on,wait=off -serial file:"$dir/serial.log" \
+        -daemonize -pidfile "$dir/qemu.pid"
+    for _ in $(seq 120); do ssh_vm "$vm" true 2>/dev/null && { echo "$vm is up"; exit 0; }; sleep 2; done
+    echo "$vm: no ssh after 4 minutes, see $dir/serial.log"
+    exit 1
+    ;;
+ssh)
+    vm=$2
+    shift 2
+    ssh_vm "$vm" "$@"
+    ;;
+scp)
+    scp -i "$KEY" -P "$(port "$2")" -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o LogLevel=ERROR \
+        -r "$3" "lab@127.0.0.1:$4"
+    ;;
+stop)
+    $QMP "$(vmdir "$2")/qmp.sock" raw '{"execute":"system_powerdown"}'
+    ;;
+kill)
+    dir=$(vmdir "$2")
+    [ -f "$dir/qemu.pid" ] && kill "$(cat "$dir/qemu.pid")"
+    ;;
+shot)
+    python3 "$HERE/vncshot.py" "$(vmdir "$2")/vnc.sock" "$3"
+    ;;
+pointer | click | keys | type | raw)
+    op=$1 vm=$2
+    shift 2
+    $QMP "$(vmdir "$vm")/qmp.sock" "$op" "$@"
+    ;;
+*)
+    sed -n '2,16p' "$0"
+    exit 1
+    ;;
+esac

Неке датотеке нису приказане због велике количине промена