Jelajahi Sumber

added more packaging

UwU 1 bulan lalu
induk
melakukan
9f03e93cd0

+ 29 - 0
.github/workflows/aur.yml

@@ -0,0 +1,29 @@
+name: AUR
+
+# linux-wallpaperengine-kde-git follows main by itself, it only needs publishing when its PKGBUILD changes. The -bin
+# package is published by the release workflow (cmake.yml) once the release has its tarballs
+on:
+  workflow_dispatch:
+  push:
+    branches: [main]
+    paths:
+      - 'packaging/aur/linux-wallpaperengine-kde-git/**'
+
+jobs:
+  publish:
+    runs-on: ubuntu-latest
+    env:
+      HAS_AUR_KEY: ${{ secrets.AUR_SSH_PRIVATE_KEY != '' }}
+    steps:
+      - uses: actions/checkout@v7
+
+      - name: Publish linux-wallpaperengine-kde-git to the AUR
+        if: env.HAS_AUR_KEY == 'true'
+        uses: KSXGitHub/github-actions-deploy-aur@v4.1.1
+        with:
+          pkgname: linux-wallpaperengine-kde-git
+          pkgbuild: ./packaging/aur/linux-wallpaperengine-kde-git/PKGBUILD
+          commit_username: ${{ secrets.AUR_USERNAME }}
+          commit_email: ${{ secrets.AUR_EMAIL }}
+          ssh_private_key: ${{ secrets.AUR_SSH_PRIVATE_KEY }}
+          commit_message: ${{ github.event.head_commit.message || 'Update PKGBUILD' }}

+ 170 - 2
.github/workflows/cmake.yml

@@ -125,9 +125,18 @@ jobs:
     strategy:
       fail-fast: false
       matrix:
-        distro: [fedora-44]
+        distro: [fedora-44, arch]
         variant: [kde, generic]
         include:
+          - distro: arch
+            image: archlinux:latest
+            # libnode itself comes from the AUR below, these are its dependencies plus CEF's
+            install: >-
+              pacman -Syu --noconfirm --needed git base-devel curl cmake glew freeglut sdl2-compat lz4 zlib ffmpeg glm
+              glfw mpv libpulse freetype2 harfbuzz dbus wayland wayland-protocols mesa libxrandr libxinerama
+              libxcursor libxi libxxf86vm fftw gmp nss at-spi2-core libcups libxcomposite libxdamage libxkbcommon
+              pango cairo alsa-lib libdrm libxshmfence ada brotli c-ares icu libffi libnghttp2 libnghttp3 libngtcp2
+              libuv openssl simdjson zstd ninja procps-ng python
           - distro: fedora-44
             image: fedora:44
             install: >-
@@ -145,6 +154,47 @@ jobs:
       - name: Install dependencies
         run: ${{ matrix.install }}
 
+      # Arch has V8's shared library only in the AUR (libnode, Node.js built with --shared): build it once per
+      # package version and cache the package. LTO is off, makepkg's own -flto without node's --enable-lto handling
+      # loses V8's assembly stack scanner at link time
+      - name: Fetch libnode PKGBUILD
+        if: matrix.distro == 'arch'
+        id: libnode
+        run: |
+          mkdir -p /tmp/libnode
+          curl -fsSL "https://aur.archlinux.org/cgit/aur.git/plain/PKGBUILD?h=libnode" -o /tmp/libnode/PKGBUILD
+          sed -i -e '/--enable-lto/d' -e "/^makedepends=/i options=('!lto')" /tmp/libnode/PKGBUILD
+          echo "version=$(. /tmp/libnode/PKGBUILD && echo $pkgver-$pkgrel)" >> "$GITHUB_OUTPUT"
+
+      - name: Cache libnode package
+        if: matrix.distro == 'arch'
+        id: libnode-cache
+        uses: actions/cache@v4
+        with:
+          path: /tmp/libnode-pkg
+          key: libnode-${{ steps.libnode.outputs.version }}-nolto
+
+      - name: Build libnode
+        if: matrix.distro == 'arch' && steps.libnode-cache.outputs.cache-hit != 'true'
+        run: |
+          useradd -m builder
+          chown -R builder /tmp/libnode
+          su builder -c 'cd /tmp/libnode && makepkg --noconfirm --nodeps'
+          mkdir -p /tmp/libnode-pkg
+          cp /tmp/libnode/libnode-[0-9]*.pkg.tar.zst /tmp/libnode-pkg/
+
+      - name: Install libnode
+        if: matrix.distro == 'arch'
+        run: pacman -U --noconfirm /tmp/libnode-pkg/libnode-[0-9]*.pkg.tar.zst
+
+      # the smoke test installs it into a fresh Arch container
+      - uses: actions/upload-artifact@v7
+        if: matrix.distro == 'arch' && matrix.variant == 'kde'
+        with:
+          name: libnode-arch
+          path: /tmp/libnode-pkg/libnode-[0-9]*.pkg.tar.zst
+          if-no-files-found: error
+
       - uses: actions/checkout@v7
         with:
           submodules: true
@@ -164,8 +214,101 @@ jobs:
           path: ${{ runner.temp }}/linux-wallpaperengine-${{ matrix.variant }}-${{ matrix.distro }}-x86_64.tar.gz
           if-no-files-found: error
 
