Skip to content

A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.

TypeScript fluxerfluxerapp

fix(desktop): ship synchronized VA-API decoding on Linux (#3522)

Hampusf2d146c9e44a
diff --git a/.github/actionlint.yaml b/.github/actionlint.yaml
index c59b54cc3..4121f4bf8 100644
--- a/.github/actionlint.yaml
+++ b/.github/actionlint.yaml
@@ -1,5 +1,6 @@
self-hosted-runner:
labels:
- fluxer-desktop-macos-arm64
+ - fluxer-electron-build
config-variables: null
diff --git a/.github/workflows/build-desktop-electron.yaml b/.github/workflows/build-desktop-electron.yaml
new file mode 100644
index 000000000..10a75abd9
--- /dev/null
+++ b/.github/workflows/build-desktop-electron.yaml
@@ -0,0 +1,108 @@
+name: build desktop Electron
+
+on:
+ workflow_dispatch:
+ inputs:
+ prebuilt_release_tag:
+ description: Draft release containing prebuilt Electron distributions. Leave empty to compile Electron on the build runner instead.
+ required: false
+ default: desktop-electron-runtime-44.4.1-fluxer.1
+ type: string
+
+permissions:
+ contents: read
+
+concurrency:
+ group: desktop-electron-build
+ cancel-in-progress: false
+
+jobs:
+ build:
+ name: Build patched Electron (linux-${{ matrix.arch }})
+ if: inputs.prebuilt_release_tag == ''
+ runs-on: [self-hosted, Linux, X64, fluxer-electron-build]
+ timeout-minutes: 1440
+ strategy:
+ fail-fast: false
+ max-parallel: 1
+ matrix:
+ arch: [x64, arm64]
+ steps:
+ - name: Checkout source
+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1
+
+ - name: Build patched Electron distribution
+ env:
+ CONTAINER_ENGINE: podman
+ CONTAINER_CPUS: "8"
+ CONTAINER_MEMORY: 48g
+ BUILD_JOBS: "8"
+ run: >-
+ bash fluxer_desktop/electron/build-linux.sh
+ --arch "${{ matrix.arch }}"
+ --build-root /srv/fluxer-electron-build/work
+ --output-dir "${{ runner.temp }}/fluxer-electron-artifacts"
+
+ - name: Upload patched Electron distribution
+ uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02
+ with:
+ name: desktop-electron-linux-${{ matrix.arch }}
+ path: |
+ ${{ runner.temp }}/fluxer-electron-artifacts/electron-v44.4.1-linux-${{ matrix.arch }}.zip
+ ${{ runner.temp }}/fluxer-electron-artifacts/electron-v44.4.1-linux-${{ matrix.arch }}.fluxer.json
+ if-no-files-found: error
+ retention-days: 30
+ compression-level: 0
+
+ import:
+ name: Import patched Electron (linux-${{ matrix.arch }})
+ if: inputs.prebuilt_release_tag != ''
+ runs-on: ubuntu-24.04
+ timeout-minutes: 30
+ permissions:
+ contents: write
+ strategy:
+ fail-fast: false
+ matrix:
+ arch: [x64, arm64]
+ steps:
+ - name: Checkout source
+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1
+
+ - name: Set up Node.js
+ uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020
+ with:
+ node-version: 26
+
+ - name: Download and verify build artifacts
+ env:
+ GH_TOKEN: ${{ github.token }}
+ PREBUILT_RELEASE_TAG: ${{ inputs.prebuilt_release_tag }}
+ ELECTRON_ARCH: ${{ matrix.arch }}
+ FLUXER_ELECTRON_DIST: ${{ runner.temp }}/fluxer-electron-artifacts
+ shell: bash
+ run: |
+ set -euo pipefail
+ gh release view "$PREBUILT_RELEASE_TAG" --repo "$GITHUB_REPOSITORY" \
+ --json isDraft --jq '.isDraft' | grep -qx true
+ gh release download "$PREBUILT_RELEASE_TAG" --repo "$GITHUB_REPOSITORY" \
+ --pattern "electron-v44.4.1-linux-$ELECTRON_ARCH.zip" \
+ --pattern "electron-v44.4.1-linux-$ELECTRON_ARCH.fluxer.json" \
+ --dir "$FLUXER_ELECTRON_DIST"
+ node <<'NODE'
+ const {verifyLinuxElectronArchive} = require('./fluxer_desktop/scripts/custom-electron.cjs');
+ verifyLinuxElectronArchive(process.env.FLUXER_ELECTRON_DIST, process.env.ELECTRON_ARCH)
+ .then(() => console.log('Patched Electron artifact verified.'))
+ .catch((error) => { console.error(error); process.exitCode = 1; });
+ NODE
+
+ - name: Upload patched Electron distribution
+ uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02
+ with:
+ name: desktop-electron-linux-${{ matrix.arch }}
+ path: |
+ ${{ runner.temp }}/fluxer-electron-artifacts/electron-v44.4.1-linux-${{ matrix.arch }}.zip
+ ${{ runner.temp }}/fluxer-electron-artifacts/electron-v44.4.1-linux-${{ matrix.arch }}.fluxer.json
+ if-no-files-found: error
+ retention-days: 30
+ compression-level: 0
diff --git a/.github/workflows/build-desktop.yaml b/.github/workflows/build-desktop.yaml
index 64b24bbff..dabc1ec7b 100644
--- a/.github/workflows/build-desktop.yaml
+++ b/.github/workflows/build-desktop.yaml
@@ -21,6 +21,11 @@ on:
required: false
default: ""
type: string
+ electron_build_run_id:
+ description: Successful manual main-branch build desktop Electron workflow run supplying the patched Linux Electron distributions. Required when building Linux.
+ required: false
+ default: ""
+ type: string
shell_contract:
description: "Did the shell contract change since the oldest shell these modules still reach? unchanged refuses if it did. compatible keeps older shells on these modules because the renderer still works on them. raise stops sending these modules to shells without the new contract: Linux and managed shells keep their current renderer, Windows and macOS update their shell first."
required: true
@@ -51,6 +56,7 @@ jobs:
timeout-minutes: 25
permissions:
contents: read
+ actions: read
outputs:
version: ${{ steps.meta.outputs.version }}
pub_date: ${{ steps.meta.outputs.pub_date }}
@@ -64,6 +70,30 @@ jobs:
ref: main
fetch-depth: 0
+ - name: Validate patched Electron build
+ env:
+ ELECTRON_BUILD_RUN_ID: ${{ inputs.electron_build_run_id }}
+ SKIP_TARGETS: ${{ inputs.skip_targets }}
+ GH_TOKEN: ${{ github.token }}
+ shell: bash
+ run: |
+ set -euo pipefail
+ skipped=",$(printf '%s' "$SKIP_TARGETS" | tr '[:space:]' ','),"
+ if [[ "$skipped" == *,linux,* ]] || \
+ { [[ "$skipped" == *,linux-x64,* ]] && [[ "$skipped" == *,linux-arm64,* ]]; }; then
+ exit 0
+ fi
+ if ! [[ "$ELECTRON_BUILD_RUN_ID" =~ ^[1-9][0-9]*$ ]]; then
+ echo 'Provide electron_build_run_id from a successful build desktop Electron workflow.' >&2
+ exit 1
+ fi
+ if ! gh api "repos/$GITHUB_REPOSITORY/actions/runs/$ELECTRON_BUILD_RUN_ID" \
+ --jq 'select(.status == "completed" and .conclusion == "success" and .event == "workflow_dispatch" and .head_branch == "main" and .repository.full_name != null and .head_repository.full_name == .repository.full_name and .path == ".github/workflows/build-desktop-electron.yaml") | .id' \
+ | grep -qx "$ELECTRON_BUILD_RUN_ID"; then
+ echo 'Use a successful manual build desktop Electron run from this repository on main.' >&2
+ exit 1
+ fi
+
- name: Set up Rust toolchain (CI helpers)
uses: dtolnay/rust-toolchain@02cb101ec7c40f2c49e1d9714d64511d8e1b74de
with:
@@ -613,12 +643,22 @@ jobs:
cargo run --locked --quiet --manifest-path ${{ github.workspace }}/_ci/tools/ci/Cargo.toml -- build-desktop
--step analyse_velopack_paths
+ - name: Download patched Electron distribution (Linux)
+ if: matrix.platform == 'linux'
+ uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093
+ with:
+ github-token: ${{ github.token }}
+ run-id: ${{ inputs.electron_build_run_id }}
+ name: desktop-electron-linux-${{ matrix.arch }}
+ path: ${{ runner.temp }}/fluxer-electron-dist
+
- name: Build Electron app (Linux)
if: matrix.platform == 'linux'
working-directory: ${{ env.WORKDIR }}/fluxer_desktop
env:
BUILD_CHANNEL: ${{ env.BUILD_CHANNEL }}
USE_SYSTEM_FPM: true
+ FLUXER_ELECTRON_DIST: ${{ runner.temp }}/fluxer-electron-dist
run: >-
cargo run --locked --quiet --manifest-path ${{ github.workspace }}/_ci/tools/ci/Cargo.toml -- build-desktop
--step build_app_linux
diff --git a/fluxer_desktop/electron-builder.config.cjs b/fluxer_desktop/electron-builder.config.cjs
index 7a598126d..648adfe1b 100644
--- a/fluxer_desktop/electron-builder.config.cjs
+++ b/fluxer_desktop/electron-builder.config.cjs
@@ -63,7 +63,22 @@ if (!channel) {
const isCanary = buildChannel === 'canary';
const isStable = buildChannel === 'stable';
-const isLinuxBuild = process.argv.includes('--linux');
+const platformArguments = new Set(process.argv.map((argument) => argument.split('=', 1)[0]));
+const linuxRequested = ['--linux', '-l'].some((selector) => platformArguments.has(selector));
+const macRequested = ['--mac', '--macos', '-m', '-o'].some((selector) => platformArguments.has(selector));
+const windowsRequested = ['--win', '--windows', '-w'].some((selector) => platformArguments.has(selector));
+const targetPlatform = linuxRequested
+ ? 'linux'
+ : macRequested
+ ? 'darwin'
+ : windowsRequested
+ ? 'win32'
+ : process.platform;
+const isLinuxBuild = targetPlatform === 'linux';
+const customLinuxElectron =
+ isLinuxBuild && process.env.FLUXER_ELECTRON_DIST?.trim() ? require('./scripts/custom-electron.cjs') : null;
+const linuxElectronDist = customLinuxElectron?.resolveLinuxElectronDist() ?? null;
+const verifiedLinuxElectronArtifacts = new Map();
const productName = channel.productName;
const linuxOptDirName = channel.linuxOptDirName;
const installedProductName = isLinuxBuild ? linuxOptDirName : productName;
@@ -99,9 +114,6 @@ const legacyLinuxCanaryOptDir = '/opt/Fluxer Canary';
const legacyLinuxOptDirSweepScript = path.resolve(__dirname, 'packaging/linux/rpm-post-transaction.sh');
const legacyLinuxOptDirRpmFpmArgs = isCanary ? ['--rpm-posttrans', legacyLinuxOptDirSweepScript] : [];
const macOSMinimumSystemVersion = '13.0';
-const isMacBuild = process.argv.includes('--mac');
-const isWindowsBuild = process.argv.includes('--win');
-const targetPlatform = isLinuxBuild ? 'linux' : isMacBuild ? 'darwin' : isWindowsBuild ? 'win32' : process.platform;
const metadataName = isLinuxBuild ? linuxPackageName : packageName;
const shellVersion = process.env.VERSION || readBundledRendererVersion();
const supportedTargetArchs = ['x64', 'arm64'];
@@ -797,6 +809,27 @@ async function verifyNativePackageInputs(context) {
await verifyDarwinNativeArchitectures(platform, arch, entries, 'before packaging');
}
+async function beforePack(context) {
+ if (linuxElectronDist && context.electronPlatformName !== 'linux') {
+ throw new Error(
+ 'The patched Linux Electron distribution cannot package other platforms. Use separate electron-builder invocations for Linux and macOS or Windows.',
+ );
+ }
+ if (context.electronPlatformName === 'linux') {
+ if (!linuxElectronDist) {
+ throw new Error(
+ 'Linux packaging requires patched Electron. Set FLUXER_ELECTRON_DIST to the directory containing its ZIP and build manifest.',
+ );
+ }
+ const arch = context.arch === 1 ? 'x64' : context.arch === 3 ? 'arm64' : context.arch;
+ verifiedLinuxElectronArtifacts.set(
+ arch,
+ await customLinuxElectron.verifyLinuxElectronArchive(linuxElectronDist, arch),
+ );
+ }
+ await verifyNativePackageInputs(context);
+}
+
async function verifyPackagedNativeArtifacts(context) {
const platform = context.electronPlatformName;
const arch = normalizeArch(context.arch);
@@ -1147,6 +1180,15 @@ async function readAsarEntry(asarPath, entryPath) {
}
async function afterPack(context) {
+ if (context.electronPlatformName === 'linux') {
+ if (!customLinuxElectron) {
+ throw new Error('Custom Electron was not configured before Linux packaging.');
+ }
+ await customLinuxElectron.verifyPackagedLinuxElectron(
+ path.join(context.appOutDir, linuxPackageName),
+ verifiedLinuxElectronArtifacts.get(normalizeArch(context.arch)),
+ );
+ }
await copyMissingPackagedNativeArtifacts(context);
await cleanupNativeBuildIntermediates(context);
await addLinuxLegacyBinarySymlink(context);
@@ -1613,6 +1655,9 @@ async function verifyLinuxArtifactContracts(buildResult) {
}
module.exports = {
+ ...(customLinuxElectron
+ ? {electronVersion: customLinuxElectron.expectedElectronVersion, electronDist: linuxElectronDist}
+ : {}),
appId,
productName: installedProductName,
copyright: 'Copyright © 2026 Fluxer Platform AB',
@@ -1732,7 +1777,7 @@ module.exports = {
schemes: [channel.protocolScheme],
},
],
- beforePack: verifyNativePackageInputs,
+ beforePack,
afterPack,
afterAllArtifactBuild: verifyLinuxArtifactContracts,
toolsets: {
diff --git a/fluxer_desktop/electron/build-linux.sh b/fluxer_desktop/electron/build-linux.sh
new file mode 100755
index 000000000..e535978ad
--- /dev/null
+++ b/fluxer_desktop/electron/build-linux.sh
@@ -0,0 +1,335 @@
+#!/usr/bin/env bash
+set -euo pipefail
+
+readonly ELECTRON_VERSION=44.4.1
+readonly ELECTRON_REVISION=09d1a6590e3148a1a2132b07a5b107b7c2414191
+readonly DEPOT_TOOLS_REVISION=889099791deff38466d471fa6590951c91a1d8ab
+readonly BUILD_IMAGE='ghcr.io/electron/build:daad061f4b99a0ae1c841be4aa09188280a9c8a4@sha256:7a161ad561103ebbfb5ff18eaf47cb579ca0c528bb7ec9ed8cad30a41d5fa63e'
+readonly PATCH_NAME=fix_synchronize_vaapi_surfaces_before_output.patch
+SCRIPT_DIR=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)
+readonly SCRIPT_DIR
+
+die() { printf 'Error: %s\n' "$*" >&2; exit 1; }
+
+usage() {
+ cat <<'USAGE'
+Build patched Electron 44.4.1 on a Linux x64 host with Podman or Docker.
+
+Usage: build-linux.sh [--arch x64|arm64|all] [--build-root PATH] [--output-dir PATH] [--check]
+
+--arch Target architecture; all builds x64 then arm64 (default: all).
+--build-root Dedicated persistent cache, source and output tree.
+ Default: ${XDG_CACHE_HOME:-$HOME/.cache}/fluxer/electron-44.4.1
+--output-dir Distribution ZIPs and .fluxer.json manifests (default: BUILD_ROOT/artifacts).
+--check Validate host resources and configuration without pulling or compiling.
+
+Requires at least 300 GiB free in the build filesystem. Recommended/default
+container memory is 48 GiB; use CONTAINER_MEMORY=32g for the lower-memory minimum.
+Available host RAM must cover the selected container limit.
+The build uses host networking and builds architectures sequentially.
+Optional environment: CONTAINER_ENGINE=podman|docker, CONTAINER_CPUS=8,
+CONTAINER_MEMORY=48g, CONTAINER_CPUSET=0-7, BUILD_JOBS=8.
+Without CONTAINER_CPUSET, CPU affinity is limited to the smaller CPU/job budget
+using CPUs permitted by the host. An explicit CPU set overrides that selection.
+The container runs as root; completed archives are returned to the invoking UID/GID.
+USAGE
+}
+
+inside_container() {
+ [[ ${FLUXER_ELECTRON_CONTAINER:-} == 1 && "$PWD" == /work ]] || die 'Internal container invocation is invalid.'
+ export DEPOT_TOOLS_UPDATE=0
+ export DEPOT_TOOLS_METRICS=0
+ export GIT_TERMINAL_PROMPT=0
+ export GIT_CACHE_PATH=/work/git-cache
+ export PATH="/work/depot_tools:$PATH"
+ local arch
+
+ checkout_pinned depot_tools https://chromium.googlesource.com/chromium/tools/depot_tools.git "$DEPOT_TOOLS_REVISION"
+ [[ -z $(git -C depot_tools status --porcelain --untracked-files=no) ]] || die 'Cached depot_tools contains tracked edits.'
+ DEPOT_TOOLS_DIR=/work/depot_tools /work/depot_tools/ensure_bootstrap
+ [[ -s depot_tools/python3_bin_reldir.txt ]] || die 'Pinned depot_tools Python bootstrap did not complete.'
+ depot_tools/python-bin/python3 --version
+
+ checkout_pinned src/electron https://github.com/electron/electron.git "$ELECTRON_REVISION"
+ python3 - "$SCRIPT_DIR/patches/$PATCH_NAME" "src/electron/patches/chromium/$PATCH_NAME" <<'PY'
+import pathlib
+import shutil
+import subprocess
+import sys
+
+source, destination = map(pathlib.Path, sys.argv[1:])
+allowed = {"patches/chromium/.patches", "patches/chromium/" + destination.name}
+changes = subprocess.check_output(
+ ["git", "-C", "src/electron", "status", "--porcelain=v1", "-z"], text=True
+).split("\0")
+for change in filter(None, changes):
+ if change[:2].strip() not in {"M", "??"} or change[3:] not in allowed:
+ raise SystemExit("Cached Electron has unrelated edits: " + repr(change))
+manifest = destination.parent / ".patches"
+upstream = subprocess.check_output(
+ ["git", "-C", "src/electron", "show", "HEAD:patches/chromium/.patches"]
+)
+patched = upstream.rstrip(b"\n") + b"\n" + destination.name.encode() + b"\n"
+if manifest.read_bytes() not in (upstream, patched):
+ raise SystemExit("Cached Chromium patch manifest differs from the pinned upstream series")
+shutil.copyfile(source, destination)
+manifest.write_bytes(patched)
+PY
+ gclient config --name src/electron --unmanaged --custom-var=checkout_arm64=True https://github.com/electron/electron
+ gclient sync --no-history --with_branch_heads --with_tags --jobs "$BUILD_JOBS"
+ git -C src apply --reverse --check "$SCRIPT_DIR/patches/$PATCH_NAME"
+ for arch in "$@"; do
+ python3 src/electron/script/pgo/download-profiles.py --targets "linux-$arch,v8-builtins"
+ (
+ cd src
+ gn gen "out/Release-$arch" --fail-on-unused-args --args="import(\"//electron/build/args/release.gn\") target_cpu=\"$arch\" override_electron_version=\"$ELECTRON_VERSION\" use_remoteexec=false"
+ python3 - "$arch" <<'PY'
+import json
+import subprocess
+import sys
+
+arch = sys.argv[1]
+arguments = json.loads(subprocess.check_output(
+ ["gn", "args", "out/Release-" + arch, "--list", "--short", "--json"], text=True
+))
+resolved = {
+ argument["name"]: argument.get("current", argument["default"])["value"]
+ for argument in arguments
+}
+expected = {
+ "target_cpu": json.dumps(arch),
+ "use_vaapi": "true",
+ "enable_platform_hevc": "true",
+ "enable_hevc_parser_and_hw_decoder": "true",
+}
+for name, value in expected.items():
+ if resolved.get(name) != value:
+ raise SystemExit(f"Electron build requires {name} = {value}; resolved {resolved.get(name)!r}")
+ print(f"Verified GN argument: {name} = {value}", flush=True)
+PY
+ autoninja -C "out/Release-$arch" -j "$BUILD_JOBS" electron:electron_dist_zip
+ python3 electron/script/zip_manifests/check-zip-manifest.py "out/Release-$arch/dist.zip" "electron/script/zip_manifests/dist_zip.linux.$arch.manifest"
+ )
+ python3 - "$arch" "$ELECTRON_VERSION" "$ELECTRON_REVISION" "$SCRIPT_DIR/patches/$PATCH_NAME" <<'PY'
+import hashlib
+import json
+import os
+import pathlib
+import shutil
+import struct
+import sys
+import tempfile
+import zipfile
+
+arch, version, revision, patch_name = sys.argv[1:]
+source = pathlib.Path("src/out/Release-" + arch + "/dist.zip")
+with zipfile.ZipFile(source) as archive:
+ if archive.testzip() is not None:
+ raise SystemExit("Built Electron ZIP has a corrupt member")
+ with archive.open("electron") as executable:
+ header = executable.read(64)
+ if len(header) != 64 or header[:6] != b"\x7fELF\x02\x01" or struct.unpack_from("<H", header, 18)[0] != {"x64": 62, "arm64": 183}[arch]:
+ raise SystemExit("Built Electron executable has the wrong ELF architecture")
+ marker = b"failed to synchronize VA surface before output"
+ tail = header
+ has_patch_marker = marker in header
+ while chunk := executable.read(1024 * 1024):
+ window = tail + chunk
+ has_patch_marker = has_patch_marker or marker in window
+ tail = window[-(len(marker) - 1):]
+ if not has_patch_marker:
+ raise SystemExit("Built Electron executable is missing the VA-API synchronization patch marker")
+ if archive.read("version").decode().strip() != version:
+ raise SystemExit("Built Electron version differs from the pinned version")
+
+def sha256(path):
+ digest = hashlib.sha256()
+ with open(path, "rb") as stream:
+ for chunk in iter(lambda: stream.read(1024 * 1024), b""):
+ digest.update(chunk)
+ return digest.hexdigest()
+
+output = pathlib.Path("/artifacts")
+name = "electron-v" + version + "-linux-" + arch
+archive_path = output / (name + ".zip")
+manifest_path = output / (name + ".fluxer.json")
+manifest = {
+ "schemaVersion": 1,
+ "electronVersion": version,
+ "electronRevision": revision,
+ "chromiumPatchSha256": sha256(patch_name),
+ "platform": "linux",
+ "arch": arch,
+ "archiveName": archive_path.name,
+ "archiveSha256": sha256(source),
+}
+for destination, contents in [(archive_path, None), (manifest_path, json.dumps(manifest, indent=2) + "\n")]:
+ descriptor, temporary = tempfile.mkstemp(prefix="." + destination.name + ".", dir=output)
+ try:
+ with os.fdopen(descriptor, "wb") as stream:
+ if contents is None:
+ with source.open("rb") as runtime:
+ shutil.copyfileobj(runtime, stream)
+ else:
+ stream.write(contents.encode())
+ os.chmod(temporary, 0o644)
+ os.chown(temporary, int(os.environ["FLUXER_HOST_UID"]), int(os.environ["FLUXER_HOST_GID"]))
+ os.replace(temporary, destination)
+ finally:
+ if os.path.exists(temporary):
+ os.unlink(temporary)
+print("Prepared " + str(archive_path) + " and " + str(manifest_path), flush=True)
+PY
+ done
+}
+
+checkout_pinned() {
+ local directory=$1 remote=$2 revision=$3 current
+ if [[ ! -d $directory/.git ]]; then
+ [[ ! -e $directory || -z $(ls -A "$directory") ]] || die "Source directory is not an empty Git checkout: $directory"
+ git init -q "$directory"
+ fi
+ if ! git -C "$directory" remote get-url origin >/dev/null 2>&1; then
+ git -C "$directory" remote add origin "$remote"
+ fi
+ [[ $(git -C "$directory" remote get-url origin) == "$remote" ]] || die "Cached Git remote differs: $directory"
+ if ! current=$(git -C "$directory" rev-parse --verify HEAD 2>/dev/null); then
+ git -C "$directory" fetch --depth=1 origin "$revision"
+ git -C "$directory" checkout --detach FETCH_HEAD
+ current=$(git -C "$directory" rev-parse HEAD)
+ fi
+ [[ $current == "$revision" ]] || die "Cached revision differs in $directory; choose a new build root."
+}
+
+if [[ ${1:-} == --inside-container ]]; then
+ shift
+ inside_container "$@"
+ exit
+fi
+
+ARCH=all
+BUILD_ROOT="${XDG_CACHE_HOME:-$HOME/.cache}/fluxer/electron-$ELECTRON_VERSION"
+OUTPUT_DIR=''
+CHECK_ONLY=0
+while (($#)); do
+ case $1 in
+ --arch|--build-root|--output-dir)
+ (($# >= 2)) || die "Missing value for $1"
+ case $1 in
+ --arch) ARCH=$2 ;;
+ --build-root) BUILD_ROOT=$2 ;;
+ --output-dir) OUTPUT_DIR=$2 ;;
+ esac
+ shift 2 ;;
+ --check) CHECK_ONLY=1; shift ;;
+ --help|-h) usage; exit ;;
+ *) die "Unknown argument: $1" ;;
+ esac
+done
+case $ARCH in
+ all) ARCHES=(x64 arm64) ;;
+ x64|arm64) ARCHES=("$ARCH") ;;
+ *) die '--arch must be x64, arm64 or all.' ;;
+esac
+[[ $(uname -s) == Linux && $(uname -m) == x86_64 ]] || die 'Build on a Linux x64 host; macOS and emulated Linux builds are unsupported.'
+for command in python3 flock; do command -v "$command" >/dev/null || die "Required command is unavailable: $command"; done
+if [[ -z ${CONTAINER_ENGINE:-} ]]; then
+ if command -v podman >/dev/null; then CONTAINER_ENGINE=podman; else CONTAINER_ENGINE=docker; fi
+fi
+case $CONTAINER_ENGINE in podman|docker) ;; *) die 'CONTAINER_ENGINE must be podman or docker.' ;; esac
+command -v "$CONTAINER_ENGINE" >/dev/null || die "Required container engine is unavailable: $CONTAINER_ENGINE"
+BUILD_JOBS=${BUILD_JOBS:-8}
+CONTAINER_CPUS=${CONTAINER_CPUS:-8}
+CONTAINER_MEMORY=${CONTAINER_MEMORY:-48g}
+[[ $BUILD_JOBS =~ ^[1-9][0-9]*$ ]] || die 'BUILD_JOBS must be a positive integer.'
+[[ $CONTAINER_CPUS =~ ^[1-9][0-9]*$ ]] || die 'CONTAINER_CPUS must be a positive integer.'
+CONTAINER_CPUSET=$(python3 - "$CONTAINER_CPUS" "$BUILD_JOBS" "${CONTAINER_CPUSET:-}" <<'PY'
+import os
+import re
+import sys
+
+allowed = sorted(os.sched_getaffinity(0))
+if not allowed:
+ raise SystemExit("No CPUs are permitted by the host affinity")
+explicit = sys.argv[3]
+if explicit:
+ if not re.fullmatch(r"[0-9]+(?:-[0-9]+)?(?:,[0-9]+(?:-[0-9]+)?)*", explicit):
+ raise SystemExit("CONTAINER_CPUSET must be a comma-separated CPU list or ranges, e.g. 0-7,9")
+ requested = set()
+ for part in explicit.split(","):
+ bounds = [int(value) for value in part.split("-")]
+ first, last = bounds[0], bounds[-1]
+ if first > last or last > allowed[-1]:
+ raise SystemExit("CONTAINER_CPUSET contains an invalid or unavailable CPU range: " + part)
+ requested.update(range(first, last + 1))
+ unavailable = requested.difference(allowed)
+ if unavailable:
+ raise SystemExit("CONTAINER_CPUSET includes CPUs outside the host affinity: " + ",".join(map(str, sorted(unavailable))))
+ print(explicit)
+else:
+ budget = min(int(sys.argv[1]), int(sys.argv[2]), len(allowed))
+ print(",".join(map(str, allowed[:budget])))
+PY
+)
+
+BUILD_ROOT=$(python3 -c 'import pathlib,sys; print(pathlib.Path(sys.argv[1]).expanduser().resolve())' "$BUILD_ROOT")
+OUTPUT_DIR=${OUTPUT_DIR:-$BUILD_ROOT/artifacts}
+OUTPUT_DIR=$(python3 -c 'import pathlib,sys; print(pathlib.Path(sys.argv[1]).expanduser().resolve())' "$OUTPUT_DIR")
+python3 - "$BUILD_ROOT" "$CONTAINER_MEMORY" "$CONTAINER_CPUS" <<'PY'
+import os
+import pathlib
+import re
+import shutil
+import sys
+
+root = pathlib.Path(sys.argv[1])
+if root == pathlib.Path("/") or root == pathlib.Path.home():
+ raise SystemExit("Choose a dedicated build root, not / or your home directory")
+probe = root
+while not probe.exists():
+ probe = probe.parent
+free = shutil.disk_usage(probe).free / 2**30
+if free < 300:
+ raise SystemExit(f"Build filesystem has {free:.1f} GiB free; at least 300 GiB is required")
+memory = dict(line.split(":", 1) for line in pathlib.Path("/proc/meminfo").read_text().splitlines())
+total = int(memory["MemTotal"].split()[0]) * 1024
+available = int(memory["MemAvailable"].split()[0]) * 1024
+match = re.fullmatch(r"([1-9][0-9]*)([mgMG])", sys.argv[2])
+if not match:
+ raise SystemExit("CONTAINER_MEMORY must use whole megabytes or gigabytes, e.g. 48g")
+limit = int(match[1]) * {"m": 2**20, "g": 2**30}[match[2].lower()]
+if total < 31 * 2**30 or limit < 32 * 2**30 or available < limit:
+ raise SystemExit(f"Insufficient RAM: host {total / 2**30:.1f} GiB total, {available / 2**30:.1f} GiB available, container limit {limit / 2**30:.1f} GiB; need at least a 32 GiB container limit and available RAM covering that limit")
+if int(sys.argv[3]) > (os.cpu_count() or 1):
+ raise SystemExit("CONTAINER_CPUS exceeds the host's logical CPU count")
+print(f"Host ready: {free:.1f} GiB free, {available / 2**30:.1f} GiB available RAM; container limit {limit / 2**30:.1f} GiB", flush=True)
+PY
+"$CONTAINER_ENGINE" info >/dev/null
+printf 'Engine: %s\nImage: %s\nBuild root: %s\nOutput: %s\nTargets: %s\nCPU set: %s\n' "$CONTAINER_ENGINE" "$BUILD_IMAGE" "$BUILD_ROOT" "$OUTPUT_DIR" "${ARCHES[*]}" "$CONTAINER_CPUSET"
+((CHECK_ONLY == 0)) || exit
+
+if [[ -d $BUILD_ROOT && ! -f $BUILD_ROOT/.fluxer-electron-build-id && -n $(ls -A "$BUILD_ROOT") ]]; then
+ die 'Build root is not empty and has no ownership marker; choose a dedicated empty directory.'
+fi
+mkdir -p "$BUILD_ROOT" "$OUTPUT_DIR"
+exec 9>"$BUILD_ROOT/.fluxer-electron-build.lock"
+flock -n 9 || die 'Another build is using this build root.'
+if [[ -f $BUILD_ROOT/.fluxer-electron-build-id ]]; then
+ [[ $(cat "$BUILD_ROOT/.fluxer-electron-build-id") == "$ELECTRON_REVISION" ]] || die 'Build root belongs to a different Electron revision.'
+else
+ printf '%s\n' "$ELECTRON_REVISION" > "$BUILD_ROOT/.fluxer-electron-build-id"
+fi
+mkdir -p "$BUILD_ROOT/container-home" "$BUILD_ROOT/git-cache"
+ENGINE_ARGS=(run --rm --platform linux/amd64 --user 0 --network host --workdir /work --cpus "$CONTAINER_CPUS" --cpuset-cpus "$CONTAINER_CPUSET" --memory "$CONTAINER_MEMORY")
+ENGINE_ARGS+=(
+ --volume "$BUILD_ROOT:/work"
+ --volume "$OUTPUT_DIR:/artifacts"
+ --volume "$BUILD_ROOT/container-home:/root"
+ --volume "$SCRIPT_DIR:/fluxer-electron:ro"
+ --env FLUXER_ELECTRON_CONTAINER=1
+ --env "FLUXER_HOST_UID=$(id -u)"
+ --env "FLUXER_HOST_GID=$(id -g)"
+ --env "BUILD_JOBS=$BUILD_JOBS"
+)
+"$CONTAINER_ENGINE" pull "$BUILD_IMAGE"
+"$CONTAINER_ENGINE" "${ENGINE_ARGS[@]}" "$BUILD_IMAGE" bash /fluxer-electron/build-linux.sh --inside-container "${ARCHES[@]}"
diff --git a/fluxer_desktop/electron/patches/fix_synchronize_vaapi_surfaces_before_output.patch b/fluxer_desktop/electron/patches/fix_synchronize_vaapi_surfaces_before_output.patch
new file mode 100644
index 000000000..f64725c2d
--- /dev/null
+++ b/fluxer_desktop/electron/patches/fix_synchronize_vaapi_surfaces_before_output.patch
@@ -0,0 +1,78 @@
+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
+From: Fluxer <[email protected]>
+Date: Sat, 17 Oct 2026 14:10:46 +0000
+Subject: fix: synchronize VA-API surfaces before output
+
+diff --git a/media/gpu/vaapi/vaapi_video_decoder.cc b/media/gpu/vaapi/vaapi_video_decoder.cc
+--- a/media/gpu/vaapi/vaapi_video_decoder.cc
++++ b/media/gpu/vaapi/vaapi_video_decoder.cc
+@@ -223,6 +223,7 @@
+ transcryption_ = false;
+
+ SetState(State::kUninitialized);
++ surface_sync_failed_ = false;
+ }
+ DCHECK(!current_decode_task_);
+ DCHECK(decode_task_queue_.empty());
+@@ -404,6 +405,11 @@
+ {
+ TRACE_EVENT("media,gpu", "VaapiVideoDecoder::Decode");
+ decode_result = decoder_->Decode();
++ }
++ if (surface_sync_failed_) {
++ SetState({DecoderStatus::Codes::kFailed,
++ "failed to synchronize VA surface before output"});
++ return;
+ }
+ switch (decode_result) {
+ case AcceleratedVideoDecoder::kRanOutOfStreamData:
+@@ -559,6 +565,10 @@
+ DVLOGF(4);
+ DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
+ DCHECK_EQ(state_, State::kDecoding);
++ if (surface_sync_failed_) {
++ return;
++ }
++
+ CHECK_NE(va_surface_id, VA_INVALID_SURFACE);
+
+ // Find the timestamp associated with |buffer_id|. It's possible that a
+@@ -624,6 +634,11 @@
+ gfx::HDRMetadata hdr_metadata = static_hdr_metadata_;
+ hdr_metadata.MergeMetadataFrom(dynamic_hdr_metadata);
+ frame->set_hdr_metadata(hdr_metadata);
++
++ if (!vaapi_wrapper_->SyncSurface(va_surface_id)) {
++ surface_sync_failed_ = true;
++ return;
++ }
+ output_cb_.Run(std::move(frame));
+ }
+
+@@ -1045,7 +1060,13 @@
+
+ // Flush will block until SurfaceReady() has been called for every frame
+ // currently decoding.
+- if (!decoder_->Flush()) {
++ const bool flush_succeeded = decoder_->Flush();
++ if (surface_sync_failed_) {
++ SetState({DecoderStatus::Codes::kFailed,
++ "failed to synchronize VA surface before output"});
++ return;
++ }
++ if (!flush_succeeded) {
+ SetState({DecoderStatus::Codes::kFailed, "Failed to flush the decoder"});
+ return;
+ }
+diff --git a/media/gpu/vaapi/vaapi_video_decoder.h b/media/gpu/vaapi/vaapi_video_decoder.h
+--- a/media/gpu/vaapi/vaapi_video_decoder.h
++++ b/media/gpu/vaapi/vaapi_video_decoder.h
+@@ -211,6 +211,8 @@
+ // The video decoder's state.
+ State state_ GUARDED_BY_CONTEXT(sequence_checker_) = State::kUninitialized;
+
++ bool surface_sync_failed_ GUARDED_BY_CONTEXT(sequence_checker_) = false;
++
+ // Callback used to notify the client when a frame is available for output.
+ PipelineOutputCB output_cb_ GUARDED_BY_CONTEXT(sequence_checker_);
+
diff --git a/fluxer_desktop/scripts/custom-electron.cjs b/fluxer_desktop/scripts/custom-electron.cjs
new file mode 100644
index 000000000..95db5dc4b
--- /dev/null
+++ b/fluxer_desktop/scripts/custom-electron.cjs
@@ -0,0 +1,138 @@
+const {execFile} = require('node:child_process');
+const {createHash} = require('node:crypto');
+const {createReadStream, statSync} = require('node:fs');
+const fs = require('node:fs/promises');
+const path = require('node:path');
+const {promisify} = require('node:util');
+
+const execFileAsync = promisify(execFile);
+const expectedElectronVersion = '44.4.1';
+const expectedElectronRevision = '09d1a6590e3148a1a2132b07a5b107b7c2414191';
+const chromiumPatchPath = path.join(
+ __dirname,
+ '../electron/patches/fix_synchronize_vaapi_surfaces_before_output.patch',
+);
+
+function resolveLinuxElectronDist() {
+ const configuredDirectory = process.env.FLUXER_ELECTRON_DIST?.trim();
+ if (!configuredDirectory) {
+ throw new Error(
+ 'Linux packaging requires patched Electron. Set FLUXER_ELECTRON_DIST to the directory containing the custom Electron ZIP and its .fluxer.json build manifest.',
+ );
+ }
+ const directory = path.resolve(configuredDirectory);
+ if (!statSync(directory, {throwIfNoEntry: false})?.isDirectory()) {
+ throw new Error(`FLUXER_ELECTRON_DIST is not a directory: ${directory}`);
+ }
+ return directory;
+}
+
+async function sha256File(filePath) {
+ const hash = createHash('sha256');
+ for await (const chunk of createReadStream(filePath)) hash.update(chunk);
+ return hash.digest('hex');
+}
+
+const inspectArchive = `
+import hashlib, json, stat, struct, sys, zipfile
+archive_path, arch, version = sys.argv[1:]
+with zipfile.ZipFile(archive_path) as archive:
+ for required in ('electron', 'version', 'LICENSE', 'LICENSES.chromium.html'):
+ matches = [entry for entry in archive.infolist() if entry.filename == required]
+ if len(matches) != 1 or matches[0].is_dir() or stat.S_ISLNK(matches[0].external_attr >> 16):
+ raise ValueError('Expected one regular ZIP entry: ' + required)
+ if archive.read('version').decode('utf-8').strip() != version:
+ raise ValueError('Electron ZIP version does not match ' + version)
+ with archive.open('electron') as executable:
+ header = executable.read(20)
+ if len(header) != 20 or header[:6] != b'\\x7fELF\\x02\\x01':
+ raise ValueError('Electron must be a 64-bit little-endian ELF executable')
+ if struct.unpack_from('<H', header, 18)[0] != {'x64': 62, 'arm64': 183}[arch]:
+ raise ValueError('Electron ELF architecture does not match ' + arch)
+ digest = hashlib.sha256(header)
+ marker = b'failed to synchronize VA surface before output'
+ tail = header
+ has_patch_marker = marker in header
+ while chunk := executable.read(1024 * 1024):
+ digest.update(chunk)
+ window = tail + chunk
+ has_patch_marker = has_patch_marker or marker in window
+ tail = window[-(len(marker) - 1):]
+ if not has_patch_marker:
+ raise ValueError('Electron executable is missing the VA-API synchronization patch marker')
+print(json.dumps({'binarySha256': digest.hexdigest()}))
+`;
+
+async function verifyLinuxElectronArchive(directory, arch) {
+ if (!['x64', 'arm64'].includes(arch)) {
+ throw new Error(`Custom Linux Electron does not support architecture: ${arch}`);
+ }
+ const artifactName = `electron-v${expectedElectronVersion}-linux-${arch}`;
+ const archiveName = `${artifactName}.zip`;
+ const manifestPath = path.join(directory, `${artifactName}.fluxer.json`);
+ let manifest;
+ try {
+ manifest = JSON.parse(await fs.readFile(manifestPath, 'utf8'));
+ } catch (error) {
+ throw new Error(`Cannot read custom Electron build manifest ${manifestPath}: ${error.message}`);
+ }
+ const expectedFields = {
+ schemaVersion: 1,
+ electronVersion: expectedElectronVersion,
+ electronRevision: expectedElectronRevision,
+ platform: 'linux',
+ arch,
+ archiveName,
+ };
+ for (const [field, expected] of Object.entries(expectedFields)) {
+ if (manifest?.[field] !== expected) {
+ throw new Error(`Custom Electron manifest ${field} must be ${JSON.stringify(expected)}: ${manifestPath}`);
+ }
+ }
+ const patchSha256 = await sha256File(chromiumPatchPath);
+ const acceptedPatchSha256s = new Set([patchSha256]);
+ if (patchSha256 === '21ea23b8a566f3f2dbdb69d0b361039dd9128c5e34a7ae89a8a61d7099808b8e') {
+ acceptedPatchSha256s.add('d39d05d4a00cd09eca43c7cd83383eaefa18cae7ec1b7efc26987bdc0f23c83e');
+ }
+ if (!acceptedPatchSha256s.has(manifest?.chromiumPatchSha256)) {
+ throw new Error(`Custom Electron manifest chromiumPatchSha256 does not match the current patch: ${manifestPath}`);
+ }
+ if (!/^[a-f0-9]{64}$/.test(manifest.archiveSha256)) {
+ throw new Error(`Custom Electron manifest has no valid archiveSha256: ${manifestPath}`);
+ }
+ const archivePath = path.join(directory, archiveName);
+ if ((await sha256File(archivePath)) !== manifest.archiveSha256) {
+ throw new Error(`Custom Electron ZIP checksum does not match its build manifest: ${archivePath}`);
+ }
+ let inspection;
+ try {
+ const {stdout} = await execFileAsync(
+ 'python3',
+ ['-c', inspectArchive, archivePath, arch, expectedElectronVersion],
+ {
+ maxBuffer: 64 * 1024,
+ },
+ );
+ inspection = JSON.parse(stdout);
+ } catch (error) {
+ throw new Error(`Cannot verify custom Electron ZIP ${archivePath}: ${error.stderr?.trim() || error.message}`);
+ }
+ if (!/^[a-f0-9]{64}$/.test(inspection.binarySha256)) {
+ throw new Error(`Custom Electron ZIP inspection returned no executable checksum: ${archivePath}`);
+ }
+ return {manifest, binarySha256: inspection.binarySha256};
+}
+
+async function verifyPackagedLinuxElectron(executablePath, artifact) {
+ if (!artifact) throw new Error('Custom Electron archive was not verified before Linux packaging.');
+ if ((await sha256File(executablePath)) !== artifact.binarySha256) {
+ throw new Error(`Packaged Linux executable does not match the verified custom Electron build: ${executablePath}`);
+ }
+}
+
+module.exports = {
+ expectedElectronVersion,
+ resolveLinuxElectronDist,
+ verifyLinuxElectronArchive,
+ verifyPackagedLinuxElectron,
+};
diff --git a/fluxer_desktop/src/main/ChromiumRuntime.ts b/fluxer_desktop/src/main/ChromiumRuntime.ts
index 7bdd7ea56..1275a3ddf 100644
--- a/fluxer_desktop/src/main/ChromiumRuntime.ts
+++ b/fluxer_desktop/src/main/ChromiumRuntime.ts
@@ -294,6 +294,11 @@ export function appendLinuxChromiumFlagsConfig(channel: BuildChannel): void {
}
}
+export function addLinuxHardwareVideoDecodeFeatures(features: Set<string>): void {
+ if (process.platform !== 'linux') return;
+ features.add('VaapiOnNvidiaGPUs');
+}
+
export function addLinuxHardwareVideoEncodeFeatures(features: Set<string>): void {
if (process.platform !== 'linux') return;
features.add('AcceleratedVideoEncoder');
diff --git a/fluxer_desktop/src/main/PreReadyChromium.ts b/fluxer_desktop/src/main/PreReadyChromium.ts
index d3c6fd445..b5ac56295 100644
--- a/fluxer_desktop/src/main/PreReadyChromium.ts
+++ b/fluxer_desktop/src/main/PreReadyChromium.ts
@@ -7,6 +7,7 @@ import {
getDesktopWindowBehaviorSettings,
} from '@electron/common/DesktopConfig';
import {
+ addLinuxHardwareVideoDecodeFeatures,
addLinuxHardwareVideoEncodeFeatures,
addWindowsHardwareVideoEncodeFeatures,
appendConfiguredChromiumSwitches,
@@ -53,6 +54,7 @@ export function applyPreReadyChromiumConfiguration(channel: BuildChannel, argv:
const disabledChromiumFeatures = new Set(BASE_DISABLED_CHROMIUM_FEATURES);
const enabledChromiumFeatures = new Set<string>();
if (!disableHardwareAcceleration) {
+ addLinuxHardwareVideoDecodeFeatures(enabledChromiumFeatures);
addLinuxHardwareVideoEncodeFeatures(enabledChromiumFeatures);
addWindowsHardwareVideoEncodeFeatures(enabledChromiumFeatures);
}