+  # one tarball for every distribution: built on Debian 12 (glibc 2.36, the oldest base with FFmpeg 5.1 and a
+  # V8 >= 10.2 libnode), every library that isn't the system's bundled, glibc floor 2.35 (Ubuntu 22.04), see
+  # tools/package_release.sh
+  portable:
+    needs: tests
+    strategy:
+      matrix:
+        variant: [kde, generic]
+    runs-on: ubuntu-24.04
+    container: debian:12
+
+    steps:
+      - name: Install dependencies
+        env:
+          DEBIAN_FRONTEND: noninteractive
+        run: >-
+          apt-get update && apt-get -y install --no-install-recommends git ca-certificates curl build-essential
+          cmake pkg-config patchelf python3 binutils libxrandr-dev libxinerama-dev libxcursor-dev libxi-dev
+          libgl-dev libegl-dev libglew-dev freeglut3-dev libsdl2-dev liblz4-dev libavcodec-dev libavformat-dev
+          libavutil-dev libswscale-dev libswresample-dev libxxf86vm-dev libglm-dev libglfw3-dev libmpv-dev
+          libpulse-dev libfftw3-dev libfreetype-dev libharfbuzz-dev libdbus-1-dev libnode-dev libwayland-dev
+          wayland-protocols libgmp-dev libnss3 libnspr4 libcups2 libatk1.0-0 libatk-bridge2.0-0 libxcomposite1
+          libxdamage1 libgbm1 libxkbcommon0 libasound2 libpango-1.0-0 libcairo2 libdrm2 libxshmfence1
+          libatspi2.0-0
+
+      - uses: actions/checkout@v7
+        with:
+          submodules: true
+
+      - name: Configure CMake
+        run: cmake -B build -DCMAKE_BUILD_TYPE=Release -DDISABLE_KDE_FEATURES=${{ matrix.variant == 'generic' && 'ON' || 'OFF' }}
+
+      - name: Build
+        run: cmake --build build --parallel $(nproc)
+
+      - name: Package
+        run: tools/package_release.sh --portable build linux-wallpaperengine-${{ matrix.variant }}-portable-x86_64 "$RUNNER_TEMP"
+
+      - uses: actions/upload-artifact@v7
+        with:
+          name: linux-wallpaperengine-${{ matrix.variant }}-portable
+          path: ${{ runner.temp }}/linux-wallpaperengine-${{ matrix.variant }}-portable-x86_64.tar.gz
+          if-no-files-found: error
+
+  # every release tarball unpacked in a bare container of the distributions it is meant for: libraries resolve
+  # (portable: with only what a desktop has; distribution builds: plus their packages, found by soname) and
+  # --help runs
+  smoke:
+    needs: [build, distro-build, portable]
+    strategy:
+      fail-fast: false
+      matrix:
+        include:
+          - { image: 'ubuntu:22.04', tarball: kde-portable }
+          - { image: 'ubuntu:22.04', tarball: generic-portable }
+          - { image: 'ubuntu:24.04', tarball: kde-portable }
+          - { image: 'ubuntu:26.04', tarball: kde-portable }
+          - { image: 'debian:12', tarball: kde-portable }
+          - { image: 'debian:13', tarball: kde-portable }
+          - { image: 'fedora:43', tarball: kde-portable }
+          - { image: 'fedora:44', tarball: kde-portable }
+          - { image: 'fedora:45', tarball: kde-portable }
+          - { image: 'opensuse/leap:16.0', tarball: kde-portable }
+          - { image: 'opensuse/tumbleweed', tarball: kde-portable }
+          - { image: 'archlinux:latest', tarball: kde-portable }
+          - { image: 'ubuntu:24.04', tarball: kde-ubuntu-24.04 }
+          - { image: 'fedora:44', tarball: kde-fedora-44 }
+          - { image: 'archlinux:latest', tarball: kde-arch }
+    runs-on: ubuntu-24.04
+    container: ${{ matrix.image }}
+
+    steps:
+      - uses: actions/checkout@v7
+
+      - uses: actions/download-artifact@v8
+        with:
+          # the Ubuntu build's artifact has no distribution in its name
+          name: linux-wallpaperengine-${{ matrix.tarball == 'kde-ubuntu-24.04' && 'kde' || matrix.tarball }}
+          path: tarball
+
+      - uses: actions/download-artifact@v8
+        if: matrix.tarball == 'kde-arch'
+        with:
+          name: libnode-arch
+          path: libnode
+
+      - name: Smoke test
+        run: |
+          libnode=(libnode/libnode-[0-9]*.pkg.tar.zst)
+          [ -e "${libnode[0]}" ] && export LIBNODE_PKG="$PWD/${libnode[0]}"
+          tools/smoke_test_release.sh --install-deps tarball/*.tar.gz
+        shell: bash
+
   release:
-    needs: [build, distro-build]
+    needs: [build, distro-build, portable, smoke]
     if: startsWith(github.ref, 'refs/tags/')
     runs-on: ubuntu-latest
     permissions:
@@ -189,6 +332,31 @@ jobs:
             gh release create "$GITHUB_REF_NAME" --title "$GITHUB_REF_NAME" --generate-notes release/*.tar.gz
           fi
 
+  # the -bin package points at the release's portable tarball, so it is updated after the upload
+  aur:
+    needs: release
+    runs-on: ubuntu-latest
+    env:
+      HAS_AUR_KEY: ${{ secrets.AUR_SSH_PRIVATE_KEY != '' }}
+    steps:
+      - uses: actions/checkout@v7
+
+      - name: Set the version
+        run: sed -i -e "s/^pkgver=.*/pkgver=${GITHUB_REF_NAME#v}/" -e "s/^pkgrel=.*/pkgrel=1/"
+          packaging/aur/linux-wallpaperengine-kde-bin/PKGBUILD
+
+      - name: Publish linux-wallpaperengine-kde-bin to the AUR
+        if: env.HAS_AUR_KEY == 'true'
+        uses: KSXGitHub/github-actions-deploy-aur@v4.1.1
+        with:
+          pkgname: linux-wallpaperengine-kde-bin
+          pkgbuild: ./packaging/aur/linux-wallpaperengine-kde-bin/PKGBUILD
+          updpkgsums: true
+          commit_username: ${{ secrets.AUR_USERNAME }}
+          commit_email: ${{ secrets.AUR_EMAIL }}
+          ssh_private_key: ${{ secrets.AUR_SSH_PRIVATE_KEY }}
+          commit_message: Update to ${{ github.ref_name }}
+
   clang-build:
     needs: tests
     permissions:

+ 2 - 0
CMakeLists.txt

@@ -45,6 +45,8 @@ find_package(V8 10.2 REQUIRED)
 set(ENABLE_OPT OFF)
 set(SPIRV_CROSS_FORCE_PIC ON)
 set(CMAKE_POSITION_INDEPENDENT_CODE ON)
+# kissfft's old cmake_minimum_required would otherwise override the options below
+set(CMAKE_POLICY_DEFAULT_CMP0077 NEW)
 set(KISSFFT_TEST OFF)
 set(KISSFFT_TOOLS OFF)
 

+ 3 - 2
CMakeModules/FindV8.cmake

@@ -1,5 +1,6 @@
 # Finds V8 the way distributions ship it: inside Node.js's shared library (Fedora nodejs<N>-devel, Debian/Ubuntu
-# libnode-dev), headers under include/node. V8_INCLUDE_DIR / V8_LIBRARY can point anywhere else.
+# libnode-dev), headers under include/node (include/libnode on Arch's AUR libnode). V8_INCLUDE_DIR / V8_LIBRARY can
+# point anywhere else.
 #
 # This module defines:
 # V8_FOUND
@@ -33,7 +34,7 @@ find_path(
   V8_INCLUDE_DIR
   NAMES v8.h
   HINTS ${PC_NODE_INCLUDE_DIRS} ${_V8_PREFIX_HINTS}
-  PATH_SUFFIXES node nodejs/deps/v8/include v8
+  PATH_SUFFIXES libnode node nodejs/deps/v8/include v8
 )
 
 set(V8_DEFINITIONS)

+ 23 - 10
README.md

@@ -60,7 +60,7 @@ Control:
 - V8 10.2 or newer, as shipped in Node.js's shared library (`libnode`): scene scripts run on it like in Wallpaper Engine. CMake looks for `v8.h` under `include/node` and `libnode`; point `-DV8_INCLUDE_DIR`/`-DV8_LIBRARY` at another V8 build if yours lives elsewhere
 
 ### Ubuntu 22.04
-Its `libnode-dev` (Node.js 12) is too old for the scripting, install a newer Node.js `libnode` or use 24.04.
+Its `libnode-dev` (Node.js 12) is too old for the scripting and its FFmpeg 4.4 too old for the audio code, use the portable build (see Installing) or 24.04.
 ```bash
 sudo apt-get update
 sudo apt-get install build-essential cmake libxrandr-dev libxinerama-dev libxcursor-dev libxi-dev libgl-dev libglew-dev freeglut3-dev libsdl2-dev liblz4-dev libavcodec-dev libavformat-dev libavutil-dev libswscale-dev libxxf86vm-dev libglm-dev libglfw3-dev libmpv-dev mpv libmpv1 libpulse-dev libpulse0 libfftw3-dev libfreetype-dev libharfbuzz-dev libdbus-1-dev libwayland-dev wayland-protocols libegl1-mesa-dev
@@ -80,9 +80,9 @@ If you already have Node.js 22, use `nodejs22-devel` instead, Fedora's nodejs -d
 
 ### Arch Linux
 ```bash
-sudo pacman -S --needed git base-devel cmake pkg-config glew freeglut sdl2 lz4 ffmpeg glm glfw mpv libpulse fftw freetype2 harfbuzz dbus libxrandr libxinerama libxcursor libxi libxxf86vm wayland wayland-protocols mesa gmp
+sudo pacman -S --needed git base-devel cmake pkg-config glew freeglut sdl2 lz4 ffmpeg glm glfw mpv libpulse fftw freetype2 harfbuzz dbus libxrandr libxinerama libxcursor libxi libxxf86vm wayland wayland-protocols mesa gmp nss at-spi2-core libcups libxcomposite libxdamage libxkbcommon pango cairo alsa-lib libdrm libxshmfence
 ```
-Arch's `nodejs` package has the headers but no `libnode`, the AUR's `libnode` package (a Node.js built with `--shared`) provides it, e.g. `paru -S libnode`.
+The second half of that list is what the bundled CEF links against, a desktop install usually has it already. Arch's `nodejs` package has the headers but no `libnode`, the AUR's `libnode` package (a Node.js built with `--shared`) provides it, e.g. `paru -S libnode`.
 
 ### ALT Linux
 ```bash
@@ -90,16 +90,25 @@ sudo epm update
 sudo epm install gcc-c++ make cmake libXrandr-devel libXinerama-devel libXcursor-devel libXi-devel libGL-devel libGLEW-devel freeglut-devel libSDL2-devel liblz4-devel libavcodec-devel libavformat-devel libavutil-devel libswscale-devel libXxf86vm-devel libglm-devel libglfw3-devel libmpv-devel mpv libpulseaudio-devel libpulseaudio libfftw3-devel libpng-devel libffi-devel libswresample-devel libgmpxx-devel libfreetype-devel libharfbuzz-devel libdbus-devel
 ```
 
-## Prebuilt downloads
+## Installing
 
-Tagged releases on the [releases page](https://github.com/WallpaperEngineLover/linux-wallpaperengine-kde/releases) have ready-to-run builds for Ubuntu 24.04 and Fedora 44, each with (`kde`) and without (`generic`) the KDE Plasma integration. They use the distro's own ffmpeg, mpv, GLFW and so on, so pick the one for your distro and install the runtime packages from the list above (the non `-dev`/`-devel` ones). Arch users build from source for now.
+Tagged releases on the [releases page](https://github.com/WallpaperEngineLover/linux-wallpaperengine-kde/releases) have ready-to-run builds, each with (`kde`) and without (`generic`) the KDE Plasma integration:
+
+- **Portable** (`linux-wallpaperengine-kde-portable-x86_64.tar.gz`): runs on any x86_64 distribution with glibc 2.35 or newer (Ubuntu 22.04 and newer, Debian 12+, Fedora, openSUSE, Arch, SteamOS, Bazzite, Silverblue/Kinoite and other image-based systems) without installing anything: it carries FFmpeg, mpv, V8 and the rest, and only uses what every desktop has (Mesa, the display server's and audio server's libraries, the GTK stack CEF needs). A few libraries it brings are only used where the system has no library of that name (`lib/fallback`), the `linux-wallpaperengine` script in the folder takes care of that.
+- **Distribution builds** for Ubuntu 24.04, Fedora 44 and Arch Linux use the distribution's own FFmpeg, mpv and so on: install the runtime packages from the list above (the non `-dev`/`-devel` ones). The Arch build also needs the AUR's `libnode`.
 
 ```bash
-tar xzf linux-wallpaperengine-kde-fedora-44-x86_64.tar.gz
-./linux-wallpaperengine-kde-fedora-44-x86_64/linux-wallpaperengine --help
+tar xzf linux-wallpaperengine-kde-portable-x86_64.tar.gz
+./linux-wallpaperengine-kde-portable-x86_64/linux-wallpaperengine --help
 ```
 
-The folder can live anywhere, the binary finds its libraries next to itself.
+The folder can live anywhere. Web wallpapers run in Chromium's sandbox when the system allows unprivileged user namespaces or `chrome-sandbox` is setuid root (`sudo chown root:root chrome-sandbox && sudo chmod 4755 chrome-sandbox`), otherwise without it (Ubuntu 24.04+ restricts user namespaces, a tarball in the home folder can't have a setuid file).
+
+Other ways to get it:
+
+- **AUR**: `linux-wallpaperengine-kde-bin` (the portable build in `/opt`) or `linux-wallpaperengine-kde-git` (built from this repository, needs the AUR's `libnode`).
+- **Flatpak**: [WE Manager](https://github.com/WallpaperEngineLover/we_manager)'s Flatpak comes with the engine.
+- **Nix**: `nix run github:WallpaperEngineLover/linux-wallpaperengine-kde -- --help` builds it from source against nixpkgs (the first build also compiles Node.js as a shared library for V8) (`packages.x86_64-linux.generic` without the KDE integration, `overlays.default` adds `linux-wallpaperengine-kde`).
 
 ## Build
 
@@ -138,6 +147,10 @@ If it isn't found there, either copy the `assets` folder from Wallpaper Engine's
 linux-wallpaperengine --assets-dir /path/to/assets
 ```
 
+### Fonts
+
+Some wallpapers show emoji in their text layers and expect Windows' emoji font, Segoe UI Emoji (`seguiemj.ttf`). It is not part of this repo (it is Microsoft's font), but installing it makes those wallpapers look exactly like on Windows: copy `C:\Windows\Fonts\seguiemj.ttf` from a Windows install to `~/.local/share/fonts/` and run `fc-cache -f`. Without it the emoji come from the Twemoji font in Wallpaper Engine's assets. Wallpapers using `systemfont_*` text likewise look closest with the Windows fonts they name (Arial, Segoe UI, ...) or their metric-compatible clones installed.
+
 ## Usage
 
 ```bash
@@ -300,7 +313,7 @@ Platform and setup:
 - Some NVIDIA setups hit GLFW/OpenGL init failures; try `__GL_THREADED_OPTIMIZATIONS=0 linux-wallpaperengine` if you run into this.
 - Windows fonts (`systemfont_*`) are replaced by the closest installed match through fontconfig, so text can look slightly different if Arial, Segoe UI etc. or their metric-compatible clones aren't installed.
 - RGB lighting output (iCUE/Chroma `ledsource`) is ignored.
-- No Arch release builds for now (Arch has `libnode` only in the AUR), Arch users build from source.
+- Arch has `libnode` only in the AUR, so the Arch release build needs it installed from there.
 
 Puppets (2D animated characters):
 
@@ -315,7 +328,7 @@ Images, particles and text:
 
 - `layerimage` particle emitters read the layer right away, not from the GPU a frame later like Wallpaper Engine, and don't support text layers or opacity masks.
 - Particle `spritesheetrefreshsync`, `alphatocoverage` and rope `uvscrolling`/`uvsmoothing` are not supported.
-- Emoji from the bundled Twemoji font are drawn as their colour bitmap where Wallpaper Engine (without Windows' emoji font) draws nothing.
+- Without Segoe UI Emoji installed (see Fonts), emoji come from the Twemoji font in Wallpaper Engine's assets and are drawn as their colour bitmap; Wallpaper Engine itself draws nothing for them without that font.
 
 Sound:
 

+ 27 - 0
flake.lock

@@ -0,0 +1,27 @@
+{
+  "nodes": {
+    "nixpkgs": {
+      "locked": {
+        "lastModified": 1791456040,
+        "narHash": "sha256-H83yz/do+hjOO0uujHyH8RgtIQP2v7Mw+cLwcZK/xKc=",
+        "owner": "NixOS",
+        "repo": "nixpkgs",
+        "rev": "e7439b6b14ad3cc35d05608ebca9bce01a25f5f8",
+        "type": "github"
+      },
+      "original": {
+        "owner": "NixOS",
+        "ref": "nixos-unstable",
+        "repo": "nixpkgs",
+        "type": "github"
+      }
+    },
+    "root": {
+      "inputs": {
+        "nixpkgs": "nixpkgs"
+      }
+    }
+  },
+  "root": "root",
+  "version": 7
+}

+ 35 - 0
flake.nix

@@ -0,0 +1,35 @@
+{
+  description = "linux-wallpaperengine-kde, Wallpaper Engine live wallpapers on Linux";
+
+  inputs = {
+    self.submodules = true;
+    nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable";
+  };
+
+  outputs =
+    { self, nixpkgs }:
+    let
+      system = "x86_64-linux";
+      pkgs = nixpkgs.legacyPackages.${system};
+      version = "0-unstable-${self.lastModifiedDate or "19700101"}";
+      package =
+        disableKdeFeatures:
+        pkgs.callPackage ./nix/package.nix {
+          src = self;
+          inherit version disableKdeFeatures;
+        };
+    in
+    {
+      packages.${system} = {
+        default = package false;
+        generic = package true;
+      };
+
+      overlays.default = final: prev: {
+        linux-wallpaperengine-kde = final.callPackage ./nix/package.nix {
+          src = self;
+          inherit version;
+        };
+      };
+    };
+}

+ 183 - 0
nix/package.nix

@@ -0,0 +1,183 @@
+{
+  lib,
+  stdenv,
+  fetchurl,
+  cmake,
+  pkg-config,
+  python3,
+  autoPatchelfHook,
+  wayland-scanner,
+  binutils,
+  glm,
+  glfw,
+  glew,
+  freeglut,
+  libGLU,
+  libGL,
+  libglvnd,
+  SDL2,
+  lz4,
+  zlib,
+  ffmpeg,
+  mpv-unwrapped,
+  libpulseaudio,
+  freetype,
+  harfbuzz,
+  dbus,
+  wayland,
+  wayland-protocols,
+  libxkbcommon,
+  xorg,
+  gmp,
+  nodejs-slim_24,
+  nss,
+  nspr,
+  cups,
+  at-spi2-atk,
+  at-spi2-core,
+  libdrm,
+  mesa,
+  alsa-lib,
+  pango,
+  cairo,
+  glib,
+  expat,
+  libva,
+  vulkan-loader,
+  pipewire,
+  src,
+  version,
+  disableKdeFeatures ? false,
+}:
+
+let
+  # V8 comes from Node.js's shared library like on the distributions (Arch's AUR libnode is the same build).
+  # nixpkgs only has a static libv8, whose local-exec TLS can't go into our shared library
+  libnode = nodejs-slim_24.overrideAttrs (old: {
+    pname = "libnode";
+    configureFlags = (old.configureFlags or [ ]) ++ [ "--shared" ];
+    doCheck = false;
+    doInstallCheck = false;
+  });
+
+  # the version CMakeLists.txt pins, CMake's DownloadCEF finds the archive already in its folder
+  cefVersion = "135.0.17+gcbc1c5b+chromium-135.0.7049.52";
+  cefArchive = "cef_binary_${cefVersion}_linux64_minimal.tar.bz2";
+  cef = fetchurl {
+    url = "https://cef-builds.spotifycdn.com/${lib.replaceStrings [ "+" ] [ "%2B" ] cefArchive}";
+    hash = "sha256-JKwZgOYr57GuosM31r1Lx3DczYs35HxtuUs5fxPsTcY=";
+  };
+in
+stdenv.mkDerivation {
+  pname = "linux-wallpaperengine-kde";
+  inherit version src;
+
+  nativeBuildInputs = [
+    cmake
+    pkg-config
+    python3
+    autoPatchelfHook
+    wayland-scanner
+    binutils
+  ];
+
+  buildInputs = [
+    glm
+    glfw
+    glew
+    freeglut
+    libGLU
+    libGL
+    SDL2
+    lz4
+    zlib
+    ffmpeg
+    mpv-unwrapped
+    libpulseaudio
+    freetype
+    harfbuzz
+    dbus
+    wayland
+    wayland-protocols
+    libxkbcommon
+    gmp
+    libnode
+    # CEF's own libraries
+    nss
+    nspr
+    cups
+    at-spi2-atk
+    at-spi2-core
+    libdrm
+    mesa
+    alsa-lib
+    pango
+    cairo
+    glib
+    expat
+  ]
+  ++ (with xorg; [
+    libX11
+    libXrandr
+    libXinerama
+    libXcursor
+    libXi
+    libXxf86vm
+    libXcomposite
+    libXdamage
+    libXext
+    libXfixes
+    libxshmfence
+    libxcb
+  ]);
+
+  # loaded at runtime with dlopen (GL dispatch, Vulkan for CEF, VA-API, the audio backends SDL picks)
+  runtimeDependencies = map lib.getLib [
+    libglvnd
+    vulkan-loader
+    libva
+    libpulseaudio
+    pipewire
+    alsa-lib
+    wayland
+    libxkbcommon
+  ];
+
+  cmakeFlags = [
+    (lib.cmakeBool "DISABLE_KDE_FEATURES" disableKdeFeatures)
+    (lib.cmakeFeature "CMAKE_BUILD_TYPE" "Release")
+    (lib.cmakeFeature "V8_INCLUDE_DIR" "${libnode}/include/node")
+    # relative, package_release.sh installs into a prefix of its own
+    (lib.cmakeFeature "CMAKE_INSTALL_LIBDIR" "lib")
+  ];
+
+  # the CEF wrapper library builds with -Werror and defines its own _FORTIFY_SOURCE
+  hardeningDisable = [ "fortify" "fortify3" ];
+
+  preConfigure = ''
+    # node installs only the versioned libnode.so.<abi>
+    cmakeFlagsArray+=("-DV8_LIBRARY=$(echo ${libnode}/lib/libnode.so.*)")
+    mkdir -p build/cef
+    ln -s ${cef} build/cef/${cefArchive}
+  '';
+
+  # the same file set as the release tarballs, the install tree also carries the vendored libraries' tools
+  installPhase = ''
+    runHook preInstall
+    bash ../tools/package_release.sh . linux-wallpaperengine-kde "$TMPDIR/dist"
+    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
+    runHook postInstall
+  '';
+
+  dontStrip = true;
+
+  meta = {
+    description = "Wallpaper Engine live wallpapers on Linux, KDE/Wayland fork of linux-wallpaperengine";
+    homepage = "https://github.com/WallpaperEngineLover/linux-wallpaperengine-kde";
+    license = lib.licenses.gpl3Only;
+    platforms = [ "x86_64-linux" ];
+    mainProgram = "linux-wallpaperengine";
+  };
+}

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

@@ -0,0 +1,30 @@
+# Maintainer: UwU <260361707+WallpaperEngineLover@users.noreply.github.com>
+# pkgver and the checksum are set by .github/workflows/aur.yml on every release
+pkgname=linux-wallpaperengine-kde-bin
+_pkgname=linux-wallpaperengine-kde
+pkgver=0.8.0
+pkgrel=1
+pkgdesc="Wallpaper Engine live wallpapers on Linux, KDE/Wayland fork of linux-wallpaperengine (portable release build)"
+arch=('x86_64')
+url="https://github.com/WallpaperEngineLover/linux-wallpaperengine-kde"
+license=('GPL-3.0-only')
+# what the portable build leaves to the system (lib/SYSTEM_LIBS), everything else is bundled, V8 included
+depends=('glibc' 'gcc-libs' 'zlib' 'dbus' 'systemd-libs' 'libglvnd' 'mesa' 'libdrm' 'libva' 'vulkan-icd-loader'
+    'wayland' 'libx11' 'libxcb' 'libxext' 'libxrender' 'libxfixes' 'libxrandr' 'libxi' 'libxcursor' 'libxinerama'
+    'libxdamage' 'libxcomposite' 'libxxf86vm' 'libxkbcommon' 'libxshmfence' 'alsa-lib' 'libpipewire' 'nss' 'nspr'
+    'libcups' 'at-spi2-core' 'pango' 'cairo' 'gdk-pixbuf2' 'glib2')
+provides=('linux-wallpaperengine')
+conflicts=('linux-wallpaperengine' 'linux-wallpaperengine-git' 'linux-wallpaperengine-kde-git')
+options=('!strip' '!debug')
+source=("$_pkgname-$pkgver.tar.gz::$url/releases/download/v$pkgver/linux-wallpaperengine-kde-portable-x86_64.tar.gz")
+sha256sums=('SKIP')
+
+package() {
+    install -d "$pkgdir/opt"
+    cp -a linux-wallpaperengine-kde-portable-x86_64 "$pkgdir/opt/$_pkgname"
+    # without user namespaces Chromium falls back to the setuid sandbox
+    chmod 4755 "$pkgdir/opt/$_pkgname/chrome-sandbox"
+
+    install -d "$pkgdir/usr/bin"
+    ln -s "/opt/$_pkgname/linux-wallpaperengine" "$pkgdir/usr/bin/linux-wallpaperengine"
+}

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

@@ -0,0 +1,57 @@
+# Maintainer: UwU <260361707+WallpaperEngineLover@users.noreply.github.com>
+pkgname=linux-wallpaperengine-kde-git
+_pkgname=linux-wallpaperengine-kde
+pkgver=r0
+pkgrel=1
+pkgdesc="Wallpaper Engine live wallpapers on Linux, KDE/Wayland fork of linux-wallpaperengine (built from git)"
+arch=('x86_64')
+url="https://github.com/WallpaperEngineLover/linux-wallpaperengine-kde"
+license=('GPL-3.0-only')
+# libnode (V8 for scene scripts) is in the AUR
+depends=('libnode' 'mpv' 'ffmpeg' 'glew' 'glfw' 'sdl2' 'freeglut' 'glu' 'fftw' 'lz4' 'freetype2' 'harfbuzz' 'gmp'
+    'dbus' 'wayland' 'libpulse' 'libglvnd' 'libx11' 'libxrandr' 'libxinerama' 'libxcursor' 'libxi' 'libxxf86vm'
+    'nss' 'at-spi2-core' 'libcups' 'libxcomposite' 'libxdamage' 'libxkbcommon' 'pango' 'cairo' 'alsa-lib' 'libdrm'
+    'mesa' 'libxshmfence')
+makedepends=('git' 'cmake' 'glm' 'wayland-protocols' 'python')
+provides=('linux-wallpaperengine')
+conflicts=('linux-wallpaperengine' 'linux-wallpaperengine-git' 'linux-wallpaperengine-kde-bin')
+# CEF ships its own stripped libraries, stripping them again only costs time
+options=('!strip' '!debug' '!lto')
+source=("$_pkgname::git+$url.git")
+sha256sums=('SKIP')
+
+pkgver() {
+    cd "$_pkgname"
+    printf "r%s.%s" "$(git rev-list --count HEAD)" "$(git rev-parse --short HEAD)"
+}
+
+prepare() {
+    cd "$_pkgname"
+    git submodule update --init --recursive
+}
+
+build() {
+    # CEF's wrapper library defines its own _FORTIFY_SOURCE and builds with -Werror
+    CFLAGS="${CFLAGS//-Wp,-D_FORTIFY_SOURCE=?/}"
+    CXXFLAGS="${CXXFLAGS//-Wp,-D_FORTIFY_SOURCE=?/}"
+    export CFLAGS CXXFLAGS
+    # CMake downloads the CEF version the checkout pins
+    cmake -B build -S "$_pkgname" \
+        -DCMAKE_BUILD_TYPE=Release \
+        -DCMAKE_INSTALL_PREFIX="/opt/$_pkgname" \
+        -Wno-dev
+    cmake --build build
+}
+
+package() {
+    # the same files as the release tarballs
+    "$_pkgname/tools/package_release.sh" build "$_pkgname" "$srcdir/dist"
+    install -d "$pkgdir/opt"
+    tar -xzf "$srcdir/dist/$_pkgname.tar.gz" -C "$pkgdir/opt"
+    # without user namespaces Chromium falls back to the setuid sandbox
+    chmod 4755 "$pkgdir/opt/$_pkgname/chrome-sandbox"
+
+    install -d "$pkgdir/usr/bin"
+    ln -s "/opt/$_pkgname/linux-wallpaperengine" "$pkgdir/usr/bin/linux-wallpaperengine"
+    install -Dm644 "$_pkgname/LICENSE" "$pkgdir/usr/share/licenses/$pkgname/LICENSE"
+}

+ 1 - 22
src/WallpaperEngine/Assets/AssetLocator.cpp

@@ -7,29 +7,8 @@ using namespace WallpaperEngine::Assets;
 AssetLocator::AssetLocator (ContainerUniquePtr filesystem) : m_filesystem (std::move (filesystem)) { }
 
 std::string AssetLocator::shader (const std::filesystem::path& filename) const {
+    // assets/zcompat shader replacements are mobile-only (wallpaperui.exe), wallpaper64.exe never reads them
     try {
-	std::filesystem::path shader = filename;
-
-	// workshop shaders may have a zcompat replacement under zcompat/scene/shaders/<id>/<file>
-	if (auto it = shader.begin (); *it++ == "workshop") {
-	    const std::filesystem::path workshopId = *it++;
-
-	    if (++it != shader.end ()) {
-		const std::filesystem::path& shaderfile = *it;
-
-		try {
-		    shader = std::filesystem::path ("zcompat") / "scene" / "shaders" / workshopId / shaderfile;
-		    std::string contents = this->m_filesystem->readString (shader);
-
-		    sLog.out ("Replaced ", filename, " with compat ", shader);
-
-		    return contents;
-		} catch (std::filesystem::filesystem_error&) {
-		    // these exceptions can be ignored because the replacement file might not exist
-		}
-	    }
-	}
-
 	return this->m_filesystem->readString ("shaders" / filename);
     } catch (std::filesystem::filesystem_error& base) {
 	throw AssetLoadException (base);

+ 98 - 77
src/WallpaperEngine/Audio/AudioStream.cpp

@@ -31,13 +31,12 @@ int audio_read_thread (void* arg) {
 	ret = av_read_frame (stream->getFormatContext (), packet);
 
 	if (ret == AVERROR_EOF) {
-	    // a one-shot stream is done, rewinding/flushing would only race the decoder still draining the queue
 	    if (!stream->isRepeat ()) {
 		break;
 	    }
 
 	    avformat_seek_file (stream->getFormatContext (), stream->getAudioStream (), 0, 0, 0, ~AVSEEK_FLAG_FRAME);
-	    stream->flushCodec ();
+	    stream->queueLoopMarker ();
 	    ret = 0;
 
 	    continue;
@@ -165,10 +164,6 @@ AudioStream::~AudioStream () {
 
     delete this->m_queue;
 
-    if (this->m_codecMutex != nullptr) {
-	SDL_DestroyMutex (this->m_codecMutex);
-    }
-
     if (this->m_formatContext != nullptr) {
 	avformat_free_context (this->m_formatContext);
     }
@@ -289,8 +284,6 @@ void AudioStream::initialize () {
 	sLog.exception ("Failed to initialize the resampling context.");
     }
 
-    this->m_codecMutex = SDL_CreateMutex ();
-
     this->m_queue->mutex = SDL_CreateMutex ();
     this->m_queue->cond = SDL_CreateCond ();
     this->m_queue->wait = SDL_CreateCond ();
@@ -353,10 +346,23 @@ bool AudioStream::doQueue (AVPacket* pkt) {
     return true;
 }
 
-void AudioStream::flushCodec () {
-    SDL_LockMutex (this->m_codecMutex);
-    avcodec_flush_buffers (this->m_context);
-    SDL_UnlockMutex (this->m_codecMutex);
+void AudioStream::queueLoopMarker () {
+    AVPacket* marker = av_packet_alloc ();
+
+    if (marker == nullptr) {
+	return;
+    }
+
+    // empty packet, recognised by its stream index
+    marker->stream_index = NO_AUDIO_STREAM;
+
+    SDL_LockMutex (this->m_queue->mutex);
+    const bool gotQueued = this->doQueue (marker);
+    SDL_UnlockMutex (this->m_queue->mutex);
+
+    if (!gotQueued) {
+	av_packet_free (&marker);
+    }
 }
 
 void AudioStream::markReaderFinished () {
@@ -367,45 +373,40 @@ void AudioStream::markReaderFinished () {
     SDL_UnlockMutex (this->m_queue->mutex);
 }
 
-bool AudioStream::dequeuePacket () {
+AudioStream::Dequeued AudioStream::dequeuePacket () {
     MyAVPacketList entry {};
-    bool gotPacket = false;
+    // read before the queue, the reader sets it after queueing its last packet
+    const bool finished = this->m_readerFinished || !this->m_initialized;
 
     SDL_LockMutex (this->m_queue->mutex);
 
-    while (this->m_audioContext.getApplicationContext ().state.general.keepRunning) {
 #if FF_API_FIFO_OLD_API
-	int ret = -1;
+    int ret = -1;
 
-	if (av_fifo_size (this->m_queue->packetList) >= static_cast<int> (sizeof (entry))) {
-	    ret = av_fifo_generic_read (this->m_queue->packetList, &entry, sizeof (entry), nullptr);
-	}
+    if (av_fifo_size (this->m_queue->packetList) >= static_cast<int> (sizeof (entry))) {
+	ret = av_fifo_generic_read (this->m_queue->packetList, &entry, sizeof (entry), nullptr);
+    }
 #else
-	const int ret = av_fifo_read (this->m_queue->packetList, &entry, 1);
+    const int ret = av_fifo_read (this->m_queue->packetList, &entry, 1);
 #endif
 
-	if (ret >= 0) {
-	    this->m_queue->nb_packets--;
-	    this->m_queue->size -= entry.packet->size + sizeof (entry);
-	    this->m_queue->duration -= entry.packet->duration;
-
-	    av_packet_move_ref (this->m_decodePacket, entry.packet);
-	    av_packet_free (&entry.packet);
-	    gotPacket = true;
-	    break;
-	}
+    if (ret >= 0) {
+	this->m_queue->nb_packets--;
+	this->m_queue->size -= entry.packet->size + sizeof (entry);
+	this->m_queue->duration -= entry.packet->duration;
+    }
 
-	// the reader is gone and the queue is drained, nobody will ever signal us again
-	if (this->m_readerFinished || !this->m_initialized) {
-	    break;
-	}
+    SDL_UnlockMutex (this->m_queue->mutex);
 
-	SDL_CondWaitTimeout (this->m_queue->cond, this->m_queue->mutex, 20);
+    if (ret < 0) {
+	return finished ? Dequeued::Finished : Dequeued::Empty;
     }
 
-    SDL_UnlockMutex (this->m_queue->mutex);
+    av_packet_unref (this->m_decodePacket);
+    av_packet_move_ref (this->m_decodePacket, entry.packet);
+    av_packet_free (&entry.packet);
 
-    return gotPacket;
+    return Dequeued::Packet;
 }
 
 AVCodecContext* AudioStream::getContext () const { return this->m_context; }
@@ -464,8 +465,6 @@ AVRational AudioStream::getTimeBase () const {
 
 int64_t AudioStream::getQueueDuration () const { return this->m_queue->duration; }
 
-bool AudioStream::isQueueEmpty () const { return this->m_queue->nb_packets == 0; }
-
 SDL_mutex* AudioStream::getMutex () const { return this->m_queue->mutex; }
 
 void AudioStream::stop () {
@@ -586,62 +585,84 @@ int AudioStream::resampleAudio (uint8_t* out_buf, const int out_size) {
     return resampled_data_size;
 }
 
+int AudioStream::flushResampler (uint8_t* out_buf, const int out_size) {
+    const int channels = this->m_audioContext.getChannels ();
+    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;
+    }
+
+    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;
+
+    if (size > 0) {
+	memcpy (out_buf, data, std::min (size, out_size));
+    }
+
+    av_freep (&data);
+
+    return size > 0 ? std::min (size, out_size) : -1;
+}
+
 int AudioStream::decodeFrame (uint8_t* audioBuffer, const int bufferSize) {
-    // block until there's any data in the buffers
+    // runs on the audio callback, so it never waits
     while (this->m_audioContext.getApplicationContext ().state.general.keepRunning) {
-	while (this->m_audioPacketSize > 0 && this->m_audioContext.getApplicationContext ().state.general.keepRunning) {
-	    int got_frame = 0;
+	const int ret = avcodec_receive_frame (this->getContext (), this->m_decodeFrame);
 
-	    SDL_LockMutex (this->m_codecMutex);
-	    int ret = avcodec_receive_frame (this->getContext (), this->m_decodeFrame);
+	if (ret == 0) {
+	    const int size = this->resampleAudio (audioBuffer, bufferSize);
 
-	    if (ret == 0) {
-		got_frame = 1;
-	    }
-	    if (ret == AVERROR (EAGAIN)) {
-		ret = 0;
+	    if (size > 0) {
+		return size;
 	    }
-	    if (ret == 0) {
-		ret = avcodec_send_packet (this->getContext (), this->m_decodePacket);
-	    }
-	    SDL_UnlockMutex (this->m_codecMutex);
 
-	    if (ret < 0 && ret != AVERROR (EAGAIN)) {
-		return -1;
-	    }
+	    continue;
+	}
 
-	    if (this->m_decodePacket->size < 0) {
-		// if error, skip frame
-		this->m_audioPacketSize = 0;
-		break;
+	if (ret == AVERROR_EOF) {
+	    if (this->m_loopDrain) {
+		avcodec_flush_buffers (this->getContext ());
+		this->m_loopDrain = false;
+		continue;
 	    }
 
-	    this->m_audioPacketSize -= this->m_decodePacket->size;
-	    int data_size = 0;
+	    return this->flushResampler (audioBuffer, bufferSize);
+	}
 
-	    if (got_frame) {
-		data_size = this->resampleAudio (audioBuffer, bufferSize);
-	    }
-	    if (data_size <= 0) {
-		// no data found, keep waiting
-		continue;
-	    }
-	    return data_size;
+	if (ret != AVERROR (EAGAIN)) {
+	    return -1;
 	}
 
-	if (this->m_decodePacket->data) {
-	    av_packet_unref (this->m_decodePacket);
+	switch (this->dequeuePacket ()) {
+	    case Dequeued::Empty:
+		return 0;
+	    case Dequeued::Finished:
+		avcodec_send_packet (this->getContext (), nullptr);
+		continue;
+	    case Dequeued::Packet:
+		break;
 	}
 
-	if (!this->dequeuePacket ()) {
-	    this->m_audioPacketSize = 0;
-	    return -1;
+	if (this->m_decodePacket->stream_index == NO_AUDIO_STREAM) {
+	    avcodec_send_packet (this->getContext (), nullptr);
+	    this->m_loopDrain = true;
+	    continue;
 	}
 
-	this->m_audioPacketSize = this->m_decodePacket->size;
+	avcodec_send_packet (this->getContext (), this->m_decodePacket);
+	av_packet_unref (this->m_decodePacket);
     }
 
-    return 0;
+    return -1;
 }
 
 AudioContext& AudioStream::getAudioContext () const { return this->m_audioContext; }

+ 13 - 18
src/WallpaperEngine/Audio/AudioStream.h

@@ -46,26 +46,24 @@ public:
 
     void queuePacket (AVPacket* pkt);
 
+    enum class Dequeued { Packet, Empty, Finished };
+
     /**
-     * Gets the next packet in the queue
-     *
-     * WARNING: BLOCKS UNTIL SOME DATA IS READ FROM IT, unless the file reader is done (a non-repeating
-     * stream that reached its end) or the stream was stopped
+     * Takes the next packet off the queue into m_decodePacket without waiting
      *
-     * @return true if a packet was fetched, false if there is nothing left to play
+     * @return Empty when the reader hasn't queued more yet, Finished once it never will
      */
-    bool dequeuePacket ();
+    Dequeued dequeuePacket ();
 
     /**
-     * Called by the file reader thread when it will not queue any more packets
+     * Called by the file reader thread when a repeating stream starts over, the decoder drains up to the marker
      */
-    void markReaderFinished ();
+    void queueLoopMarker ();
 
     /**
-     * Flushes the decoder's internal state (called by the reader thread when a repeating stream loops).
-     * Locks against decodeFrame() so the reset can't land mid-decode on another thread.
+     * Called by the file reader thread when it will not queue any more packets
      */
-    void flushCodec ();
+    void markReaderFinished ();
 
     [[nodiscard]] AudioContext& getAudioContext () const;
 
@@ -96,14 +94,13 @@ public:
      */
     [[nodiscard]] int64_t getQueueDuration () const;
     [[nodiscard]] AVRational getTimeBase () const;
-    [[nodiscard]] bool isQueueEmpty () const;
     [[nodiscard]] SDL_mutex* getMutex () const;
 
     /**
      * Reads a frame from the audio stream, resamples it to the driver's settings
      * and returns the data ready to be played
      *
-     * @return The amount of bytes available or < 0 for error
+     * @return The amount of bytes available, 0 when nothing is decoded yet or < 0 at the end or on error
      */
     int decodeFrame (uint8_t* audioBuffer, int bufferSize);
 
@@ -116,6 +113,8 @@ private:
      * Converts the audio frame from the original format to one supported by the audio driver
      */
     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);
     bool doQueue (AVPacket* pkt);
     /**
      * Initializes queues and ffmpeg resampling
@@ -140,11 +139,7 @@ private:
 
     AVPacket* m_decodePacket = nullptr;
     AVFrame* m_decodeFrame = nullptr;
-    /** Bytes left to decode from m_decodePacket, carried between decodeFrame() calls */
-    int m_audioPacketSize = 0;
-    /** Guards m_context: avcodec_flush_buffers() on the reader thread races send/receive on the decode thread otherwise
-     */
-    SDL_mutex* m_codecMutex = nullptr;
+    bool m_loopDrain = false;
 
     struct PacketQueue {
 #if FF_API_FIFO_OLD_API

+ 11 - 13
src/WallpaperEngine/Audio/Drivers/SDLAudioDriver.cpp

@@ -1,7 +1,8 @@
 #include "SDLAudioDriver.h"
 #include "WallpaperEngine/Logging/Log.h"
 
-#define SDL_AUDIO_BUFFER_SIZE 4096
+// a sound starts at the next callback, so keep it short (WE's OpenAL Soft updates every 20 ms)
+#define SDL_AUDIO_BUFFER_SIZE 1024
 #define MAX_AUDIO_FRAME_SIZE 192000
 
 using namespace WallpaperEngine::Audio;
@@ -69,23 +70,20 @@ void audio_callback (void* userdata, uint8_t* streamData, int length) {
 	    continue;
 	}
 
-	if (buffer->stream->isQueueEmpty ()) {
-	    SDL_CondSignal (buffer->stream->getWaitCondition ());
-	    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 (audio_size < 0) {
-		    // fallback for errors, silence
-		    buffer->audio_buf_size = 1024;
-		    memset (buffer->audio_buf, 0, buffer->audio_buf_size);
-		} else {
-		    buffer->audio_buf_size = audio_size;
+		// 0: nothing decoded yet, wake the reader
+		if (audio_size <= 0) {
+		    if (audio_size == 0) {
+			SDL_CondSignal (buffer->stream->getWaitCondition ());
+		    }
+
+		    break;
 		}
 
+		buffer->audio_buf_size = audio_size;
 		buffer->audio_buf_index = 0;
 	    }
 
@@ -189,7 +187,7 @@ int SDLAudioDriver::addStream (AudioStream* stream, int volume, float left, floa
 }
 void SDLAudioDriver::removeStream (int streamId) {
     // must hold the same lock the SDL audio callback thread holds while it iterates m_streams and
-    // calls into each stream (decodeFrame, isQueueEmpty, ...) - without it, erasing here can race
+    // calls into each stream (decodeFrame, ...) - without it, erasing here can race
     // the callback's map iteration (heap corruption) and the caller may go on to delete the
     // AudioStream while the callback thread is still using it
     SDL_LockMutex (this->m_streamListMutex);

+ 5 - 25
src/WallpaperEngine/Data/Parsers/MaterialParser.cpp

@@ -26,38 +26,18 @@ MaterialUniquePtr MaterialParser::load (const Project& project, const std::strin
 
 MaterialUniquePtr MaterialParser::parse (const JSON& it, const std::string& filename, const Project& project) {
     const auto passes = it.find ("passes");
+    // WE only reads the first entry of "passes", without one the material's root is the pass
+    const bool hasPasses = passes != it.end () && passes->is_array () && !passes->empty ();
 
-    // without a non-empty "passes" array WE reads the material's root as its pass
-    if (passes == it.end () || !passes->is_array () || passes->empty ()) {
-	std::vector<MaterialPassUniquePtr> single;
-	single.push_back (parsePass (it, project));
-
-	return std::make_unique<Material> (Material {
-	    .filename = filename,
-	    .passes = std::move (single),
-	});
-    }
+    std::vector<MaterialPassUniquePtr> result;
+    result.push_back (parsePass (hasPasses ? passes->front () : it, project));
 
     return std::make_unique<Material> (Material {
 	.filename = filename,
-	.passes = parsePasses (*passes, project),
+	.passes = std::move (result),
     });
 }
 
-std::vector<MaterialPassUniquePtr> MaterialParser::parsePasses (const JSON& it, const Project& project) {
-    std::vector<MaterialPassUniquePtr> result = {};
-
-    if (!it.is_array ()) {
-	return result;
-    }
-
-    for (const auto& cur : it) {
-	result.push_back (parsePass (cur, project));
-    }
-
-    return result;
-}
-
 MaterialPassUniquePtr MaterialParser::parsePass (const JSON& it, const Project& project) {
     const auto textures = it.optional ("textures");
     const auto usertextures = it.optional ("usertextures");

+ 0 - 1
src/WallpaperEngine/Data/Parsers/MaterialParser.h

@@ -12,7 +12,6 @@ class MaterialParser {
 public:
     static MaterialUniquePtr load (const Project& project, const std::string& filename);
     static MaterialUniquePtr parse (const JSON& it, const std::string& filename, const Project& project);
-    static std::vector<MaterialPassUniquePtr> parsePasses (const JSON& it, const Project& project);
     static MaterialPassUniquePtr parsePass (const JSON& it, const Project& project);
     static std::map<std::string, int> parseCombos (const JSON& it);
     static BlendingMode parseBlendMode (const std::string& mode);

+ 14 - 1
src/WallpaperEngine/Desktop/UserShortcut.cpp

@@ -249,11 +249,24 @@ bool isExecutableFile (const std::string& path) {
  * needs is prepared before fork() since the engine is multithreaded. The engine's own library path and preloads
  * would break other programs, so they are left out of the environment.
  */
-bool spawnDetached (const std::vector<std::string>& arguments, const std::string& workingDirectory = "") {
+bool spawnDetached (std::vector<std::string> arguments, const std::string& workingDirectory = "") {
     if (arguments.empty ()) {
 	return false;
     }
 
+    // inside a Flatpak only xdg-open reaches the host by itself
+    static const bool insideFlatpak = access ("/.flatpak-info", F_OK) == 0;
+
+    if (insideFlatpak && arguments.front () != "xdg-open") {
+	std::vector<std::string> host = { "flatpak-spawn", "--host" };
+
+	if (!workingDirectory.empty ()) {
+	    host.push_back ("--directory=" + workingDirectory);
+	}
+
+	arguments.insert (arguments.begin (), host.begin (), host.end ());
+    }
+
     std::vector<char*> argv;
     for (const auto& argument : arguments) {
 	argv.push_back (const_cast<char*> (argument.c_str ()));

+ 7 - 1
src/WallpaperEngine/Input/Drivers/KDECursorInput.cpp

@@ -109,7 +109,13 @@ bool KDECursorInput::loadKWinScript () {
 	   << "workspace.cursorPosChanged.connect(lweReportCursorPos);\n"
 	   << "lweReportCursorPos();\n";
 
-    m_scriptPath = std::string (runtimeDir) + "/linux-wallpaperengine-cursor-" + std::to_string (getpid ()) + ".js";
+    // inside a Flatpak only the app's own runtime folder is shared with the host
+    std::string scriptDir = runtimeDir;
+    if (const char* flatpakId = std::getenv ("FLATPAK_ID"); flatpakId != nullptr) {
+	scriptDir += std::string ("/app/") + flatpakId;
+    }
+
+    m_scriptPath = scriptDir + "/linux-wallpaperengine-cursor-" + std::to_string (getpid ()) + ".js";
 
     std::ofstream out (m_scriptPath, std::ios::trunc);
     if (!out.is_open ()) {

+ 61 - 0
src/WallpaperEngine/WebBrowser/WebBrowserContext.cpp

@@ -5,10 +5,16 @@
 #include "WallpaperEngine/WebBrowser/CEF/SubprocessApp.h"
 #include "include/cef_app.h"
 #include "include/cef_render_handler.h"
+#include <cerrno>
+#include <cstdio>
 #include <cstdlib>
+#include <fcntl.h>
 #include <filesystem>
 #include <random>
+#include <sched.h>
 #include <string_view>
+#include <sys/stat.h>
+#include <sys/wait.h>
 #include <unistd.h>
 
 using namespace WallpaperEngine::WebBrowser;
@@ -71,6 +77,55 @@ std::filesystem::path subprocessHelper () {
 
     return helper;
 }
+
+bool writeFile (const char* path, const char* text, size_t length) {
+    const int fd = open (path, O_WRONLY);
+
+    if (fd < 0) {
+	return false;
+    }
+
+    const bool written = write (fd, text, length) == static_cast<ssize_t> (length);
+    close (fd);
+    return written;
+}
+
+// Ubuntu 24.04+ allows the unshare but AppArmor drops its capabilities, so the uid map write is what fails
+bool userNamespacesWork () {
+    char uidMap[64];
+    const int uidMapLength = snprintf (uidMap, sizeof (uidMap), "0 %u 1\n", getuid ());
+    const pid_t child = fork ();
+
+    if (child < 0) {
+	return false;
+    }
+
+    if (child == 0) {
+	const bool mapped = unshare (CLONE_NEWUSER) == 0 && writeFile ("/proc/self/setgroups", "deny", 4)
+	    && writeFile ("/proc/self/uid_map", uidMap, uidMapLength);
+	_exit (mapped ? 0 : 1);
+    }
+
+    int status = 0;
+
+    while (waitpid (child, &status, 0) < 0 && errno == EINTR) { }
+
+    return WIFEXITED (status) && WEXITSTATUS (status) == 0;
+}
+
+// Chromium aborts without a user namespace or a setuid root chrome-sandbox next to libcef
+bool chromiumSandboxUsable () {
+    std::error_code error;
+    const auto self = std::filesystem::read_symlink ("/proc/self/exe", error);
+    struct stat sandbox {};
+
+    if (!error && stat ((self.parent_path () / "chrome-sandbox").c_str (), &sandbox) == 0 && sandbox.st_uid == 0
+	&& (sandbox.st_mode & S_ISUID) != 0) {
+	return true;
+    }
+
+    return userNamespacesWork ();
+}
 } // namespace
 
 int WebBrowserContext::runSubprocess (int argc, char* argv[]) {
@@ -112,6 +167,12 @@ WebBrowserContext::WebBrowserContext (WallpaperEngine::Application::WallpaperApp
     if (const char* noSandbox = std::getenv ("LWE_CEF_NO_SANDBOX"); noSandbox != nullptr && noSandbox[0] == '1') {
 	sLog.error ("LWE_CEF_NO_SANDBOX is set, web content runs without Chromium's sandbox");
 	settings.no_sandbox = true;
+    } else if (!settings.no_sandbox && !chromiumSandboxUsable ()) {
+	sLog.error (
+	    "No user namespaces and no setuid root chrome-sandbox, web content runs without Chromium's sandbox. "
+	    "Distribution packages set it up, or as root: chown root:root chrome-sandbox; chmod 4755 chrome-sandbox"
+	);
+	settings.no_sandbox = true;
     }
 
     if (!CefInitialize (main_args, settings, this->m_browserApplication, nullptr)) {

+ 81 - 0
tools/distro_rootfs.sh

@@ -0,0 +1,81 @@
+#!/usr/bin/env bash
+# Distribution userlands without docker or root: pulls an image's layers from a registry and runs commands in it
+# under proot. Used to build the portable release on an old glibc and to smoke test tarballs locally.
+#
+# Usage:
+#   tools/distro_rootfs.sh fetch <image[:tag]> <dir>     e.g. debian:12, fedora:44, opensuse/tumbleweed, ghcr.io/...
+#   tools/distro_rootfs.sh run <dir> [-u] <cmd...>       -u runs as uid 1000 instead of fake root
+#
+# PROOT points at the proot binary (default: proot from PATH, a static build works best), BINDS adds "-b src:dst" pairs.
+# Whiteout files of later layers are applied, other OCI features (hardlinks across layers etc.) are not.
+set -euo pipefail
+
+PROOT="${PROOT:-proot}"
+
+fetch() {
+    local image="$1" dir="$2" repo tag token manifest digest registry=registry-1.docker.io
+    repo="${image%%:*}"
+    tag="${image#*:}"
+    [ "$tag" = "$image" ] && tag=latest
+    if [[ "$repo" == ghcr.io/* ]]; then
+        registry=ghcr.io
+        repo="${repo#ghcr.io/}"
+        token=$(curl -fsSL "https://ghcr.io/token?scope=repository:$repo:pull" | jq -r .token)
+    else
+        [[ "$repo" == */* ]] || repo="library/$repo"
+        token=$(curl -fsSL "https://auth.docker.io/token?service=registry.docker.io&scope=repository:$repo:pull" |
+            jq -r .token)
+    fi
+    local accept="application/vnd.oci.image.index.v1+json,application/vnd.docker.distribution.manifest.list.v2+json"
+    accept+=",application/vnd.oci.image.manifest.v1+json,application/vnd.docker.distribution.manifest.v2+json"
+    manifest=$(curl -fsSL -H "Authorization: Bearer $token" -H "Accept: $accept" \
+        "https://$registry/v2/$repo/manifests/$tag")
+    if jq -e '.manifests' <<<"$manifest" >/dev/null; then
+        digest=$(jq -r '[.manifests[] | select(.platform.architecture == "amd64" and .platform.os == "linux")][0].digest' <<<"$manifest")
+        manifest=$(curl -fsSL -H "Authorization: Bearer $token" -H "Accept: $accept" \
+            "https://$registry/v2/$repo/manifests/$digest")
+    fi
+
+    mkdir -p "$dir"
+    local layer
+    for layer in $(jq -r '.layers[].digest' <<<"$manifest"); do
+        echo "layer $layer" >&2
+        curl -fsSL -H "Authorization: Bearer $token" "https://$registry/v2/$repo/blobs/$layer" -o "$dir/.layer"
+        # whiteouts: .wh.name deletes name from the lower layers, .wh..wh..opq empties the directory
+        local wh
+        while IFS= read -r wh; do
+            local base="${wh##*/}" parent
+            parent="$(dirname "$wh")"
+            if [ "$base" = ".wh..wh..opq" ]; then
+                find "$dir/$parent" -mindepth 1 -delete 2>/dev/null || true
+            else
+                rm -rf "${dir:?}/$parent/${base#.wh.}"
+            fi
+        done < <(tar -tf "$dir/.layer" 2>/dev/null | grep '\.wh\.' || true)
+        tar -xf "$dir/.layer" -C "$dir" --exclude='*.wh.*' --no-same-owner 2>/dev/null || true
+        rm -f "$dir/.layer"
+    done
+    chmod -R u+w "$dir"
+    cp /etc/resolv.conf "$dir/etc/resolv.conf" 2>/dev/null || true
+    echo "$image" >"$dir/.image"
+}
+
+run() {
+    local dir="$1" user=(-0) home=/root
+    shift
+    if [ "${1:-}" = -u ]; then
+        user=(-i 1000:1000)
+        home=/tmp
+        shift
+    fi
+    # shellcheck disable=SC2086
+    exec "$PROOT" "${user[@]}" -r "$dir" -b /dev -b /proc -b /sys -b /etc/resolv.conf ${BINDS:-} -w / \
+        /usr/bin/env -i HOME="$home" PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \
+        TERM=xterm LANG=C.UTF-8 "$@"
+}
+
+case "${1:-}" in
+    fetch) fetch "$2" "$3" ;;
+    run) shift; run "$@" ;;
+    *) sed -n '2,12p' "$0"; exit 1 ;;
+esac

+ 74 - 0
tools/glibc_compat/lwe_glibc_compat.c

@@ -0,0 +1,74 @@
+// Functions that bundled libraries of the portable release call but older systems don't have.
+//
+// glibc: libraries retargeted by retarget_glibc_versions.py can't bind to libc's own copy and resolve to this
+// unversioned one instead (see the script).
+//
+// Others are forwarded to the system's own copy when it has one. Libraries referencing them get this one as a
+// dependency (package_release.sh).
+#define _GNU_SOURCE
+#include <dlfcn.h>
+#include <errno.h>
+#include <stddef.h>
+#include <stdint.h>
+#include <string.h>
+#include <sys/random.h>
+
+// glibc 2.36
+void arc4random_buf (void* buffer, size_t size) {
+    unsigned char* out = buffer;
+
+    while (size > 0) {
+        ssize_t got = getrandom (out, size, 0);
+
+        if (got < 0) {
+            if (errno == EINTR)
+                continue;
+            // no fallback: getrandom exists since Linux 3.17
+            __builtin_trap ();
+        }
+
+        out += got;
+        size -= got;
+    }
+}
+
+uint32_t arc4random (void) {
+    uint32_t value;
+
+    arc4random_buf (&value, sizeof (value));
+    return value;
+}
+
+uint32_t arc4random_uniform (uint32_t upper) {
+    if (upper < 2)
+        return 0;
+
+    // rejection sampling to avoid the modulo bias
+    uint32_t min = -upper % upper;
+    uint32_t value;
+
+    do {
+        value = arc4random ();
+    } while (value < min);
+
+    return value % upper;
+}
+
+// libpipewire 0.3.50, called by mpv (Ubuntu 22.04 has 0.3.48). The older call fills the start of the same struct
+int pw_stream_get_time_n (void* stream, void* time, size_t size) {
+    static int (*own) (void*, void*, size_t);
+    static int (*old) (void*, void*);
+
+    if (!own && !old) {
+        own = dlsym (RTLD_NEXT, "pw_stream_get_time_n");
+        old = dlsym (RTLD_DEFAULT, "pw_stream_get_time");
+    }
+
+    if (own)
+        return own (stream, time, size);
+    if (!old)
+        return -ENOSYS;
+
+    memset (time, 0, size);
+    return old (stream, time);
+}

+ 114 - 0
tools/glibc_compat/retarget_glibc_versions.py

@@ -0,0 +1,114 @@
+#!/usr/bin/env python3
+"""Lowers a shared library's glibc requirement for symbols lwe_glibc_compat.c provides.
+
+usage: retarget_glibc_versions.py <floor> <provided symbols, comma separated> <library>...
+
+Every GLIBC_x version a library needs that is newer than <floor> (e.g. 2.35) is rewritten in its version needs
+(.gnu.version_r) to GLIBC_2.2.5, which every x86_64 glibc defines, so the loader no longer refuses it on an older
+glibc. The symbols bound to that version then can't match libc's own versioned copies and bind to the next
+unversioned definition in the global scope, the compat library (add it as a dependency with patchelf). Refuses
+when an undefined symbol of such a version isn't in the provided list. Prints the libraries it changed.
+"""
+import struct
+import sys
+
+SHT_DYNSYM = 11
+SHT_GNU_VERNEED = 0x6FFFFFFE
+SHT_GNU_VERSYM = 0x6FFFFFFF
+BASE_VERSION = b"GLIBC_2.2.5"
+
+
+def elf_hash(name):
+    h = 0
+    for c in name:
+        h = (h << 4) + c
+        g = h & 0xF0000000
+        if g:
+            h ^= g >> 24
+        h &= ~g & 0xFFFFFFFF
+    return h
+
+
+def version_tuple(name):
+    return tuple(int(p) for p in name[len("GLIBC_"):].split("."))
+
+
+def cstr(data, offset):
+    return data[offset:data.index(b"\0", offset)]
+
+
+def retarget(path, floor, provided):
+    with open(path, "rb") as f:
+        data = bytearray(f.read())
+    if data[:4] != b"\x7fELF" or data[4] != 2 or data[5] != 1:
+        return False
+
+    shoff, = struct.unpack_from("<Q", data, 0x28)
+    shentsize, shnum = struct.unpack_from("<HH", data, 0x3A)
+    sections = []
+    for i in range(shnum):
+        name, stype, flags, addr, offset, size, link, info, align, entsize = struct.unpack_from(
+            "<IIQQQQIIQQ", data, shoff + i * shentsize)
+        sections.append({"type": stype, "offset": offset, "size": size, "link": link, "info": info,
+                         "entsize": entsize})
+
+    verneed = next((s for s in sections if s["type"] == SHT_GNU_VERNEED), None)
+    if verneed is None:
+        return False
+    strtab = sections[verneed["link"]]["offset"]
+
+    # vernaux entries of libc.so.6 newer than the floor, and where GLIBC_2.2.5's name sits in .dynstr
+    base_name = None
+    newer = {}
+    offset = verneed["offset"]
+    for _ in range(verneed["info"]):
+        vn_version, vn_cnt, vn_file, vn_aux, vn_next = struct.unpack_from("<HHIII", data, offset)
+        aux = offset + vn_aux
+        for _ in range(vn_cnt):
+            vna_hash, vna_flags, vna_other, vna_name, vna_next = struct.unpack_from("<IHHII", data, aux)
+            name = cstr(data, strtab + vna_name)
+            if name == BASE_VERSION:
+                base_name = vna_name
+            elif name.startswith(b"GLIBC_") and version_tuple(name.decode()) > floor:
+                newer[vna_other] = (aux, name.decode())
+            aux += vna_next
+        offset += vn_next
+
+    if not newer:
+        return False
+    if base_name is None:
+        raise SystemExit(f"{path}: needs {BASE_VERSION.decode()} for the rewrite but doesn't reference it")
+
+    dynsym = next(s for s in sections if s["type"] == SHT_DYNSYM)
+    versym = next(s for s in sections if s["type"] == SHT_GNU_VERSYM)
+    symstr = sections[dynsym["link"]]["offset"]
+    for i in range(dynsym["size"] // dynsym["entsize"]):
+        st_name, st_info, st_other, st_shndx = struct.unpack_from("<IBBH", data, dynsym["offset"] + i * 24)
+        index, = struct.unpack_from("<H", data, versym["offset"] + i * 2)
+        index &= 0x7FFF
+        if index in newer:
+            symbol = cstr(data, symstr + st_name).decode()
+            if st_shndx != 0 or symbol not in provided:
+                raise SystemExit(f"{path}: {symbol}@{newer[index][1]} is newer than GLIBC_{'.'.join(map(str, floor))}"
+                                 f" and not in lwe_glibc_compat.c")
+
+    for aux, _ in newer.values():
+        struct.pack_into("<I", data, aux, elf_hash(BASE_VERSION))
+        struct.pack_into("<I", data, aux + 8, base_name)
+    with open(path, "wb") as f:
+        f.write(data)
+    print(path)
+    return True
+
+
+def main():
+    if len(sys.argv) < 4:
+        raise SystemExit(__doc__)
+    floor = version_tuple("GLIBC_" + sys.argv[1])
+    provided = set(sys.argv[2].split(","))
+    for path in sys.argv[3:]:
+        retarget(path, floor, provided)
+
+
+if __name__ == "__main__":
+    main()

+ 9 - 1
tools/headless_render.sh

@@ -79,10 +79,18 @@ if command -v dbus-daemon >/dev/null; then
     DBUS_PID=$(dbus-daemon --session --fork --print-pid --address="unix:path=$RUNTIME_DIR/bus")
     BUS_ADDRESS="unix:path=$RUNTIME_DIR/bus"
 fi
+# HEADLESS_RENDER_PULSE_SERVER: private audio server to play into (tools/wecompare/wine/audio_sink.sh), never the desktop's
+PULSE=unix:/nonexistent-pulse
+if [ -n "${HEADLESS_RENDER_PULSE_SERVER:-}" ]; then
+    case "$HEADLESS_RENDER_PULSE_SERVER" in
+        *"/run/user/"*) echo "HEADLESS_RENDER_PULSE_SERVER must not be the desktop's audio server" >&2; exit 1 ;;
+    esac
+    PULSE=$HEADLESS_RENDER_PULSE_SERVER
+fi
 ISOLATE=(-u WAYLAND_DISPLAY -u WAYLAND_SOCKET -u KDE_FULL_SESSION -u KDE_SESSION_VERSION
     -u DESKTOP_SESSION -u XDG_CURRENT_DESKTOP -u XDG_SESSION_DESKTOP XDG_RUNTIME_DIR="$RUNTIME_DIR"
     DBUS_SESSION_BUS_ADDRESS="$BUS_ADDRESS"
-    PULSE_SERVER=unix:/nonexistent-pulse PIPEWIRE_REMOTE=/nonexistent-pipewire)
+    PULSE_SERVER="$PULSE" PIPEWIRE_REMOTE=/nonexistent-pipewire)
 if [ -n "$USE_GPU" ]; then
     SESSION=(env -u DISPLAY "${ISOLATE[@]}" XDG_SESSION_TYPE=headless)
 else

+ 132 - 7
tools/package_release.sh

@@ -1,14 +1,28 @@
 #!/usr/bin/env bash
-# Packs a finished build into a relocatable tarball: the binary, its library, CEF's runtime files
-# and the shared kissfft, all found through the $ORIGIN runpath `cmake --install` sets. The install
-# tree also carries the dependencies' own tools, headers and static libs, those are left out.
+# Packs a finished build into a relocatable tarball: the binary, its library, the web helper, CEF's runtime files
+# and the shared kissfft, found through the $ORIGIN runpath `cmake --install` sets. The dependencies' own tools,
+# headers and static libs are left out.
 #
 # Usage:
-#   tools/package_release.sh <build-dir> <package-name> <output-dir>
+#   tools/package_release.sh [--portable] <build-dir> <package-name> <output-dir>
 #
 # Writes <output-dir>/<package-name>.tar.gz with a single <package-name>/ folder inside.
+#
+# --portable also copies every shared library the binaries need into lib/, except system ones (glibc, GPU,
+# display and audio clients, D-Bus, the GTK/NSS stack CEF loads). Build it on the oldest glibc it should run on
+# (CI: Debian 12). Bundled libraries calling glibc functions newer than GLIBC_FLOOR (default 2.35) get them from
+# tools/glibc_compat. The engine binary becomes linux-wallpaperengine.bin behind tools/portable_launcher.sh, which
+# adds the lib/fallback copies the system lacks. lib/SYSTEM_LIBS lists the sonames left to the system,
+# tools/smoke_test_release.sh checks a tarball against a distribution.
 set -euo pipefail
 
+portable=0
+if [ "${1:-}" = --portable ]; then
+    portable=1
+    shift
+fi
+
+tools_dir="$(dirname "$(realpath "$0")")"
 build_dir="$(realpath "$1")"
 name="$2"
 out_dir="$(realpath "$3")"
@@ -21,8 +35,8 @@ cmake --install "$build_dir" --prefix "$work/install" >/dev/null
 pkg="$work/$name"
 mkdir -p "$pkg"
 cd "$work/install"
-cp -a linux-wallpaperengine liblinux-wallpaperengine-lib.so libcef.so libEGL.so libGLESv2.so \
-    libvk_swiftshader.so vk_swiftshader_icd.json chrome-sandbox icudtl.dat v8_context_snapshot.bin \
+cp -a linux-wallpaperengine linux-wallpaperengine-web-helper liblinux-wallpaperengine-lib.so libcef.so libEGL.so \
+    libGLESv2.so libvk_swiftshader.so vk_swiftshader_icd.json chrome-sandbox icudtl.dat v8_context_snapshot.bin \
     ./*.pak locales "$pkg/"
 
 # GNUInstallDirs puts kissfft in lib64 on Fedora and lib elsewhere, the runpath covers both
@@ -32,11 +46,122 @@ if [ ! -e "${kissfft[0]}" ]; then
     exit 1
 fi
 libdir="$(dirname "${kissfft[0]}")"
+[ "$portable" = 1 ] && libdir=lib
 mkdir -p "$pkg/$libdir"
 cp -a "${kissfft[@]}" "$pkg/$libdir/"
 
 # CEF ships libcef.so with debug symbols, 1.4 GB instead of about 220 MB
-strip --strip-unneeded "$pkg/linux-wallpaperengine" "$pkg/liblinux-wallpaperengine-lib.so" "$pkg/libcef.so"
+strip --strip-unneeded "$pkg/linux-wallpaperengine" "$pkg/linux-wallpaperengine-web-helper" \
+    "$pkg/liblinux-wallpaperengine-lib.so" "$pkg/libcef.so"
+
+if [ "$portable" = 1 ]; then
+    # sonames (extended regexes) left to the system, everything else gets bundled
+    system_libs=(
+        # glibc and the compiler runtime
+        'ld-linux-x86-64' 'libc' 'libm' 'libdl' 'libpthread' 'librt' 'libresolv' 'libutil' 'libanl' 'libmvec'
+        'libBrokenLocale' 'libnsl' 'libstdc\+\+' 'libgcc_s'
+        # GPU, display servers, input
+        'libGL' 'libGLX' 'libGLdispatch' 'libOpenGL' 'libEGL' 'libGLESv1_CM' 'libGLESv2' 'libgbm' 'libdrm.*'
+        # libva: an older bundled one can't load newer drivers
+        'libvulkan' 'libva' 'libva-(drm|x11|wayland)' 'libwayland-.*' 'libX11' 'libX11-xcb' 'libXau'
+        'libXdmcp' 'libXext' 'libXrender' 'libXfixes' 'libXrandr' 'libXi' 'libXcursor' 'libXinerama' 'libXdamage'
+        'libXcomposite' 'libXxf86vm' 'libxkbcommon.*' 'libxshmfence' 'libSM' 'libICE' 'libudev' 'libinput'
+        'libevdev'
+        # xcb extensions Mesa and cairo use
+        'libxcb' 'libxcb-(dri2|dri3|present|sync|xfixes|randr|shm|glx|xkb|render|xinput|composite|damage)'
+        # audio and IPC client libraries, they load plugins from system paths
+        'libasound' 'libpipewire-0\.3' 'libdbus-1' 'libsystemd' 'libcap'
+        # what CEF and the system's GTK stack link themselves
+        'libnss3' 'libnssutil3' 'libsmime3' 'libssl3' 'libnspr4' 'libplc4' 'libplds4' 'libcups' 'libatk-1\.0'
+        'libatk-bridge-2\.0' 'libatspi' 'libpango.*' 'libcairo.*' 'libpixman-1' 'libgdk_pixbuf-2\.0' 'libgtk-3' 'libgdk-3'
+        'libglib-2\.0' 'libgobject-2\.0' 'libgio-2\.0' 'libgmodule-2\.0' 'libgthread-2\.0' 'libffi' 'libpcre2-.*'
+        'libmount' 'libblkid' 'libselinux' 'libuuid' 'libz' 'libthai' 'libdatrie' 'libavahi-.*'
+    )
+    system_re="^($(IFS='|'; echo "${system_libs[*]}"))\.so(\..*)?$"
+    # bundled but only used when the system lacks that soname, since system libraries may need their own newer
+    # copy (GnuTLS and nettle). The launcher adds lib/fallback/<soname> for the missing ones
+    fallback_libs=(
+        'libnettle' 'libhogweed' 'libgnutls' 'libtasn1' 'libidn2' 'libunistring' 'libp11-kit' 'libgmp' 'libgcrypt'
+        'libgpg-error' 'libssl' 'libcrypto' 'libbrotli(common|dec|enc)' 'liblzma' 'libzstd' 'liblz4' 'libbz2'
+        'libexpat' 'libpng16' 'libfreetype' 'libfontconfig' 'libharfbuzz' 'libgraphite2' 'libfribidi' 'libxml2'
+        'libkrb5.*' 'libk5crypto' 'libcom_err' 'libgssapi_krb5' 'libkeyutils'
+    )
+    fallback_re="^($(IFS='|'; echo "${fallback_libs[*]}"))\.so(\..*)?$"
+
+    mkdir -p "$pkg/lib/fallback"
+    elves=("$pkg/linux-wallpaperengine" "$pkg/linux-wallpaperengine-web-helper" "$pkg/liblinux-wallpaperengine-lib.so"
+        "$pkg"/lib/libkissfft-float.so*)
+    declare -A seen=()
+    : >"$work/system"
+    while [ "${#elves[@]}" -gt 0 ]; do
+        elf="${elves[0]}"
+        elves=("${elves[@]:1}")
+        while read -r soname path; do
+            [ -n "${seen[$soname]:-}" ] && continue
+            seen[$soname]=1
+            if [[ "$soname" =~ $system_re ]] || [ "$soname" = libcef.so ]; then
+                echo "$soname" >>"$work/system"
+                continue
+            fi
+            [ -e "$pkg/lib/$soname" ] || [[ "$path" == "$pkg"/* ]] && continue
+            if [ "$path" = "not" ]; then
+                echo "$elf needs $soname, which is not installed on the build system" >&2
+                exit 1
+            fi
+            dest="$pkg/lib/$soname"
+            if [[ "$soname" =~ $fallback_re ]]; then
+                mkdir -p "$pkg/lib/fallback/$soname"
+                dest="$pkg/lib/fallback/$soname/$soname"
+            fi
+            cp -L "$path" "$dest"
+            chmod u+w "$dest"
+            elves+=("$dest")
+        done < <(LD_LIBRARY_PATH="$pkg:$pkg/lib:$(find "$pkg/lib/fallback" -mindepth 1 -type d | paste -sd:)" ldd "$elf" |
+            awk '$2 == "=>" { print $1, $3 }')
+    done
+    mapfile -t bundled < <(find "$pkg/lib" -name '*.so*' -type f)
+
+    command -v patchelf >/dev/null || { echo "--portable needs patchelf" >&2; exit 1; }
+    # before patchelf, strip can break what patchelf moved around
+    strip --strip-unneeded "${bundled[@]}" 2>/dev/null || true
+
+    floor="${GLIBC_FLOOR:-2.35}"
+    compat=liblwe-glibc-compat.so
+    gcc -shared -fPIC -O2 -o "$pkg/lib/$compat" "$tools_dir/glibc_compat/lwe_glibc_compat.c"
+    provided=$(nm -D --defined-only "$pkg/lib/$compat" | awk '$2 == "T" { print $3 }' | paste -sd,)
+    python3 "$tools_dir/glibc_compat/retarget_glibc_versions.py" "$floor" "$provided" "${bundled[@]}" >/dev/null
+    for f in "${bundled[@]}"; do
+        if nm -D --undefined-only "$f" | awk '{ print $2 }' | sed 's/@.*//' | grep -qxF -f <(tr , '\n' <<<"$provided"); then
+            patchelf --add-needed "$compat" "$f"
+        fi
+    done
+
+    for f in "${bundled[@]}"; do
+        case "$f" in
+            "$pkg"/lib/fallback/*) patchelf --set-rpath '$ORIGIN/../..' "$f" ;;
+            *) patchelf --set-rpath '$ORIGIN' "$f" ;;
+        esac
+    done
+    for f in linux-wallpaperengine linux-wallpaperengine-web-helper liblinux-wallpaperengine-lib.so; do
+        patchelf --set-rpath '$ORIGIN:$ORIGIN/lib' "$pkg/$f"
+    done
+    sort -u "$work/system" | grep -v '^libcef.so$' >"$pkg/lib/SYSTEM_LIBS"
+
+    mv "$pkg/linux-wallpaperengine" "$pkg/linux-wallpaperengine.bin"
+    cp "$tools_dir/portable_launcher.sh" "$pkg/linux-wallpaperengine"
+    chmod 755 "$pkg/linux-wallpaperengine"
+
+    glibc=$(find "$pkg" -maxdepth 4 -type f \( -name '*.so*' -o -name '*.bin' -o -name '*-helper' \) \
+        -exec objdump -T {} + 2>/dev/null | grep -o 'GLIBC_[0-9.]*' | sort -uV | tail -1 || true)
+    echo "Bundled $(find "$pkg/lib" -name '*.so*' -type f | wc -l) libraries, needs $glibc"
+    if [ "$(printf '%s\n' "${glibc#GLIBC_}" "$floor" | sort -V | tail -1)" != "$floor" ]; then
+        echo "needs a newer glibc than $floor:" >&2
+        find "$pkg" -maxdepth 4 -type f -name '*.so*' -exec sh -c \
+            'objdump -T "$1" | grep -q "($2)" && echo "  $1"' _ {} "$glibc" \; >&2
+        exit 1
+    fi
+    echo "${glibc#GLIBC_}" >"$pkg/lib/GLIBC_VERSION"
+fi
 
 mkdir -p "$out_dir"
 tar -czf "$out_dir/$name.tar.gz" -C "$work" "$name"

+ 38 - 0
tools/portable_launcher.sh

@@ -0,0 +1,38 @@
+#!/bin/sh
+# linux-wallpaperengine of the portable release (tools/package_release.sh --portable). Starts the engine with the
+# bundled lib/fallback/<soname> copies on the library path, only for sonames the system doesn't have.
+#
+# --check-libraries prints `ldd -r` of the engine and the web helper with that path and exits.
+here=$(dirname "$(readlink -f "$0")")
+
+system_has() {
+    for ldconfig in /sbin/ldconfig /usr/sbin/ldconfig /usr/bin/ldconfig; do
+        if [ -x "$ldconfig" ]; then
+            "$ldconfig" -p 2>/dev/null | grep -q "^[[:space:]]*$1 (.*x86-64" && return 0
+            break
+        fi
+    done
+    for libdir in /lib64 /usr/lib64 /lib/x86_64-linux-gnu /usr/lib/x86_64-linux-gnu /usr/lib /lib; do
+        [ -e "$libdir/$1" ] && return 0
+    done
+    return 1
+}
+
+fallback=
+for dir in "$here"/lib/fallback/*/; do
+    [ -d "$dir" ] || continue
+    soname=$(basename "$dir")
+    system_has "$soname" || fallback="$fallback:${dir%/}"
+done
+if [ -n "$fallback" ]; then
+    LD_LIBRARY_PATH="${LD_LIBRARY_PATH:+$LD_LIBRARY_PATH}$fallback"
+    LD_LIBRARY_PATH="${LD_LIBRARY_PATH#:}"
+    export LD_LIBRARY_PATH
+fi
+
+if [ "$1" = --check-libraries ]; then
+    ldd -r "$here/linux-wallpaperengine.bin" "$here/linux-wallpaperengine-web-helper"
+    exit
+fi
+
+exec "$here/linux-wallpaperengine.bin" "$@"

+ 150 - 0
tools/smoke_test_release.sh

@@ -0,0 +1,150 @@
+#!/usr/bin/env bash
+# Checks a release tarball on the running distribution: unpacks it, resolves the engine and the web helper with
+# `ldd -r` (portable tarballs through their launcher's --check-libraries) and runs `linux-wallpaperengine --help`.
+# A missing library or symbol version fails, and so does an unresolved symbol in our own libraries. Unresolved
+# functions in bundled third-party libraries are only listed, they bind lazily.
+#
+# Usage:
+#   tools/smoke_test_release.sh [--install-deps] <tarball>
+#
+# --install-deps first installs what a desktop system has anyway (GTK 3, NSS, Mesa, libva, PipeWire, CUPS, ALSA,
+# GnuTLS, libgcrypt) for bare CI containers, and for a non-portable tarball whatever provides the libraries still
+# missing, looked up by soname (LIBNODE_PKG names a built package for Arch's AUR-only libnode). Run as root then.
+# Knows Debian/Ubuntu, Fedora, Arch and openSUSE.
+set -euo pipefail
+
+install_deps=0
+if [ "${1:-}" = --install-deps ]; then
+    install_deps=1
+    shift
+fi
+tarball="$(realpath "$1")"
+
+install_desktop_runtime() {
+    . /etc/os-release
+    case " $ID ${ID_LIKE:-} " in
+        *" debian "* | *" ubuntu "*)
+            export DEBIAN_FRONTEND=noninteractive
+            apt-get update -qq
+            # Ubuntu 24.04 and Debian 13 renamed some for the 64 bit time_t transition
+            local pkgs=() p
+            for p in libgtk-3-0 libnss3 libasound2 libcups2 libpipewire-0.3-0 libgl1 libegl1 libgbm1 libvulkan1 \
+                libva2 libva-drm2 libva-x11-2 libva-wayland2 libxkbcommon0 libwayland-egl1 libxxf86vm1 liblz4-1 libgnutls30 libgcrypt20; do
+                if apt-cache show "${p}t64" >/dev/null 2>&1; then pkgs+=("${p}t64"); else pkgs+=("$p"); fi
+            done
+            apt-get install -y -qq --no-install-recommends "${pkgs[@]}" >/dev/null
+            ;;
+        *" fedora "*)
+            dnf -y -q install gtk3 nss alsa-lib cups-libs pipewire-libs mesa-libGL mesa-libEGL mesa-libgbm \
+                vulkan-loader libva libxkbcommon libwayland-egl libXxf86vm lz4-libs gnutls libgcrypt binutils findutils >/dev/null
+            ;;
+        *" arch "*)
+            pacman -Syu --noconfirm --needed gtk3 nss alsa-lib libcups libpipewire mesa vulkan-icd-loader libva \
+                libxkbcommon libxxf86vm lz4 gnutls libgcrypt binutils findutils >/dev/null
+            ;;
+        *" suse "* | *" opensuse "*)
+            zypper -n -q install libgtk-3-0 mozilla-nss libasound2 libcups2 libpipewire-0_3-0 Mesa-libGL1 \
+                Mesa-libEGL1 libgbm1 libvulkan1 libva2 libva-drm2 libva-x11-2 libva-wayland2 libxkbcommon0 \
+                libwayland-egl1 libXxf86vm1 liblz4-1 libgnutls30 libgcrypt20 binutils findutils gzip tar >/dev/null
+            ;;
+        *)
+            echo "don't know how to install packages on $PRETTY_NAME" >&2
+            exit 1
+            ;;
+    esac
+}
+
+# packages providing the given sonames, through each package manager's file index
+install_sonames() {
+    . /etc/os-release
+    local pkgs=() so
+    case " $ID ${ID_LIKE:-} " in
+        *" debian "* | *" ubuntu "*)
+            apt-get install -y -qq --no-install-recommends apt-file >/dev/null
+            apt-file update >/dev/null
+            for so in "$@"; do
+                pkgs+=($(apt-file search -x "/${so//./\\.}\$" | cut -d: -f1 | grep -v -- '-dbg' | head -1))
+            done
+            apt-get install -y -qq --no-install-recommends "${pkgs[@]}" >/dev/null
+            ;;
+        *" fedora "*)
+            dnf -y -q install "${@/%/()(64bit)}" >/dev/null
+            ;;
+        *" arch "*)
+            if [[ " $* " == *" libnode.so."* ]] && [ -n "${LIBNODE_PKG:-}" ]; then
+                pacman -U --noconfirm "$LIBNODE_PKG" >/dev/null
+            fi
+            pacman -Fy >/dev/null
+            for so in "$@"; do
+                [[ "$so" == libnode.so.* ]] && continue
+                pkgs+=($(pacman -Fq "/usr/lib/$so" | head -1 | cut -d/ -f2))
+            done
+            [ "${#pkgs[@]}" -gt 0 ] && pacman -S --noconfirm --needed "${pkgs[@]}" >/dev/null
+            ;;
+        *" suse "* | *" opensuse "*)
+            zypper -n -q install "${@/%/()(64bit)}" >/dev/null
+            ;;
+    esac
+}
+
+[ "$install_deps" = 1 ] && install_desktop_runtime
+
+work="$(mktemp -d)"
+trap 'rm -rf "$work"' EXIT
+tar -xzf "$tarball" -C "$work"
+dir=("$work"/*/)
+dir="${dir[0]%/}"
+
+. /etc/os-release
+echo "== $(basename "$tarball") on $PRETTY_NAME, $(ldd --version | head -1)"
+
+failed=0
+check_libraries() {
+    if [ -e "$dir/linux-wallpaperengine.bin" ]; then
+        # the launcher puts the fallback copies the system lacks on the path, like when it starts the engine
+        "$dir/linux-wallpaperengine" --check-libraries 2>&1 || true
+    else
+        ldd -r "$dir/linux-wallpaperengine" "$dir/linux-wallpaperengine-web-helper" 2>&1 || true
+    fi
+}
+out="$(check_libraries)"
+if [ "$install_deps" = 1 ] && [ ! -e "$dir/linux-wallpaperengine.bin" ]; then
+    mapfile -t sonames < <(awk '/=> not found/ { print $1 }' <<<"$out" | sort -u)
+    if [ "${#sonames[@]}" -gt 0 ]; then
+        echo "-- installing what provides ${sonames[*]}"
+        install_sonames "${sonames[@]}"
+        out="$(check_libraries)"
+    fi
+fi
+missing="$(grep -E 'not found' <<<"$out" | sort -u || true)"
+ours="$(grep -E 'undefined symbol: .*/(linux-wallpaperengine[^/]*|liblinux-wallpaperengine-lib\.so)\)' <<<"$out" || true)"
+lazy="$(grep -E 'undefined symbol' <<<"$out" | grep -vE '/(linux-wallpaperengine[^/]*|liblinux-wallpaperengine-lib\.so)\)' |
+    sed -E 's/^\s*undefined symbol: (\S+).*\/([^/)]+)\)$/\2: \1/' | sort -u || true)"
+if [ -n "$missing$ours" ]; then
+    echo "-- missing"
+    sed 's/^/   /' <<<"$missing$ours" | head -30
+    failed=1
+fi
+if [ -n "$lazy" ]; then
+    echo "-- unresolved functions in bundled libraries (only fail when called):"
+    sed 's/^/   /' <<<"$lazy" | head -30
+fi
+fallback="$(grep -oE 'lib/fallback/[^/]+' <<<"$out" | sort -u | sed 's|lib/fallback/||' | paste -sd' ' || true)"
+[ -n "$fallback" ] && echo "-- uses the bundled fallback for: $fallback"
+
+if ! help="$(cd / && "$dir/linux-wallpaperengine" --help 2>&1)"; then
+    echo "-- linux-wallpaperengine --help failed:"
+    sed 's/^/   /' <<<"$help" | tail -20
+    failed=1
+elif ! grep -q -- '--screen-root' <<<"$help"; then
+    echo "-- linux-wallpaperengine --help printed something unexpected:"
+    sed 's/^/   /' <<<"$help" | head -20
+    failed=1
+fi
+
+if [ "$failed" = 0 ]; then
+    echo "OK"
+else
+    echo "FAILED"
+fi
+exit "$failed"

+ 8 - 0
tools/wecompare/README.md

@@ -38,6 +38,14 @@ Data locations (all overridable):
 - `we_cursor.sh <scene> <outdir> "x,y x,y" [settle]` - warps the pointer before each grab (parallax, cursor).
 - `we_capture.sh <scene> [secs]` - RenderDoc capture of one WE frame (inspect with `tools/rdc_dump.py` on :98,
   `rdscripts/` has the replay scripts).
+- `audio_sink.sh start|stop|env|record <wav> <secs>` - a private PulseAudio with one null sink (never the desktop's
+  server) and a recorder on its monitor. `WE_AUDIO_REC=<wav> we_full.sh ...` plays live WE into it, and
+  `HEADLESS_RENDER_PULSE_SERVER` does the same for `tools/headless_render.sh`; `../wavstat.py` prints levels. Align
+  recordings by onset, not wall clock.
+- `WE_WINE_DIR=<wine build root> WE_PREFIX=<prefix>` run WE on another Wine (e.g. WineHQ 11.0 unpacked into
+  `~/.local/share/wine11`, prefix `~/.local/share/we_live/wineprefix11` with upstream DXVK 3.1.1 PE DLLs and
+  mscoree/mshtml disabled), `WE_WINEDEBUG` sets WINEDEBUG.
+- `gdb_video_hr.py` - HRESULTs of WE's video texture upload (keyed mutex + TransferVideoFrame) on a live WE.
 - `repack_pkg.py in.pkg out.pkg name=file ...` - replaces files inside a scene.pkg (test variants of scenes
   whose texture names Wine can't open in folder mode).
 

+ 35 - 0
tools/wecompare/wavstat.py

@@ -0,0 +1,35 @@
+#!/usr/bin/env python3
+"""wavstat.py <file.wav> [window seconds] - per channel peak/RMS and, per window, RMS of each channel.
+Reads the float32 or int16 WAVs parec writes (audio_sink.sh record)."""
+import struct, sys
+import numpy as np
+
+
+def read_wav(path):
+    d = open(path, 'rb').read()
+    pos, fmt, data = 12, None, None
+    while pos + 8 <= len(d):
+        tag, size = d[pos:pos + 4], struct.unpack('<I', d[pos + 4:pos + 8])[0]
+        body = d[pos + 8:pos + 8 + size] if size != 0xFFFFFFFF else d[pos + 8:]
+        if tag == b'fmt ':
+            fmt = struct.unpack('<HHIIHH', body[:16])
+        elif tag == b'data':
+            data = body
+            break
+        pos += 8 + size + (size & 1)
+    code, channels, rate, _, _, bits = fmt
+    dtype = '<f4' if code == 3 or (code == 0xFFFE and bits == 32) else '<i2'
+    a = np.frombuffer(data[:len(data) // (channels * bits // 8) * channels * bits // 8], dtype=dtype)
+    a = a.astype(np.float64) / (32768.0 if dtype == '<i2' else 1.0)
+    return a.reshape(-1, channels), rate
+
+
+if __name__ == '__main__':
+    a, rate = read_wav(sys.argv[1])
+    print('%s: %.2f s, %d Hz, %d ch' % (sys.argv[1], len(a) / rate, rate, a.shape[1]))
+    print('peak', np.abs(a).max(0).round(4), 'rms', np.sqrt((a ** 2).mean(0)).round(4))
+    if len(sys.argv) > 2:
+        n = int(float(sys.argv[2]) * rate)
+        for i in range(0, len(a), n):
+            w = a[i:i + n]
+            print('%7.2f s  ' % (i / rate) + '  '.join('%.4f' % v for v in np.sqrt((w ** 2).mean(0))))

+ 49 - 0
tools/wecompare/wine/audio_sink.sh

@@ -0,0 +1,49 @@
+#!/bin/bash
+# usage: audio_sink.sh start|stop|env|record <out.wav> <seconds>
+# private PulseAudio with a single null sink, no connection to the desktop's audio server.
+# `eval "$(audio_sink.sh env)"` points a process at it, `record` captures the sink's monitor (float32 stereo 48 kHz
+# WAV). Clients need PULSE_LATENCY_MSEC (set by env), otherwise the monitor delivers in 2 s blocks; parec takes
+# ~0.5 s to connect, so align recordings by onset
+S=${WE_LIVE_DIR:-$HOME/.local/share/we_live}
+R=$S/run/pulse-null
+SOCK=$R/native
+
+env_lines() {
+    echo "export PULSE_SERVER=unix:$SOCK PULSE_COOKIE=$R/cookie PULSE_LATENCY_MSEC=20 PIPEWIRE_REMOTE=$S/run/no-pipewire ALSA_CONFIG_PATH=/dev/null"
+}
+
+running() { [ -S "$SOCK" ] && PULSE_SERVER=unix:$SOCK PULSE_COOKIE=$R/cookie pactl info >/dev/null 2>&1; }
+
+case "$1" in
+start)
+    running && exit 0
+    mkdir -p "$R"
+    cat > "$R/default.pa" <<EOF
+load-module module-native-protocol-unix socket=$SOCK auth-anonymous=1
+load-module module-null-sink sink_name=lwe_null rate=48000 channels=2 format=float32le sink_properties=device.description=lwe_null
+set-default-sink lwe_null
+set-default-source lwe_null.monitor
+EOF
+    # own runtime/state dirs and no autospawn, so it never finds the host's server
+    env -u DBUS_SESSION_BUS_ADDRESS XDG_RUNTIME_DIR=$R PULSE_RUNTIME_PATH=$R PULSE_STATE_PATH=$R \
+        PULSE_CONFIG_PATH=$R PULSE_COOKIE=$R/cookie \
+        nohup pulseaudio -n --daemonize=no --exit-idle-time=-1 --use-pid-file=no --disallow-module-loading \
+        --log-target=file:$R/log -F "$R/default.pa" > /dev/null 2>&1 &
+    for i in $(seq 50); do running && exit 0; sleep 0.1; done
+    echo "pulseaudio did not come up, see $R/log" >&2; exit 1 ;;
+stop)
+    pkill -f "pulseaudio -n .*$R/default.pa" ;;
+env)
+    env_lines ;;
+record)
+    running || { echo "not running" >&2; exit 1; }
+    eval "$(env_lines)"
+    # a silent low latency stream keeps the sink running so the monitor delivers a continuous timeline
+    pacat -p -d lwe_null --latency-msec=20 --rate=48000 --channels=2 --format=float32le < /dev/zero & KEEP=$!
+    sleep 0.3
+    timeout -s INT "$3" parec -d lwe_null.monitor --latency-msec=20 --rate=48000 --channels=2 --format=float32le --file-format=wav "$2"
+    kill $KEEP 2>/dev/null
+    [ -s "$2" ] ;;
+*)
+    sed -n 2,5p "$0"; exit 1 ;;
+esac

+ 22 - 0
tools/wecompare/wine/gdb_video_hr.py

@@ -0,0 +1,22 @@
+# HRESULTs of WE's video texture upload (wallpaper64.exe 2.8.42 sub_1400F3480): the keyed mutex AcquireSync and the
+# media engine's TransferVideoFrame into the shared texture; the frame only counts when both succeed.
+#     OUT=hr.txt COUNT=40 gdb -q -batch -p <wallpaper64.exe pid> -x gdb_video_hr.py
+import gdb, os
+gdb.execute('set pagination off')
+gdb.execute('set confirm off')
+out = open(os.environ.get('OUT', 'video_hr.txt'), 'w')
+count = [0]
+class B(gdb.Breakpoint):
+    def __init__(self, addr, kind):
+        super().__init__('*' + hex(addr), internal=False); self.kind = kind
+    def stop(self):
+        eax = int(gdb.selected_frame().read_register('rax')) & 0xffffffff
+        out.write('%s hr=0x%08x\n' % (self.kind, eax)); out.flush()
+        count[0] += 1
+        if count[0] >= int(os.environ.get('COUNT', 40)):
+            gdb.execute('delete'); out.close()
+            gdb.post_event(lambda: gdb.execute('detach'))
+        return False
+B(0x1400f3517, 'AcquireSync')
+B(0x1400f3545, 'TransferVideoFrame')
+gdb.execute('continue')

+ 7 - 4
tools/wecompare/wine/we_capture.sh

@@ -6,21 +6,24 @@ ulimit -c 0
 S=${WE_LIVE_DIR:-$HOME/.local/share/we_live}
 bash "$(dirname "$0")/we_display.sh" >/dev/null || exit 1
 pgrep -f "Xvfb :97" >/dev/null || { Xvfb :97 -screen 0 1920x1080x24 -nolisten tcp >/dev/null 2>&1 & sleep 1; }
-export WINEPREFIX=$S/wineprefix DISPLAY=:98 WINEDEBUG=-all DXVK_LOG_PATH=$S
+# WE_WINE_DIR=<other Wine build root> with its own WE_PREFIX (README); default is system Wine and $S/wineprefix
+WINE=${WE_WINE_DIR:+$WE_WINE_DIR/bin/wine}; WINE=${WINE:-/usr/lib/wine/wine64}
+WINESERVER=${WE_WINE_DIR:+$WE_WINE_DIR/bin/wineserver}; WINESERVER=${WINESERVER:-/usr/lib/wine/wineserver}
+export WINEPREFIX=${WE_PREFIX:-$S/wineprefix} DISPLAY=:98 WINEDEBUG=${WE_WINEDEBUG:--all} DXVK_LOG_PATH=$S
 # Wine must only see the isolated :98, not the desktop session (wayland-0, D-Bus) in the shared runtime dir
 unset WAYLAND_DISPLAY WAYLAND_SOCKET DBUS_SESSION_BUS_ADDRESS; export XDG_RUNTIME_DIR=$S/run
 # keep Wine off the desktop's audio server (a shared /run/user/<uid>/pulse would play the wallpaper's sounds on real speakers and feed real system audio to the visualizers)
 export PULSE_SERVER=unix:$S/run/no-pulse PIPEWIRE_REMOTE=$S/run/no-pipewire ALSA_CONFIG_PATH=/dev/null
 export VK_ADD_IMPLICIT_LAYER_PATH=$S/vklayer ENABLE_VULKAN_RENDERDOC_CAPTURE=1
-/usr/lib/wine/wineserver -k 2>/dev/null; sleep 3
+$WINESERVER -k 2>/dev/null; sleep 3
 cd $S/we28
 F=$1; [ -d "$F" ] && F=$F/scene.json
 WIN=$(echo "Z:$F" | tr '/' '\\')
-nohup /usr/lib/wine/wine64 wallpaper64.exe -control openWallpaper -file "$WIN" -monitor 0 -playInWindow -silent > $S/we_run_last.log 2>&1 &
+nohup $WINE wallpaper64.exe -control openWallpaper -file "$WIN" -monitor 0 -playInWindow -silent > $S/we_run_last.log 2>&1 &
 sleep ${2:-30}
 PID=$(pgrep -f "wallpaper64.exe -control" | head -1)
 # qrenderdoc only has the xcb platform; it runs on the isolated Xvfb :97 (analytics already opted out in ~/.renderdoc)
 env -u WAYLAND_DISPLAY -u VK_ADD_IMPLICIT_LAYER_PATH -u ENABLE_VULKAN_RENDERDOC_CAPTURE RD_PID=$PID RD_TRIGGER_OUT=$S/rd_trigger.out \
     QT_QPA_PLATFORM=xcb DISPLAY=:97 timeout 90 qrenderdoc --python $S/rd_trigger.py >/dev/null 2>&1
-/usr/lib/wine/wineserver -k 2>/dev/null
+$WINESERVER -k 2>/dev/null
 head -1 $S/rd_trigger.out

+ 7 - 4
tools/wecompare/wine/we_cursor.sh

@@ -6,16 +6,19 @@ ulimit -c 0
 S=${WE_LIVE_DIR:-$HOME/.local/share/we_live}
 D=:98
 bash "$(dirname "$0")/we_display.sh" >/dev/null || exit 1
-export WINEPREFIX=$S/wineprefix DISPLAY=$D WINEDEBUG=-all DXVK_LOG_PATH=$S
+# WE_WINE_DIR=<other Wine build root> with its own WE_PREFIX (README); default is system Wine and $S/wineprefix
+WINE=${WE_WINE_DIR:+$WE_WINE_DIR/bin/wine}; WINE=${WINE:-/usr/lib/wine/wine64}
+WINESERVER=${WE_WINE_DIR:+$WE_WINE_DIR/bin/wineserver}; WINESERVER=${WINESERVER:-/usr/lib/wine/wineserver}
+export WINEPREFIX=${WE_PREFIX:-$S/wineprefix} DISPLAY=$D WINEDEBUG=${WE_WINEDEBUG:--all} DXVK_LOG_PATH=$S
 # Wine must only see the isolated :98, not the desktop session (wayland-0, D-Bus) in the shared runtime dir
 unset WAYLAND_DISPLAY WAYLAND_SOCKET DBUS_SESSION_BUS_ADDRESS; export XDG_RUNTIME_DIR=$S/run
 # keep Wine off the desktop's audio server (a shared /run/user/<uid>/pulse would play the wallpaper's sounds on real speakers and feed real system audio to the visualizers)
 export PULSE_SERVER=unix:$S/run/no-pulse PIPEWIRE_REMOTE=$S/run/no-pipewire ALSA_CONFIG_PATH=/dev/null
-/usr/lib/wine/wineserver -k 2>/dev/null; timeout 4 tail -f /dev/null
+$WINESERVER -k 2>/dev/null; timeout 4 tail -f /dev/null
 cd $S/we28
 F=$1; [ -d "$F" ] && F=$F/scene.json
 WIN=$(echo "Z:$F" | tr '/' '\\')
-nohup /usr/lib/wine/wine64 wallpaper64.exe -control openWallpaper -file "$WIN" -monitor 0 -playInWindow -silent > $S/we_run_last.log 2>&1 &
+nohup $WINE wallpaper64.exe -control openWallpaper -file "$WIN" -monitor 0 -playInWindow -silent > $S/we_run_last.log 2>&1 &
 timeout 25 tail -f /dev/null
 mkdir -p "$2"
 python3 - "$2" "$3" "${4:-3}" "$D" <<'PY'
@@ -51,4 +54,4 @@ with mss.MSS(display=sys.argv[4]) as m:
         s=m.grab({'left':0,'top':0,'width':1920,'height':1080})
         Image.frombytes('RGB',s.size,s.rgb).save('%s/f%d_%d_%d.png'%(sys.argv[1],i,x,y))
 PY
-/usr/lib/wine/wineserver -k 2>/dev/null
+$WINESERVER -k 2>/dev/null

+ 19 - 4
tools/wecompare/wine/we_full.sh

@@ -6,18 +6,32 @@ ulimit -c 0
 S=${WE_LIVE_DIR:-$HOME/.local/share/we_live}
 D=${WE_DISPLAY:-:98}
 [ "$D" = ":98" ] && { bash "$(dirname "$0")/we_display.sh" >/dev/null || exit 1; }
-export WINEPREFIX=$S/wineprefix DISPLAY=$D WINEDEBUG=-all DXVK_LOG_PATH=$S
+# WE_WINE_DIR=<other Wine build root> with its own WE_PREFIX (README); default is system Wine and $S/wineprefix
+WINE=${WE_WINE_DIR:+$WE_WINE_DIR/bin/wine}; WINE=${WINE:-/usr/lib/wine/wine64}
+WINESERVER=${WE_WINE_DIR:+$WE_WINE_DIR/bin/wineserver}; WINESERVER=${WINESERVER:-/usr/lib/wine/wineserver}
+export WINEPREFIX=${WE_PREFIX:-$S/wineprefix} DISPLAY=$D WINEDEBUG=${WE_WINEDEBUG:--all} DXVK_LOG_PATH=$S
 # Wine must only see the isolated :98, not the desktop session (wayland-0, D-Bus) in the shared runtime dir
 unset WAYLAND_DISPLAY WAYLAND_SOCKET DBUS_SESSION_BUS_ADDRESS; export XDG_RUNTIME_DIR=$S/run
 # keep Wine off the desktop's audio server (a shared /run/user/<uid>/pulse would play the wallpaper's sounds on real speakers and feed real system audio to the visualizers)
 export PULSE_SERVER=unix:$S/run/no-pulse PIPEWIRE_REMOTE=$S/run/no-pipewire ALSA_CONFIG_PATH=/dev/null
+# WE_AUDIO_REC=<file.wav>: record WE's audio from a private null sink (audio_sink.sh)
+if [ -n "$WE_AUDIO_REC" ]; then
+    bash "$(dirname "$0")/audio_sink.sh" start || exit 1
+    eval "$(bash "$(dirname "$0")/audio_sink.sh" env)"
+fi
 [ -n "$WE_WINED3D" ] && export WINEDLLOVERRIDES="d3d11,d3d10core,dxgi=b"
 [ "$D" != ":97" ] || pgrep -f "Xvfb :97" >/dev/null || { Xvfb :97 -screen 0 1920x1080x24 -nolisten tcp >/dev/null 2>&1 & sleep 1; }
-/usr/lib/wine/wineserver -k 2>/dev/null; timeout 4 tail -f /dev/null
+$WINESERVER -k 2>/dev/null; timeout 4 tail -f /dev/null
 cd $S/we28
 F=$1; [ -d "$F" ] && F=$F/scene.json
 WIN=$(echo "Z:$F" | tr '/' '\\')
-nohup /usr/lib/wine/wine64 wallpaper64.exe -control openWallpaper -file "$WIN" -monitor 0 -playInWindow -silent > $S/we_run_last.log 2>&1 &
+if [ -n "$WE_AUDIO_REC" ]; then
+    bash "$(dirname "$0")/audio_sink.sh" record "$WE_AUDIO_REC" 600 & REC=$!
+    # WE plays ~1.5 s after launch, wait for the recorder
+    for i in $(seq 50); do pactl list short source-outputs 2>/dev/null | grep -q . && break; sleep 0.1; done
+    sleep 0.5
+fi
+nohup $WINE wallpaper64.exe -control openWallpaper -file "$WIN" -monitor 0 -playInWindow -silent > $S/we_run_last.log 2>&1 &
 timeout 25 tail -f /dev/null
 mkdir -p "$2"
 python3 - "$2" "${3:-10}" "${4:-1}" "$D" <<'PY'
@@ -44,4 +58,5 @@ with mss.MSS(display=sys.argv[4]) as m:
         Image.frombytes('RGB',s.size,s.rgb).save('%s/f%03d_%.1f.png'%(sys.argv[1],i,time.time()-t0))
         time.sleep(float(sys.argv[3]))
 PY
-/usr/lib/wine/wineserver -k 2>/dev/null
+$WINESERVER -k 2>/dev/null
+[ -n "$REC" ] && { pkill -INT -P $REC timeout; wait $REC; }