mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-11-22 06:15:58 +00:00
Merge remote-tracking branch 'origin/main' into fix/pr-1174-gog-installer
# Conflicts: # app/src/main/java/com/droiddeck/launcher/stores/gog/GogBackend.kt # app/src/main/java/com/droiddeck/launcher/stores/gog/GogDownloadManager.java
This commit is contained in:
commit
6cbf8f4d73
223 files changed
+7406
-1373
No files matched your search
+22
-1
@@ -12,7 +12,18 @@ else
|
||||
export DROIDDECK_BUILD_TREE_STATE=unknown
|
||||
fi
|
||||
sdk_dir=${ANDROID_HOME:-${ANDROID_SDK_ROOT:-"${HOME}/Library/Android/sdk"}}
|
||||
java_dir=${JAVA_HOME:-"/opt/homebrew/opt/openjdk@17/libexec/openjdk.jdk/Contents/Home"}
|
||||
java_dir="${JAVA_HOME:-/opt/homebrew/opt/openjdk@17/libexec/openjdk.jdk/Contents/Home}"
|
||||
[[ -x "$java_dir/bin/java" ]] || {
|
||||
mise_java="$(mise -C "${repo_root}" which java 2>/dev/null)"
|
||||
if [[ -n "$mise_java" ]]; then
|
||||
mise_home="$(dirname "$mise_java")"
|
||||
[[ "$mise_home" == */bin ]] && mise_home="$(dirname "$mise_home")"
|
||||
[[ -x "$mise_home/bin/java" ]] && java_dir="$mise_home"
|
||||
fi
|
||||
}
|
||||
[[ -x "$java_dir/bin/java" ]] || java_dir="${HOME}/.local/share/mise/installs/java/temurin-17"
|
||||
[[ "$java_dir" == */homebrew/* ]] && echo "using homebrew java path: $java_dir"
|
||||
[[ "$java_dir" == */mise/* ]] && echo "using mise java path: $java_dir"
|
||||
image_name=${DROIDDECK_BUILD_IMAGE:-droiddeck-local-cross:24.04-v3}
|
||||
build_variant=${DROIDDECK_BUILD_VARIANT:-release}
|
||||
case "$build_variant" in
|
||||
@@ -278,6 +289,16 @@ docker run --rm --platform linux/amd64 --user "$(id -u):$(id -g)" -v "${repo_roo
|
||||
mkdir -p "${linuxfs_dir}/usr/local/bin"
|
||||
install -m644 "${repo_root}/tools/mangoapp/mangoapp" "${linuxfs_dir}/usr/local/bin/mangoapp"
|
||||
|
||||
pw_pkgs="${staging_dir}/pw-pkgs"
|
||||
mkdir -p "${pw_pkgs}"
|
||||
while read -r package_sha256 package_url; do
|
||||
[[ -n "${package_url}" ]] || continue
|
||||
package_archive=$(cached "${package_sha256}" "$(basename "${package_url}")" \
|
||||
bash -c 'curl -fsSL --retry 3 -o "$out" "$0"' "${package_url}")
|
||||
zstd -dc "${package_archive}" | tar -xf - -C "${pw_pkgs}"
|
||||
done < <(grep -v '^#' "${repo_root}/tools/pipewire/packages.txt")
|
||||
"${repo_root}/tools/pipewire/assemble.sh" "${pw_pkgs}" "${linuxfs_dir}/usr/local/lib/droiddeck-pipewire.tzst"
|
||||
|
||||
pa_source=${DROIDDECK_PA13_SOURCE_DIR:-"${staging_dir}/pulseaudio-13.0"}
|
||||
if [[ -z "${DROIDDECK_PA13_SOURCE_DIR:-}" ]]; then
|
||||
pa_tarball="${cache_dir}/pulseaudio-13.0.tar.gz"
|
||||
|
||||
@@ -56,6 +56,13 @@ library list, before anything is published.
|
||||
own limiter slips such a frame by one refresh. The fixed-refresh branch now paces each window by
|
||||
time, as the VRR branch already did: its next frame goes out on the first refresh a capped interval
|
||||
after its last one, with half a refresh of tolerance so an on-time window keeps every Nth refresh.
|
||||
- `0116-hold-overlay-repaint-for-next-frame.patch` - this app: on a fixed-refresh output every
|
||||
mangoapp commit asked for a repaint of its own, and mangoapp draws once per game frame just after
|
||||
that frame was shown, so a 60 fps game on a 120 Hz panel was composited twice per frame - 75 frames
|
||||
a second reached the screen, one in two 8 ms after the last with no new picture (Valheim, Stardew
|
||||
Valley, Among Us). The VRR path already leaves such repaints to the next game frame; on a fixed
|
||||
refresh output they now wait for it too, for at most `external_overlay_hold_cycles` refreshes (4,
|
||||
so 30 fps at 120 Hz still merges), and are painted on their own after that.
|
||||
|
||||
Sixteen more of Armada's patches are DRM/lease/HDR-on-KMS work for a native display, which this
|
||||
app's Wayland-hosted gamescope never reaches, or need a newer gamescope than the runtime has.
|
||||
@@ -0,0 +1,64 @@
|
||||
diff --git a/src/steamcompmgr.cpp b/src/steamcompmgr.cpp
|
||||
index 214677d..6c9299d 100644
|
||||
--- a/src/steamcompmgr.cpp
|
||||
+++ b/src/steamcompmgr.cpp
|
||||
@@ -298,6 +298,7 @@ update_runtime_info();
|
||||
gamescope::ConVar<bool> cv_adaptive_sync( "adaptive_sync", false, "Whether or not adaptive sync is enabled if available." );
|
||||
gamescope::ConVar<bool> cv_adaptive_sync_ignore_overlay( "adaptive_sync_ignore_overlay", false, "Whether or not to ignore overlay planes for pushing commits with adaptive sync." );
|
||||
gamescope::ConVar<int> cv_adaptive_sync_overlay_cycles( "adaptive_sync_overlay_cycles", 1, "Number of vblank cycles to ignore overlay repaints before forcing a commit with adaptive sync." );
|
||||
+gamescope::ConVar<int> cv_external_overlay_hold_cycles( "external_overlay_hold_cycles", 4, "Number of vblank cycles an external overlay's repaint waits for the next base plane commit on a fixed refresh output, 0 repaints at once." );
|
||||
gamescope::ConVar<bool> cv_adaptive_sync_uncapped( "adaptive_sync_uncapped", true, "Whether or not to allow mailbox/immediate clients to run uncapped with adaptive sync by deferring paints until the display can take a new flip." );
|
||||
|
||||
gamescope::ConVar<bool> cv_upscale_preemptive( "upscale_preemptive", true, "Allow pre-emptive upscaling" );
|
||||
@@ -1119,6 +1120,7 @@ uint32_t lastPublishedInputCounter;
|
||||
|
||||
std::atomic<bool> hasRepaint = false;
|
||||
bool hasRepaintNonBasePlane = false;
|
||||
+bool hasRepaintExternalOverlay = false;
|
||||
|
||||
bool g_bUpdateForwardedVROverlays = false;
|
||||
|
||||
@@ -8015,7 +8017,10 @@ bool handle_done_commit( steamcompmgr_win_t *w, xwayland_ctx_t *ctx, uint64_t co
|
||||
if ( ( w == pFocus->externalOverlayWindow && w->opacity != TRANSLUCENT ) &&
|
||||
( GetBackend()->GetCurrentConnector() && !GetBackend()->GetCurrentConnector()->IsVRRActive() ) )
|
||||
{
|
||||
- hasRepaintNonBasePlane = true;
|
||||
+ if ( cv_external_overlay_hold_cycles > 0 )
|
||||
+ hasRepaintExternalOverlay = true;
|
||||
+ else
|
||||
+ hasRepaintNonBasePlane = true;
|
||||
}
|
||||
|
||||
// If this is the main plane, repaint
|
||||
@@ -10573,6 +10578,14 @@ steamcompmgr_main(int argc, char **argv)
|
||||
hasRepaint = true;
|
||||
|
||||
bool bPainted = false;
|
||||
+ bool bPaintedOutput = false;
|
||||
+
|
||||
+ static int nHeldExternalOverlayCycles = 0;
|
||||
+
|
||||
+ if ( !hasRepaintExternalOverlay )
|
||||
+ nHeldExternalOverlayCycles = 0;
|
||||
+ else if ( vblank && ++nHeldExternalOverlayCycles >= cv_external_overlay_hold_cycles )
|
||||
+ hasRepaintNonBasePlane = true;
|
||||
|
||||
static int nIgnoredOverlayRepaints = 0;
|
||||
|
||||
@@ -10733,6 +10746,7 @@ steamcompmgr_main(int argc, char **argv)
|
||||
paint_all( pPaintFocus, eFlipType == FlipType::Async );
|
||||
|
||||
bPainted = true;
|
||||
+ bPaintedOutput = true;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10751,6 +10765,8 @@ steamcompmgr_main(int argc, char **argv)
|
||||
|
||||
hasRepaint = false;
|
||||
hasRepaintNonBasePlane = false;
|
||||
+ if ( bPaintedOutput )
|
||||
+ hasRepaintExternalOverlay = false;
|
||||
nIgnoredOverlayRepaints = 0;
|
||||
|
||||
{
|
||||
@@ -1,3 +1,3 @@
|
||||
GAMESCOPE_REPO=Droid-Deck/DroidDeck-Components
|
||||
GAMESCOPE_TAG=gamescope-3.16.29-cursor-045e5a31-qa
|
||||
GAMESCOPE_SHA256=76929e93804450e7352421b76a457c825a6251de8b704d942c363a211bd99424
|
||||
GAMESCOPE_TAG=gamescope-3.16.29-p12
|
||||
GAMESCOPE_SHA256=07b69944a1ebf2741d4a867afa6327dcc63ec458f432a8f7483089dce2197010
|
||||
@@ -1060,6 +1060,24 @@ def main(argv):
|
||||
return 3
|
||||
print("droiddeck-agent: Steam overview is ready for shortcut app %d" % prepared["appId"])
|
||||
return 0
|
||||
if argv and argv[0] == "--steam-supports-vr":
|
||||
if len(argv) != 2 or not argv[1].isascii() or not argv[1].isdecimal():
|
||||
print("usage: droiddeck-agent --steam-supports-vr <appid>", file=sys.stderr)
|
||||
return 2
|
||||
# Optional-VR games (Thumper, VRChat) carry vr_supported without vr_only.
|
||||
expression = ("(o => o ? (o.vr_supported === true || o.vr_only === true) : null)"
|
||||
"(window.appStore?.GetAppOverviewByGameID?.(%s))" % json.dumps(argv[1]))
|
||||
value = None
|
||||
deadline = time.monotonic() + 12 # Steam's UI is busiest while a game starts.
|
||||
while value is None and time.monotonic() < deadline:
|
||||
try:
|
||||
value = cdp_eval(Path(base) / "agent", expression, await_promise=False, timeout=8).get("value")
|
||||
except (AgentError, OSError, ValueError):
|
||||
pass
|
||||
if value is None:
|
||||
time.sleep(0.5)
|
||||
print({True: "yes", False: "no"}.get(value, "unknown"))
|
||||
return {True: 0, False: 5}.get(value, 1)
|
||||
if argv and argv[0] == "--steam-asleep":
|
||||
expression = """(() => {
|
||||
const store = globalThis.SuspendResumeStore;
|
||||
|
||||
@@ -17,7 +17,7 @@ if [ -s /etc/ld.so.preload ]; then
|
||||
export LD_PRELOAD="${preload%:}${LD_PRELOAD:+:$LD_PRELOAD}" SHARUN_ALLOW_LD_PRELOAD=1
|
||||
fi
|
||||
flags=()
|
||||
if [ -e "$APPDIR/chrome-sandbox" ] || compgen -G "$APPDIR/*/chrome-sandbox" >/dev/null; then
|
||||
if [ -n "$(find -H "$APPDIR" -maxdepth 4 \( -name chrome-sandbox -o -name chrome_100_percent.pak -o -name v8_context_snapshot.bin \) -print -quit 2>/dev/null)" ]; then
|
||||
flags+=(--no-sandbox)
|
||||
if [ -n "${DISPLAY:-}" ]; then
|
||||
export XDG_SESSION_TYPE=x11
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
#!/usr/bin/python3
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
@@ -308,17 +309,118 @@ def mark_install_scripts(command, env):
|
||||
starts - on first launch the shared ones may still be downloading, and on ARM64 Proton the VC++
|
||||
ones stop with an error."""
|
||||
if not any(arg.lower().replace("\\", "/").endswith("iscriptevaluator.exe") for arg in command):
|
||||
return
|
||||
return []
|
||||
root = env.get("BL_X64_STEAM_ROOT") or env.get("STEAM_COMPAT_CLIENT_INSTALL_PATH") or str(Path.home() / ".local/share/Steam")
|
||||
scripts = [str(Path(root) / arg.replace("\\", "/")) for arg in command if EVALUATOR_SCRIPT.search(arg)]
|
||||
scripts = [path for path in scripts if os.path.isfile(path)]
|
||||
if not scripts:
|
||||
return
|
||||
return []
|
||||
try:
|
||||
subprocess.run([SEED_REDISTS, root], env=dict(env, DROIDDECK_SEED_SCRIPTS="\n".join(scripts)),
|
||||
stdout=sys.stderr, timeout=60, check=False)
|
||||
except (OSError, subprocess.SubprocessError) as error:
|
||||
print("droiddeck-game-env: install scripts not marked (%s)" % error, file=sys.stderr)
|
||||
return scripts
|
||||
|
||||
|
||||
INSTALL_STAMP = ".droiddeck-install-scripts"
|
||||
VDF_TOKEN = re.compile(r'"((?:[^"\\]|\\.)*)"|([{}])')
|
||||
|
||||
|
||||
def read_vdf(text):
|
||||
tokens = iter(VDF_TOKEN.findall(text))
|
||||
|
||||
def block():
|
||||
items = []
|
||||
for word, brace in tokens:
|
||||
if brace == "}":
|
||||
return items
|
||||
if brace:
|
||||
raise ValueError("a block without a name")
|
||||
value, opens = next(tokens, ("", "}"))
|
||||
if opens == "}":
|
||||
raise ValueError("a name without a value")
|
||||
items.append((re.sub(r"\\(.)", r"\1", word), block() if opens else re.sub(r"\\(.)", r"\1", value)))
|
||||
return items
|
||||
|
||||
return block()
|
||||
|
||||
|
||||
def run_keys(items, appid=""):
|
||||
appid = next((value for name, value in items if name.lower() == "appid" and isinstance(value, str)), appid)
|
||||
found = set()
|
||||
for name, value in items:
|
||||
if not isinstance(value, list):
|
||||
continue
|
||||
if any(isinstance(v, str) and re.fullmatch(r"process [0-9]+", n.lower()) for n, v in value):
|
||||
key = next((v for n, v in value if n.lower() == "hasrunkey" and isinstance(v, str)),
|
||||
"HKEY_LOCAL_MACHINE\\Software\\Valve\\Steam\\Apps\\" + appid)
|
||||
found.add((key.lower(), name.lower()))
|
||||
found |= run_keys(value, appid)
|
||||
return found
|
||||
|
||||
|
||||
def registry_values(path):
|
||||
found, section = set(), None
|
||||
with open(path, encoding="utf-8", errors="replace") as reg:
|
||||
for line in reg:
|
||||
if line.startswith("["):
|
||||
section = line[1:line.find("]")].replace("\\\\", "\\").lower() if "]" in line else None
|
||||
elif section and line.startswith('"') and '"=' in line:
|
||||
found.add((section, line[1:line.index('"=')].replace("\\\\", "\\").lower()))
|
||||
return found
|
||||
|
||||
|
||||
def has_run(key, value, values):
|
||||
path = key[len("hkey_local_machine\\"):] if key.startswith("hkey_local_machine\\") else None
|
||||
if path is None:
|
||||
return False
|
||||
views = [path]
|
||||
if path.startswith("software\\"):
|
||||
views.append("software\\wow6432node\\" + path[len("software\\"):])
|
||||
return any((view, value) in values for view in views)
|
||||
|
||||
|
||||
def scripts_digest(scripts):
|
||||
digest = hashlib.sha256()
|
||||
for path in sorted(scripts):
|
||||
digest.update(os.path.basename(path).encode() + b"\0")
|
||||
digest.update(Path(path).read_bytes())
|
||||
return digest.hexdigest()
|
||||
|
||||
|
||||
def install_scripts_done(scripts, env):
|
||||
prefix = Path(env.get("STEAM_COMPAT_DATA_PATH", "/nonexistent")) / "pfx"
|
||||
try:
|
||||
if (prefix / INSTALL_STAMP).read_text().strip() != scripts_digest(scripts):
|
||||
return False
|
||||
keys = set()
|
||||
for path in scripts:
|
||||
keys |= run_keys(read_vdf(Path(path).read_text(encoding="utf-8", errors="replace")))
|
||||
values = registry_values(prefix / "system.reg")
|
||||
except (OSError, ValueError):
|
||||
return False
|
||||
return bool(keys) and all(has_run(key, value, values) for key, value in keys)
|
||||
|
||||
|
||||
def record_install_scripts(digest, env):
|
||||
prefix = Path(env.get("STEAM_COMPAT_DATA_PATH", "/nonexistent")) / "pfx"
|
||||
try:
|
||||
if prefix.is_dir():
|
||||
staged = prefix / (INSTALL_STAMP + ".tmp")
|
||||
staged.write_text(digest + "\n")
|
||||
staged.replace(prefix / INSTALL_STAMP)
|
||||
except OSError as error:
|
||||
print("droiddeck-game-env: install scripts not recorded (%s)" % error, file=sys.stderr)
|
||||
|
||||
|
||||
def start(launch, launch_env, digest):
|
||||
if digest:
|
||||
code = subprocess.run(launch, env=launch_env, check=False).returncode
|
||||
if code == 0:
|
||||
record_install_scripts(digest, launch_env)
|
||||
return code
|
||||
return os.execvpe(launch[0], launch, launch_env)
|
||||
|
||||
|
||||
def main():
|
||||
@@ -327,7 +429,14 @@ def main():
|
||||
return 2
|
||||
env = game_gpu(os.environ.copy())
|
||||
mic_enabled = env.get("BL_MIC_ENABLED")
|
||||
mark_install_scripts(command, env)
|
||||
scripts = mark_install_scripts(command, env)
|
||||
if scripts and install_scripts_done(scripts, env):
|
||||
print("droiddeck-game-env: install scripts already run in this prefix; evaluator skipped", file=sys.stderr)
|
||||
return 0
|
||||
try:
|
||||
digest = scripts_digest(scripts) if scripts else None
|
||||
except OSError:
|
||||
digest = None
|
||||
app_id = game_id(env)
|
||||
if app_id:
|
||||
waiting = len(command) > 1 and command[1] == "waitforexitandrun"
|
||||
@@ -376,12 +485,12 @@ def main():
|
||||
launch, launch_env = select_sync(command, env, sync)
|
||||
if launch[0] != command[0]:
|
||||
try:
|
||||
os.execvpe(launch[0], launch, launch_env)
|
||||
return start(launch, launch_env, digest)
|
||||
except OSError as error:
|
||||
print("droiddeck-game-env: %s could not start (%s); stock launch" % (launch[0], error), file=sys.stderr)
|
||||
launch, launch_env = command, without_pack(launch_env, env)
|
||||
record_stock(sync, launch, launch_env)
|
||||
os.execvpe(launch[0], launch, launch_env)
|
||||
return start(launch, launch_env, digest)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
+62
@@ -0,0 +1,62 @@
|
||||
#!/bin/sh
|
||||
# Audio stays on the session's PulseAudio, so WirePlumber runs its upstream video-only profile.
|
||||
set -u
|
||||
|
||||
bundle=/usr/local/lib/droiddeck-pipewire.tzst
|
||||
dir=/usr/local/lib/droiddeck-pipewire
|
||||
state=${XDG_RUNTIME_DIR:-/tmp}/droiddeck-pipewire
|
||||
|
||||
client_env() {
|
||||
echo "export PIPEWIRE_CONFIG_DIR=$dir/share/pipewire PIPEWIRE_MODULE_DIR=$dir/lib/pipewire-0.3 SPA_PLUGIN_DIR=$dir/lib/spa-0.2"
|
||||
}
|
||||
|
||||
unpack() {
|
||||
[ -f "$bundle" ] || { echo "droiddeck-pipewire: $bundle is missing" >&2; return 1; }
|
||||
sum=$(cksum < "$bundle")
|
||||
[ "$(cat "$dir/.bundle" 2>/dev/null)" = "$sum" ] && return 0
|
||||
rm -rf "$dir.new" && mkdir -p "$dir.new" &&
|
||||
zstd -dc "$bundle" | tar -xf - -C "$dir.new" &&
|
||||
printf '%s\n' "$sum" > "$dir.new/.bundle" &&
|
||||
rm -rf "$dir" && mv "$dir.new" "$dir" ||
|
||||
{ rm -rf "$dir.new"; echo "droiddeck-pipewire: could not unpack $bundle" >&2; return 1; }
|
||||
}
|
||||
|
||||
stop() {
|
||||
for pid in $(cat "$state/pids" 2>/dev/null); do kill "$pid" 2>/dev/null; done
|
||||
rm -f "$state/pids"
|
||||
}
|
||||
|
||||
case "${1:-}" in
|
||||
env)
|
||||
client_env
|
||||
;;
|
||||
start)
|
||||
unpack || exit 1
|
||||
stop
|
||||
mkdir -p "$state"
|
||||
eval "$(client_env)"
|
||||
export LD_LIBRARY_PATH=$dir/lib${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}
|
||||
export WIREPLUMBER_MODULE_DIR=$dir/lib/wireplumber-0.5 WIREPLUMBER_CONFIG_DIR=$dir/share/wireplumber \
|
||||
WIREPLUMBER_DATA_DIR=$dir/share/wireplumber
|
||||
socket=${XDG_RUNTIME_DIR:-/tmp}/pipewire-0
|
||||
rm -f "$socket" "$socket.lock" "$socket-manager" "$socket-manager.lock"
|
||||
"$dir/bin/pipewire" < /dev/null &
|
||||
echo $! > "$state/pids"
|
||||
i=0
|
||||
while [ ! -S "$socket" ]; do
|
||||
i=$((i + 1))
|
||||
[ "$i" -le 50 ] || { echo "droiddeck-pipewire: pipewire did not open $socket" >&2; stop; exit 1; }
|
||||
sleep 0.1
|
||||
done
|
||||
"$dir/bin/wireplumber" --profile video-only < /dev/null &
|
||||
echo $! >> "$state/pids"
|
||||
echo "droiddeck-pipewire: pipewire and wireplumber (video-only) up at $socket"
|
||||
;;
|
||||
stop)
|
||||
stop
|
||||
;;
|
||||
*)
|
||||
echo "usage: droiddeck-pipewire env|start|stop" >&2
|
||||
exit 2
|
||||
;;
|
||||
esac
|
||||
@@ -96,14 +96,14 @@ done <<<"$pairs"
|
||||
want+=("vcrt"$'\t'"$VCRT_MAJOR.$VCRT_MINOR.$VCRT_BUILD")
|
||||
|
||||
printf -v now '%(%s)T' -1
|
||||
block_for() { printf '%s\n' "$@" | awk -F'\t' -v now="$now" '
|
||||
block_for() { printf '%s\n' "$@" | awk -F'\t' -v now="$now" -v hive="$hive" '
|
||||
{
|
||||
path = $1
|
||||
sub(/^HKEY_LOCAL_MACHINE\\\\/, "", path)
|
||||
sub(/^HKEY_(LOCAL_MACHINE|CURRENT_USER)\\\\/, "", path)
|
||||
if (path == $1)
|
||||
next
|
||||
printf "\n[%s] %d\n\"%s\"=dword:00000001\n", path, now, $2
|
||||
if (substr(path, 1, 10) != "Software\\\\")
|
||||
if (hive != "HKEY_LOCAL_MACHINE" || substr(path, 1, 10) != "Software\\\\")
|
||||
next
|
||||
printf "\n[%s] %d\n\"%s\"=dword:00000001\n", "Software\\\\Wow6432Node\\\\" substr(path, 11), now, $2
|
||||
}
|
||||
@@ -115,16 +115,17 @@ block_for() { printf '%s\n' "$@" | awk -F'\t' -v now="$now" '
|
||||
unseed() {
|
||||
local reg=$1 out
|
||||
shift
|
||||
out=$(mktemp "${reg%/*}/.system.reg.XXXXXX") || return 1
|
||||
if printf '%s\n' "$@" | awk -F'\t' '
|
||||
[ -w "$reg" ] || return 1
|
||||
out=$(mktemp "${reg%/*}/.${reg##*/}.XXXXXX") || return 1
|
||||
if printf '%s\n' "$@" | awk -F'\t' -v hive="$hive" '
|
||||
NR == FNR {
|
||||
path = $1
|
||||
sub(/^HKEY_LOCAL_MACHINE\\\\/, "", path)
|
||||
sub(/^HKEY_(LOCAL_MACHINE|CURRENT_USER)\\\\/, "", path)
|
||||
if (path == $1)
|
||||
next
|
||||
path = tolower(path)
|
||||
drop["[" path "]" SUBSEP tolower($2)] = 1
|
||||
if (substr(path, 1, 10) == "software\\\\")
|
||||
if (hive == "HKEY_LOCAL_MACHINE" && substr(path, 1, 10) == "software\\\\")
|
||||
drop["[software\\\\wow6432node\\\\" substr(path, 11) "]" SUBSEP tolower($2)] = 1
|
||||
next
|
||||
}
|
||||
@@ -145,11 +146,11 @@ unseed() {
|
||||
|
||||
# The ledger lines whose values the registry still holds, in both views where we wrote both. A Proton
|
||||
# update replaces its default_pfx system.reg but not our ledger beside it, and new prefixes copy both.
|
||||
present() { awk -F'\t' '
|
||||
present() { awk -F'\t' -v hive="$hive" '
|
||||
NR == FNR {
|
||||
path = $1
|
||||
if (path != "vcrt") {
|
||||
sub(/^HKEY_LOCAL_MACHINE\\\\/, "", path)
|
||||
sub(/^HKEY_(LOCAL_MACHINE|CURRENT_USER)\\\\/, "", path)
|
||||
if (path == $1)
|
||||
next
|
||||
}
|
||||
@@ -163,7 +164,7 @@ present() { awk -F'\t' '
|
||||
key[n, ++need[n]] = "[software\\\\wow6432node\\\\" runtime "]" SUBSEP "installed"
|
||||
}
|
||||
} else {
|
||||
both = substr(path, 1, 10) == "Software\\\\"
|
||||
both = hive == "HKEY_LOCAL_MACHINE" && substr(path, 1, 10) == "Software\\\\"
|
||||
path = tolower(path)
|
||||
key[n, ++need[n]] = "[" path "]" SUBSEP tolower($2)
|
||||
if (both)
|
||||
@@ -200,60 +201,80 @@ for reg in "$steam_root"/steamapps/common/Proton*/files/share/default_pfx*/syste
|
||||
done
|
||||
declare -A regid=()
|
||||
if [ ${#regs[@]} -gt 0 ]; then
|
||||
users=()
|
||||
for reg in "${regs[@]}"; do users+=("${reg%/*}/user.reg"); done
|
||||
while IFS=$'\t' read -r id name; do
|
||||
regid[$name]=$id
|
||||
done < <(stat -c $'%i %s %.9Y\t%n' -- "${regs[@]}" 2>/dev/null)
|
||||
done < <(stat -c $'%i %s %.9Y\t%n' -- "${regs[@]}" "${users[@]}" 2>/dev/null)
|
||||
fi
|
||||
|
||||
for reg in "${regs[@]}"; do
|
||||
seeded=${reg%/*}/.droiddeck-redists
|
||||
checked=${reg%/*}/.droiddeck-redists-checked
|
||||
id=${regid[$reg]:-}
|
||||
for system in "${regs[@]}"; do
|
||||
user=${system%/*}/user.reg
|
||||
seeded=${system%/*}/.droiddeck-redists
|
||||
checked=${system%/*}/.droiddeck-redists-checked
|
||||
id="${regid[$system]:-}|${regid[$user]:-missing}"
|
||||
prev=
|
||||
[ -f "$checked" ] && read -r prev <"$checked"
|
||||
legacy=${reg%/*}/.bannerlator-redists
|
||||
legacy=${system%/*}/.bannerlator-redists
|
||||
if [ -f "$legacy" ] && [ ! -f "$seeded" ]; then
|
||||
mv -f "$legacy" "$seeded"
|
||||
fi
|
||||
declare -A had=()
|
||||
if [ -f "$seeded" ]; then
|
||||
while IFS= read -r line; do [[ $line == *$'\t'* ]] && had[$line]=1; done <"$seeded"
|
||||
fi
|
||||
stale=() kept=()
|
||||
for line in "${!had[@]}"; do
|
||||
if [ -n "${vulkan[$line]:-}" ]; then stale+=("$line"); else kept+=("$line"); fi
|
||||
done
|
||||
if [ ${#stale[@]} -gt 0 ] && unseed "$reg" "${stale[@]}"; then
|
||||
id=
|
||||
had=()
|
||||
for line in "${kept[@]}"; do had[$line]=1; done
|
||||
printf '%s\n' "${kept[@]}" >"$seeded"
|
||||
echo "== took Vulkan runtime markers out of $reg"
|
||||
fi
|
||||
if [ ${#had[@]} -gt 0 ] && { [ -z "$id" ] || [ "$id" != "$prev" ]; }; then
|
||||
declare -A held=()
|
||||
while IFS= read -r line; do [[ $line == *$'\t'* ]] && held[$line]=1; done < <(printf '%s\n' "${!had[@]}" | present "$reg")
|
||||
if [ ${#held[@]} -lt ${#had[@]} ]; then
|
||||
echo "== $((${#had[@]} - ${#held[@]})) recorded redist markers are gone from $reg"
|
||||
had=()
|
||||
for line in "${!held[@]}"; do had[$line]=1; done
|
||||
printf '%s\n' "${!had[@]}" >"$seeded"
|
||||
for reg in "$system" "$user"; do
|
||||
hive=HKEY_LOCAL_MACHINE
|
||||
[ "$reg" == "$user" ] && hive=HKEY_CURRENT_USER
|
||||
declare -A had=()
|
||||
other=()
|
||||
if [ -f "$seeded" ]; then
|
||||
while IFS= read -r line; do
|
||||
[[ $line == *$'\t'* ]] || continue
|
||||
if [[ $line == "$hive\\"* ]] || { [ "$reg" == "$system" ] && [[ $line == vcrt$'\t'* ]]; }; then
|
||||
had[$line]=1
|
||||
else
|
||||
other+=("$line")
|
||||
fi
|
||||
done <"$seeded"
|
||||
fi
|
||||
unset held
|
||||
fi
|
||||
missing=()
|
||||
for line in "${want[@]}"; do [ -n "${had[$line]:-}" ] || missing+=("$line"); done
|
||||
if [ ${#missing[@]} -eq 0 ]; then
|
||||
[ -n "$id" ] && [ "$id" != "$prev" ] && printf '%s\n' "$id" >"$checked"
|
||||
continue
|
||||
fi
|
||||
rm -f "$checked"
|
||||
dated=$(mktemp) || continue
|
||||
touch -r "$reg" "$dated"
|
||||
if printf '%s\n' "$(block_for "${missing[@]}")" >>"$reg"; then
|
||||
printf '%s\n' "${!had[@]}" "${missing[@]}" >"$seeded"
|
||||
echo "== seeded redist markers into $reg"
|
||||
fi
|
||||
touch -r "$dated" "$reg"
|
||||
rm -f "$dated"
|
||||
stale=() kept=()
|
||||
for line in "${!had[@]}"; do
|
||||
if [ -n "${vulkan[$line]:-}" ]; then stale+=("$line"); else kept+=("$line"); fi
|
||||
done
|
||||
if [ ${#stale[@]} -gt 0 ] && unseed "$reg" "${stale[@]}"; then
|
||||
id=
|
||||
had=()
|
||||
for line in "${kept[@]}"; do had[$line]=1; done
|
||||
printf '%s\n' "${other[@]}" "${kept[@]}" >"$seeded"
|
||||
echo "== took Vulkan runtime markers out of $reg"
|
||||
fi
|
||||
if [ ${#had[@]} -gt 0 ] && { [ -z "$id" ] || [ "$id" != "$prev" ]; }; then
|
||||
declare -A held=()
|
||||
while IFS= read -r line; do [[ $line == *$'\t'* ]] && held[$line]=1; done < <([ -f "$reg" ] && printf '%s\n' "${!had[@]}" | present "$reg")
|
||||
if [ ${#held[@]} -lt ${#had[@]} ]; then
|
||||
echo "== $((${#had[@]} - ${#held[@]})) recorded redist markers are gone from $reg"
|
||||
had=()
|
||||
for line in "${!held[@]}"; do had[$line]=1; done
|
||||
printf '%s\n' "${other[@]}" "${!had[@]}" >"$seeded"
|
||||
fi
|
||||
unset held
|
||||
fi
|
||||
missing=()
|
||||
for line in "${want[@]}"; do
|
||||
[[ $line == "$hive\\"* ]] || { [ "$reg" == "$system" ] && [[ $line == vcrt$'\t'* ]]; } || continue
|
||||
[ -n "${had[$line]:-}" ] || missing+=("$line")
|
||||
done
|
||||
if [ ${#missing[@]} -eq 0 ]; then
|
||||
[ -n "$id" ] && [ "$id" != "$prev" ] && printf '%s\n' "$id" >"$checked"
|
||||
continue
|
||||
fi
|
||||
[ -f "$reg" ] && [ -w "$reg" ] || continue
|
||||
rm -f "$checked"
|
||||
dated=$(mktemp) || continue
|
||||
touch -r "$reg" "$dated"
|
||||
if printf '%s\n' "$(block_for "${missing[@]}")" >>"$reg"; then
|
||||
printf '%s\n' "${other[@]}" "${!had[@]}" "${missing[@]}" >"$seeded"
|
||||
id=
|
||||
echo "== seeded redist markers into $reg"
|
||||
fi
|
||||
touch -r "$dated" "$reg"
|
||||
rm -f "$dated"
|
||||
done
|
||||
done
|
||||
@@ -134,6 +134,7 @@ export XDG_CONFIG_HOME=${XDG_CONFIG_HOME:-$HOME/.config}
|
||||
export XDG_CACHE_HOME=${XDG_CACHE_HOME:-$HOME/.cache}
|
||||
mkdir -p "$XDG_DATA_HOME" "$XDG_CONFIG_HOME" "$XDG_CACHE_HOME"
|
||||
rm -f "${XDG_RUNTIME_DIR:-/run/droiddeck}/droiddeck-steamvr/active"
|
||||
rm -f "${XDG_RUNTIME_DIR:-/run/droiddeck}/droiddeck-remote-play"
|
||||
/usr/local/bin/droiddeck-steamvr unregister >/dev/null 2>&1 || true
|
||||
if [ "$mode" = lxqt ] || [ "$mode" = desktop ]; then
|
||||
/usr/local/bin/droiddeck-desktop-bookmarks || true
|
||||
@@ -251,8 +252,15 @@ if [ -z "${BL_INSIDE:-}" ]; then
|
||||
fi
|
||||
export BL_INSIDE=1
|
||||
if [ "$mode" = steam ]; then
|
||||
if /usr/local/bin/droiddeck-pipewire start; then
|
||||
eval "$(/usr/local/bin/droiddeck-pipewire env)"
|
||||
else
|
||||
echo "== pipewire: not running; Remote Play and game recording have no picture"
|
||||
fi
|
||||
run_gamescope "${args[@]}" -- "$0" "$mode" "$@"
|
||||
exit $?
|
||||
_bl_status=$?
|
||||
/usr/local/bin/droiddeck-pipewire stop
|
||||
exit $_bl_status
|
||||
fi
|
||||
exec gamescope "${args[@]}" -- "$0" "$mode" "$@"
|
||||
fi
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
#!/bin/sh
|
||||
# Exit 0 when this game run should open as a SteamVR panel: SteamVR is running and Steam
|
||||
# lists no VR support for the app, optional or required. Under SteamVR, Steam stacks a flat game's window behind
|
||||
# its own, so without the panel the game plays unseen.
|
||||
[ "${1:-}" = waitforexitandrun ] || exit 1
|
||||
[ -z "${DROIDDECK_STEAMVR_PANEL:-}" ] || exit 1
|
||||
# Non-Steam shortcuts run with SteamAppId=0 and their CGameID in SteamGameId.
|
||||
app=${SteamAppId:-}
|
||||
[ "$app" = 0 ] && app=${SteamGameId:-}
|
||||
case $app in '' | 0 | *[!0-9]*) exit 1 ;; esac
|
||||
pgrep -x vrserver >/dev/null 2>&1 || exit 1
|
||||
/usr/local/bin/droiddeck-agent --steam-supports-vr "$app" >/dev/null 2>&1
|
||||
[ $? -eq 5 ]
|
||||
@@ -6,6 +6,8 @@ pgrep -x vrserver >/dev/null 2>&1 || {
|
||||
echo 'Start SteamVR before launching a game with droiddeck-steamvr-game.' >&2
|
||||
exit 1
|
||||
}
|
||||
# droiddeck-steamvr-flat skips a run that a launch option already wrapped.
|
||||
export DROIDDECK_STEAMVR_PANEL=1
|
||||
vrdir=${DROIDDECK_VR_DIR:-/usr/local/lib/droiddeck-vr}
|
||||
export VK_LAYER_PATH="$vrdir/layer${VK_LAYER_PATH:+:$VK_LAYER_PATH}"
|
||||
export VK_INSTANCE_LAYERS="VK_LAYER_DROIDDECK_vr${VK_INSTANCE_LAYERS:+:$VK_INSTANCE_LAYERS}"
|
||||
|
||||
@@ -74,6 +74,9 @@ bl_store_launch() {
|
||||
}
|
||||
|
||||
bl_run() {
|
||||
if [ -x /usr/local/bin/droiddeck-steamvr-flat ] && /usr/local/bin/droiddeck-steamvr-flat "${verb:-}"; then
|
||||
set -- /usr/local/bin/droiddeck-steamvr-game "$@"
|
||||
fi
|
||||
if [ -n "${BL_STORE_EXIT:-}" ]; then
|
||||
"$@"
|
||||
rc=$?
|
||||
@@ -262,6 +265,13 @@ bl_directaudio() {
|
||||
echo "droiddeck-proton: DirectAudio skipped for Steam's install-script evaluator" >&2
|
||||
return 0
|
||||
fi
|
||||
streamer=$(cat "${XDG_RUNTIME_DIR:-/tmp}/droiddeck-remote-play" 2>/dev/null)
|
||||
if [ -n "$streamer" ] && kill -0 "$streamer" 2>/dev/null; then
|
||||
WINE_AUDIO_DRIVER=pulse
|
||||
export WINE_AUDIO_DRIVER
|
||||
echo "droiddeck-proton: a Remote Play client is connected - game audio goes through PulseAudio so the stream carries it" >&2
|
||||
return 0
|
||||
fi
|
||||
version=$("$base/files/bin-arm64/wine" --version 2>/dev/null)
|
||||
major=${version#wine-}
|
||||
major=${major%%.*}
|
||||
@@ -456,7 +466,12 @@ verb=$1; shift
|
||||
case $verb in
|
||||
getcompatpath | getnativepath) printf '%s\\n' "$1"; exit 0 ;;
|
||||
esac
|
||||
exec /usr/local/bin/droiddeck-fex steam "$verb" "$@"
|
||||
""" + BL_GAME_CPUS_SETUP + """
|
||||
bl_game_cpus
|
||||
if [ -x /usr/local/bin/droiddeck-steamvr-flat ] && /usr/local/bin/droiddeck-steamvr-flat "$verb"; then
|
||||
exec /usr/local/bin/droiddeck-steamvr-game ${BL_TASKSET:-} /usr/local/bin/droiddeck-fex steam "$verb" "$@"
|
||||
fi
|
||||
exec ${BL_TASKSET:-} /usr/local/bin/droiddeck-fex steam "$verb" "$@"
|
||||
"""
|
||||
|
||||
|
||||
|
||||
@@ -617,9 +617,13 @@ int shm_unlink(const char *name) {
|
||||
return r;
|
||||
}
|
||||
|
||||
int bl_venc_mmap(void *addr, size_t len, int prot, int flags, int fd, off_t off,
|
||||
void *(*real)(void *, size_t, int, int, int, off_t), void **out) __attribute__((weak, visibility("hidden")));
|
||||
|
||||
void *mmap(void *addr, size_t len, int prot, int flags, int fd, off_t off) {
|
||||
void *p;
|
||||
if (!fs_real_mmap) fs_real_mmap = (void *(*)(void *, size_t, int, int, int, off_t))dlsym(RTLD_NEXT, "mmap");
|
||||
if (bl_venc_mmap && bl_venc_mmap(addr, len, prot, flags, fd, off, fs_real_mmap, &p)) return p;
|
||||
p = fs_real_mmap(addr, len, prot, flags, fd, off);
|
||||
if (p == MAP_FAILED && bl_noexec_retry(prot, flags, fd)) p = fs_real_mmap(addr, len, prot & ~PROT_EXEC, flags, fd, off);
|
||||
if (p != MAP_FAILED && __builtin_expect(fs_fd >= 0, 0)) fs_track(p, len, flags, fd, off);
|
||||
@@ -629,6 +633,8 @@ void *mmap(void *addr, size_t len, int prot, int flags, int fd, off_t off) {
|
||||
void *mmap64(void *addr, size_t len, int prot, int flags, int fd, off64_t off) {
|
||||
void *p;
|
||||
if (!fs_real_mmap64) fs_real_mmap64 = (void *(*)(void *, size_t, int, int, int, off64_t))dlsym(RTLD_NEXT, "mmap64");
|
||||
if (bl_venc_mmap && bl_venc_mmap(addr, len, prot, flags, fd, off, (void *(*)(void *, size_t, int, int, int, off_t))fs_real_mmap64, &p))
|
||||
return p;
|
||||
p = fs_real_mmap64(addr, len, prot, flags, fd, off);
|
||||
if (p == MAP_FAILED && bl_noexec_retry(prot, flags, fd)) p = fs_real_mmap64(addr, len, prot & ~PROT_EXEC, flags, fd, off);
|
||||
if (p != MAP_FAILED && __builtin_expect(fs_fd >= 0, 0)) fs_track(p, len, flags, fd, off);
|
||||
|
||||
@@ -406,6 +406,7 @@ int bl_kgsl_poll(int (*real)(int, unsigned long, void *), int fd, unsigned long
|
||||
void *arg, int *rc) __attribute__((visibility("hidden")));
|
||||
int bl_ntsync_ioctl(int fd, unsigned long request, void *arg, int *rc) __attribute__((visibility("hidden")));
|
||||
int bl_drm_gem_close(int fd, unsigned long request, void *arg, int *rc) __attribute__((visibility("hidden")));
|
||||
int bl_venc_ioctl(int fd, unsigned long request, void *arg, int *rc) __attribute__((visibility("hidden")));
|
||||
int bl_winebus_rumble_ioctl(int (*real)(int, unsigned long, void *), int fd, unsigned long request,
|
||||
void *arg, void *caller, int *rc) __attribute__((visibility("hidden")));
|
||||
|
||||
@@ -419,6 +420,7 @@ int ioctl(int fd, unsigned long request, ...) {
|
||||
|
||||
int rc;
|
||||
if (bl_ntsync_ioctl(fd, request, arg, &rc)) return rc;
|
||||
if (bl_venc_ioctl(fd, request, arg, &rc)) return rc;
|
||||
if (bl_drm_gem_close(fd, request, arg, &rc)) return rc;
|
||||
if (real == NULL) real = (ioctl_fn) dlsym(RTLD_NEXT, "ioctl");
|
||||
if (bl_winebus_rumble_ioctl(real, fd, request, arg, __builtin_return_address(0), &rc)) return rc;
|
||||
@@ -504,19 +506,55 @@ static void write_table(FILE *out, const char *table, const struct link *link) {
|
||||
}
|
||||
}
|
||||
|
||||
static const char *denied_table(const char *path) {
|
||||
static const char *const tables[] = { "route", "ipv6_route", "if_inet6", "dev", "arp" };
|
||||
#define CARRIER_TABLE 5
|
||||
|
||||
static const char *const net_tables[] = { "route", "ipv6_route", "if_inet6", "dev", "arp", "carrier" };
|
||||
static long long net_denied_at[sizeof(net_tables) / sizeof(net_tables[0])];
|
||||
|
||||
#define CARRIER_SLOTS 8
|
||||
|
||||
static struct { char path[64]; long long at; } carrier_denied[CARRIER_SLOTS];
|
||||
|
||||
static int denied_recently(int table, const char *path) {
|
||||
if (table != CARRIER_TABLE) return fresh(&net_denied_at[table]);
|
||||
int hit = 0;
|
||||
pthread_mutex_lock(&link_lock);
|
||||
for (int i = 0; i < CARRIER_SLOTS && !hit; i++) {
|
||||
hit = strcmp(carrier_denied[i].path, path) == 0 && fresh(&carrier_denied[i].at);
|
||||
}
|
||||
pthread_mutex_unlock(&link_lock);
|
||||
return hit;
|
||||
}
|
||||
|
||||
static void remember_denial(int table, const char *path) {
|
||||
if (table != CARRIER_TABLE) {
|
||||
__atomic_store_n(&net_denied_at[table], now_ns(), __ATOMIC_RELAXED);
|
||||
return;
|
||||
}
|
||||
if (strlen(path) >= sizeof(carrier_denied[0].path)) return;
|
||||
pthread_mutex_lock(&link_lock);
|
||||
int slot = 0;
|
||||
for (int i = 0; i < CARRIER_SLOTS; i++) {
|
||||
if (strcmp(carrier_denied[i].path, path) == 0) { slot = i; break; }
|
||||
if (carrier_denied[i].at < carrier_denied[slot].at) slot = i;
|
||||
}
|
||||
snprintf(carrier_denied[slot].path, sizeof(carrier_denied[slot].path), "%s", path);
|
||||
carrier_denied[slot].at = now_ns();
|
||||
pthread_mutex_unlock(&link_lock);
|
||||
}
|
||||
|
||||
static int denied_table(const char *path) {
|
||||
if (strncmp(path, "/proc/net/", 10) == 0) {
|
||||
for (size_t i = 0; i < sizeof(tables) / sizeof(tables[0]); i++) {
|
||||
if (strcmp(path + 10, tables[i]) == 0) return tables[i];
|
||||
for (int i = 0; i < CARRIER_TABLE; i++) {
|
||||
if (strcmp(path + 10, net_tables[i]) == 0) return i;
|
||||
}
|
||||
return NULL;
|
||||
return -1;
|
||||
}
|
||||
size_t len = strlen(path);
|
||||
if (strncmp(path, "/sys/class/net/", 15) == 0 && len > 8 && strcmp(path + len - 8, "/carrier") == 0) {
|
||||
return "carrier";
|
||||
return CARRIER_TABLE;
|
||||
}
|
||||
return NULL;
|
||||
return -1;
|
||||
}
|
||||
|
||||
static FILE *synthesize(const char *table) {
|
||||
@@ -548,11 +586,16 @@ static FILE *open_stream(fopen_fn real, const char *path, const char *mode, cons
|
||||
if (copy == NULL) close(status);
|
||||
return copy;
|
||||
}
|
||||
FILE *f = real(path, mode);
|
||||
if (f || path == NULL || mode == NULL || mode[0] != 'r') return f;
|
||||
int table = path && mode && mode[0] == 'r' ? denied_table(path) : -1;
|
||||
FILE *f;
|
||||
if (table >= 0 && denied_recently(table, path) && (f = synthesize(net_tables[table])) != NULL) return f;
|
||||
f = real(path, mode);
|
||||
if (f || table < 0) return f;
|
||||
int saved = errno;
|
||||
const char *table = denied_table(path);
|
||||
if (table && (f = synthesize(table)) != NULL) return f;
|
||||
if ((f = synthesize(net_tables[table])) != NULL) {
|
||||
if (saved == EACCES) remember_denial(table, path);
|
||||
return f;
|
||||
}
|
||||
errno = saved;
|
||||
return NULL;
|
||||
}
|
||||
|
||||
@@ -1253,9 +1253,11 @@ ssize_t recvmsg(int fd, struct msghdr *msg, int flags) {
|
||||
}
|
||||
|
||||
void bl_fsync_fds_closed(unsigned int first, unsigned int last) __attribute__((visibility("hidden")));
|
||||
void bl_venc_closed(int fd) __attribute__((visibility("hidden")));
|
||||
|
||||
int close(int fd) {
|
||||
if (fd >= 0) bl_fsync_fds_closed((unsigned int)fd, (unsigned int)fd);
|
||||
bl_venc_closed(fd);
|
||||
uint64_t *t = __atomic_load_n(&ns_fdt, __ATOMIC_ACQUIRE);
|
||||
if (t && fd >= 0 && fd < NS_FDS && __atomic_load_n(&t[fd], __ATOMIC_ACQUIRE)) ns_forget(fd);
|
||||
return ns_close_fd(fd);
|
||||
|
||||
@@ -14,6 +14,7 @@
|
||||
int bl_status_without_tracer(const char *path, int flags, const void *caller) __attribute__((visibility("hidden")));
|
||||
int bl_writable_retry(int dirfd, const char *path, int flags) __attribute__((visibility("hidden")));
|
||||
int bl_ntsync_open(const char *path, int flags) __attribute__((visibility("hidden")));
|
||||
int bl_venc_open(const char *path, int flags) __attribute__((visibility("hidden")));
|
||||
int bl_dircache_create(int dirfd, const char *path, int flags, mode_t mode,
|
||||
int (*real)(int, const char *, int, mode_t)) __attribute__((visibility("hidden")));
|
||||
|
||||
@@ -53,6 +54,7 @@ int open(const char *path, int flags, ...) {
|
||||
}
|
||||
if ((fd = bl_status_without_tracer(path, flags, __builtin_return_address(0))) >= 0) return fd;
|
||||
if ((fd = bl_ntsync_open(path, flags)) != -2) return fd;
|
||||
if ((fd = bl_venc_open(path, flags)) != -2) return fd;
|
||||
if (real_open == NULL) real_open = dlsym(RTLD_NEXT, "open");
|
||||
if (real_open == NULL) {
|
||||
errno = ENOSYS;
|
||||
@@ -78,6 +80,7 @@ int openat(int dirfd, const char *path, int flags, ...) {
|
||||
}
|
||||
if ((fd = bl_status_without_tracer(path, flags, __builtin_return_address(0))) >= 0) return fd;
|
||||
if ((fd = bl_ntsync_open(path, flags)) != -2) return fd;
|
||||
if ((fd = bl_venc_open(path, flags)) != -2) return fd;
|
||||
if (real_openat == NULL) real_openat = dlsym(RTLD_NEXT, "openat");
|
||||
if (real_openat == NULL) {
|
||||
errno = ENOSYS;
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
#include <errno.h>
|
||||
#include <fcntl.h>
|
||||
#include <limits.h>
|
||||
#include <link.h>
|
||||
#include <linux/futex.h>
|
||||
#include <linux/magic.h>
|
||||
#include <pthread.h>
|
||||
@@ -28,9 +29,11 @@
|
||||
|
||||
#ifdef SYS_newfstatat
|
||||
#define BL_SYS_FSTATAT SYS_newfstatat
|
||||
#define BL_FSTATAT_NAME "fstatat"
|
||||
typedef struct stat bl_stat;
|
||||
#else
|
||||
#define BL_SYS_FSTATAT SYS_fstatat64
|
||||
#define BL_FSTATAT_NAME "fstatat64"
|
||||
typedef struct stat64 bl_stat;
|
||||
#endif
|
||||
|
||||
@@ -43,6 +46,51 @@ struct bl_open_how {
|
||||
static long (*real_syscall)(long, ...);
|
||||
static void *(*real_dlopen)(const char *, int);
|
||||
static int openat2_missing;
|
||||
static int (*next_fstatat)(int, const char *, bl_stat *, int);
|
||||
static int (*next_openat)(int, const char *, int, ...);
|
||||
static ssize_t (*next_readlinkat)(int, const char *, char *, size_t);
|
||||
|
||||
static int find_fastpath(struct dl_phdr_info *info, size_t size, void *name) {
|
||||
(void)size;
|
||||
const char *slash = strrchr(info->dlpi_name, '/');
|
||||
if (!slash || strcmp(slash + 1, "libblfastpath.so") != 0 || strlen(info->dlpi_name) >= PATH_MAX) {
|
||||
return 0;
|
||||
}
|
||||
strcpy(name, info->dlpi_name);
|
||||
return 1;
|
||||
}
|
||||
|
||||
__attribute__((constructor)) static void find_fastpath_calls(void) {
|
||||
char name[PATH_MAX] = "";
|
||||
dl_iterate_phdr(find_fastpath, name);
|
||||
void *fastpath = *name ? dlopen(name, RTLD_NOLOAD | RTLD_LAZY) : NULL;
|
||||
if (fastpath) {
|
||||
next_fstatat = (int (*)(int, const char *, bl_stat *, int))dlsym(fastpath, BL_FSTATAT_NAME);
|
||||
next_openat = (int (*)(int, const char *, int, ...))dlsym(fastpath, "openat");
|
||||
next_readlinkat = (ssize_t (*)(int, const char *, char *, size_t))dlsym(fastpath, "readlinkat");
|
||||
}
|
||||
}
|
||||
|
||||
static long path_stat(int dirfd, const char *path, bl_stat *st, int flags) {
|
||||
if (!next_fstatat) {
|
||||
return real_syscall(BL_SYS_FSTATAT, (long)dirfd, (long)path, (long)st, (long)flags);
|
||||
}
|
||||
return next_fstatat(dirfd, path, st, flags);
|
||||
}
|
||||
|
||||
static long path_open(int dirfd, const char *path, int flags, long mode) {
|
||||
if (!next_openat) {
|
||||
return real_syscall(SYS_openat, (long)dirfd, (long)path, (long)flags, mode);
|
||||
}
|
||||
return next_openat(dirfd, path, flags, (mode_t)mode);
|
||||
}
|
||||
|
||||
static long path_readlink(int dirfd, const char *path, char *buf, size_t size) {
|
||||
if (!next_readlinkat) {
|
||||
return real_syscall(SYS_readlinkat, (long)dirfd, (long)path, (long)buf, (long)size);
|
||||
}
|
||||
return next_readlinkat(dirfd, path, buf, size);
|
||||
}
|
||||
|
||||
void *dlopen(const char *filename, int flags) {
|
||||
if (!real_dlopen) {
|
||||
@@ -93,7 +141,7 @@ static struct robust_list_head *thread_robust_head(void) {
|
||||
|
||||
// Magic links are procfs links below a process's directory; procfs's root holds only plain ones (self, thread-self, mounts).
|
||||
static int is_magic_link(int dirfd, char *link, size_t parent_len) {
|
||||
int fd = (int)real_syscall(SYS_openat, (long)dirfd, (long)link, (long)(O_PATH | O_NOFOLLOW | O_CLOEXEC), 0L);
|
||||
int fd = (int)path_open(dirfd, link, O_PATH | O_NOFOLLOW | O_CLOEXEC, 0L);
|
||||
if (fd < 0) {
|
||||
return 0;
|
||||
}
|
||||
@@ -106,7 +154,7 @@ static int is_magic_link(int dirfd, char *link, size_t parent_len) {
|
||||
char saved = link[parent_len];
|
||||
link[parent_len] = 0;
|
||||
bl_stat parent;
|
||||
long result = real_syscall(BL_SYS_FSTATAT, (long)dirfd, (long)(parent_len ? link : "."), (long)&parent, 0L);
|
||||
long result = path_stat(dirfd, (parent_len ? link : "."), &parent, 0);
|
||||
link[parent_len] = saved;
|
||||
return result != 0 || parent.st_ino != BL_PROC_ROOT_INO;
|
||||
}
|
||||
@@ -167,7 +215,7 @@ static long openat_in_root(int dirfd, const char *path, int flags, long mode) {
|
||||
resolved[candidate_len] = 0;
|
||||
bl_stat st;
|
||||
int follow = !last || trailing_slash || !nofollow;
|
||||
long stat_result = follow ? real_syscall(BL_SYS_FSTATAT, (long)dirfd, (long)resolved, (long)&st, (long)AT_SYMLINK_NOFOLLOW) : -1;
|
||||
long stat_result = follow ? path_stat(dirfd, resolved, &st, AT_SYMLINK_NOFOLLOW) : -1;
|
||||
if (stat_result == 0 && S_ISLNK(st.st_mode)) {
|
||||
if (++symlinks > BL_MAX_SYMLINKS) {
|
||||
errno = ELOOP;
|
||||
@@ -176,7 +224,7 @@ static long openat_in_root(int dirfd, const char *path, int flags, long mode) {
|
||||
if (!have_root) {
|
||||
bl_stat root;
|
||||
struct statfs root_fs;
|
||||
if (real_syscall(BL_SYS_FSTATAT, (long)dirfd, (long)".", (long)&root, 0L) != 0) {
|
||||
if (path_stat(dirfd, ".", &root, 0) != 0) {
|
||||
return -1;
|
||||
}
|
||||
root_dev = root.st_dev;
|
||||
@@ -195,7 +243,7 @@ static long openat_in_root(int dirfd, const char *path, int flags, long mode) {
|
||||
}
|
||||
char *tail = pending + PATH_MAX - rest_len - 1;
|
||||
memmove(tail, end, rest_len + 1);
|
||||
long target_len = real_syscall(SYS_readlinkat, (long)dirfd, (long)resolved, (long)pending, (long)(PATH_MAX - rest_len));
|
||||
long target_len = path_readlink(dirfd, resolved, pending, PATH_MAX - rest_len);
|
||||
if (target_len <= 0) {
|
||||
if (target_len == 0) {
|
||||
errno = ENOENT;
|
||||
@@ -215,11 +263,11 @@ static long openat_in_root(int dirfd, const char *path, int flags, long mode) {
|
||||
inside++;
|
||||
}
|
||||
bl_stat probe;
|
||||
int host = *inside && real_syscall(BL_SYS_FSTATAT, (long)dirfd, (long)inside, (long)&probe, (long)AT_SYMLINK_NOFOLLOW) != 0 &&
|
||||
errno == ENOENT && real_syscall(BL_SYS_FSTATAT, (long)AT_FDCWD, (long)pending, (long)&probe, 0L) == 0;
|
||||
int host = *inside && path_stat(dirfd, inside, &probe, AT_SYMLINK_NOFOLLOW) != 0 &&
|
||||
errno == ENOENT && path_stat(AT_FDCWD, pending, &probe, 0) == 0;
|
||||
pending[target_len] = saved;
|
||||
if (host) {
|
||||
return real_syscall(SYS_openat, (long)AT_FDCWD, (long)pending, (long)flags, mode);
|
||||
return path_open(AT_FDCWD, pending, flags, mode);
|
||||
}
|
||||
resolved_len = 0;
|
||||
}
|
||||
@@ -246,7 +294,7 @@ static long openat_in_root(int dirfd, const char *path, int flags, long mode) {
|
||||
resolved[resolved_len++] = '.';
|
||||
}
|
||||
resolved[resolved_len] = 0;
|
||||
return real_syscall(SYS_openat, (long)dirfd, (long)resolved, (long)flags, mode);
|
||||
return path_open(dirfd, resolved, flags, mode);
|
||||
}
|
||||
|
||||
static long openat2_via_openat(const long *args) {
|
||||
@@ -270,7 +318,7 @@ static long openat2_via_openat(const long *args) {
|
||||
errno = EXDEV;
|
||||
return -1;
|
||||
}
|
||||
return real_syscall(SYS_openat, args[0], (long)path, (long)(int)how->flags, (long)how->mode);
|
||||
return path_open((int)args[0], path, (int)how->flags, (long)how->mode);
|
||||
}
|
||||
|
||||
static int execveat_is_execve(const long *args) {
|
||||
@@ -316,6 +364,9 @@ long syscall(long number, ...) {
|
||||
}
|
||||
return openat2_via_openat(args);
|
||||
}
|
||||
if (number == SYS_openat) {
|
||||
return path_open((int)args[0], (const char *)args[1], (int)args[2], args[3]);
|
||||
}
|
||||
if (number == SYS_execveat && execveat_is_execve(args)) {
|
||||
return real_syscall(SYS_execve, args[1], args[2], args[3]);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
/* Steam's Linux Remote Play host has no touch injection: client touches arrive as an XTest mouse (absolute
|
||||
* motion plus button 1). While a stream holds the encoder, those become touches into gamescope's own touch
|
||||
* input, as a finger on the device screen would. */
|
||||
#define _GNU_SOURCE
|
||||
#include <dlfcn.h>
|
||||
#include <pthread.h>
|
||||
#include <stdint.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/socket.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include "../../../app/src/main/cpp/venc/venc_proto.h"
|
||||
|
||||
int bl_venc_streaming(void) __attribute__((visibility("hidden")));
|
||||
int bl_venc_connect(void) __attribute__((visibility("hidden")));
|
||||
|
||||
static pthread_mutex_t rt_lock = PTHREAD_MUTEX_INITIALIZER;
|
||||
static int rt_fd = -1, rt_down, rt_x, rt_y, rt_screen;
|
||||
|
||||
static int rt_enabled(void) {
|
||||
static int enabled = -1;
|
||||
if (enabled < 0) {
|
||||
const char *v = getenv("BL_REMOTE_TOUCH");
|
||||
enabled = v == NULL || strcmp(v, "0") != 0;
|
||||
}
|
||||
return enabled && bl_venc_streaming();
|
||||
}
|
||||
|
||||
static uint32_t rt_fraction(int value, int extent) {
|
||||
if (extent <= 1 || value <= 0) return 0;
|
||||
if (value >= extent - 1) return 65535;
|
||||
return (uint32_t)((int64_t)value * 65535 / (extent - 1));
|
||||
}
|
||||
|
||||
static void rt_send(void *dpy, uint32_t action) {
|
||||
static int (*width)(void *, int), (*height)(void *, int);
|
||||
if (!width) width = (int (*)(void *, int))dlsym(RTLD_DEFAULT, "XDisplayWidth");
|
||||
if (!height) height = (int (*)(void *, int))dlsym(RTLD_DEFAULT, "XDisplayHeight");
|
||||
if (!width || !height) return;
|
||||
struct venc_touch m = {
|
||||
.type = VENC_TOUCH, .action = action,
|
||||
.x = rt_fraction(rt_x, width(dpy, rt_screen)), .y = rt_fraction(rt_y, height(dpy, rt_screen)),
|
||||
};
|
||||
for (int attempt = 0; attempt < 2; attempt++) {
|
||||
if (rt_fd < 0) rt_fd = bl_venc_connect();
|
||||
if (rt_fd < 0) return;
|
||||
if (send(rt_fd, &m, sizeof m, MSG_NOSIGNAL) == (ssize_t)sizeof m) return;
|
||||
close(rt_fd);
|
||||
rt_fd = -1;
|
||||
}
|
||||
}
|
||||
|
||||
int XTestFakeMotionEvent(void *dpy, int screen, int x, int y, unsigned long delay) {
|
||||
static int (*real)(void *, int, int, int, unsigned long);
|
||||
if (!real) real = (int (*)(void *, int, int, int, unsigned long))dlsym(RTLD_NEXT, "XTestFakeMotionEvent");
|
||||
if (rt_enabled()) {
|
||||
pthread_mutex_lock(&rt_lock);
|
||||
rt_x = x;
|
||||
rt_y = y;
|
||||
rt_screen = screen < 0 ? 0 : screen;
|
||||
int down = rt_down;
|
||||
if (down) rt_send(dpy, VENC_TOUCH_MOVE);
|
||||
pthread_mutex_unlock(&rt_lock);
|
||||
if (down) return 1;
|
||||
}
|
||||
return real ? real(dpy, screen, x, y, delay) : 0;
|
||||
}
|
||||
|
||||
int XTestFakeButtonEvent(void *dpy, unsigned int button, int press, unsigned long delay) {
|
||||
static int (*real)(void *, unsigned int, int, unsigned long);
|
||||
if (!real) real = (int (*)(void *, unsigned int, int, unsigned long))dlsym(RTLD_NEXT, "XTestFakeButtonEvent");
|
||||
if (button == 1) {
|
||||
pthread_mutex_lock(&rt_lock);
|
||||
int handled = 0;
|
||||
if (press && rt_enabled()) {
|
||||
rt_down = 1;
|
||||
rt_send(dpy, VENC_TOUCH_DOWN);
|
||||
handled = 1;
|
||||
} else if (!press && rt_down) {
|
||||
rt_down = 0;
|
||||
rt_send(dpy, VENC_TOUCH_UP);
|
||||
handled = 1;
|
||||
}
|
||||
pthread_mutex_unlock(&rt_lock);
|
||||
if (handled) return 1;
|
||||
}
|
||||
return real ? real(dpy, button, press, delay) : 0;
|
||||
}
|
||||
@@ -403,6 +403,9 @@ struct msg_queue {
|
||||
struct { uint64_t seq; long mtype; size_t len; char data[2048]; } slot[MSG_SLOTS];
|
||||
};
|
||||
|
||||
struct msg_map { int id; int refs; struct msg_queue *q; };
|
||||
static struct msg_map g_msgs[MAX_OBJECTS];
|
||||
|
||||
static struct msg_queue *msg_map(int id) {
|
||||
int fd = open_by_id("msg", id);
|
||||
if (fd < 0) return NULL;
|
||||
@@ -415,6 +418,47 @@ static struct msg_queue *msg_map(int id) {
|
||||
return NULL;
|
||||
}
|
||||
|
||||
static int msg_removed(struct msg_queue *q) { return __atomic_load_n(&q->magic, __ATOMIC_ACQUIRE) != MSG_MAGIC; }
|
||||
|
||||
static struct msg_map *msg_get(int id) {
|
||||
struct msg_map *found = NULL, *spare = NULL, *idle = NULL;
|
||||
pthread_mutex_lock(&g_lock);
|
||||
for (int i = 0; i < MAX_OBJECTS; i++) {
|
||||
struct msg_map *e = &g_msgs[i];
|
||||
if (e->q && !e->refs && msg_removed(e->q)) {
|
||||
munmap(e->q, sizeof(*e->q));
|
||||
e->q = NULL;
|
||||
}
|
||||
if (!e->q) {
|
||||
if (!spare) spare = e;
|
||||
} else if (e->id == id && !msg_removed(e->q)) {
|
||||
found = e;
|
||||
} else if (!e->refs && !idle) {
|
||||
idle = e;
|
||||
}
|
||||
}
|
||||
if (!found && !spare && idle) {
|
||||
munmap(idle->q, sizeof(*idle->q));
|
||||
idle->q = NULL;
|
||||
spare = idle;
|
||||
}
|
||||
if (!found && spare && (spare->q = msg_map(id))) {
|
||||
spare->id = id;
|
||||
found = spare;
|
||||
} else if (!found && !spare) {
|
||||
errno = ENOSPC;
|
||||
}
|
||||
if (found) found->refs++;
|
||||
pthread_mutex_unlock(&g_lock);
|
||||
return found;
|
||||
}
|
||||
|
||||
static void msg_put(struct msg_map *m) {
|
||||
pthread_mutex_lock(&g_lock);
|
||||
m->refs--;
|
||||
pthread_mutex_unlock(&g_lock);
|
||||
}
|
||||
|
||||
static void msg_lock(struct msg_queue *q) {
|
||||
for (int32_t owner = 0; !atomic_compare_exchange_strong(&q->lock, &owner, getpid()); owner = 0) {
|
||||
if (kill(owner, 0) != 0 && errno == ESRCH) atomic_compare_exchange_strong(&q->lock, &owner, 0);
|
||||
@@ -446,12 +490,19 @@ int msgget(key_t key, int msgflg) {
|
||||
}
|
||||
|
||||
int msgsnd(int msqid, const void *msgp, size_t msgsz, int msgflg) {
|
||||
struct msg_queue *q = msg_map(msqid);
|
||||
if (!q) return -1;
|
||||
if (msgsz > sizeof(q->slot[0].data) || *(const long *)msgp < 1) { munmap(q, sizeof(*q)); errno = EINVAL; return -1; }
|
||||
struct msg_map *m = msg_get(msqid);
|
||||
if (!m) return -1;
|
||||
struct msg_queue *q = m->q;
|
||||
if (msgsz > sizeof(q->slot[0].data) || *(const long *)msgp < 1) { msg_put(m); errno = EINVAL; return -1; }
|
||||
for (;;) {
|
||||
msg_lock(q);
|
||||
int32_t seen = atomic_load(&q->changed);
|
||||
if (msg_removed(q)) {
|
||||
msg_unlock(q, 0);
|
||||
msg_put(m);
|
||||
errno = EIDRM;
|
||||
return -1;
|
||||
}
|
||||
for (int i = 0; i < MSG_SLOTS; i++) {
|
||||
if (q->slot[i].seq) continue;
|
||||
q->slot[i].mtype = *(const long *)msgp;
|
||||
@@ -459,12 +510,12 @@ int msgsnd(int msqid, const void *msgp, size_t msgsz, int msgflg) {
|
||||
memcpy(q->slot[i].data, (const long *)msgp + 1, msgsz);
|
||||
q->slot[i].seq = ++q->next_seq;
|
||||
msg_unlock(q, 1);
|
||||
munmap(q, sizeof(*q));
|
||||
msg_put(m);
|
||||
return 0;
|
||||
}
|
||||
msg_unlock(q, 0);
|
||||
if ((msgflg & IPC_NOWAIT) || (futex(&q->changed, FUTEX_WAIT, seen, NULL) != 0 && errno == EINTR)) {
|
||||
munmap(q, sizeof(*q));
|
||||
msg_put(m);
|
||||
if (msgflg & IPC_NOWAIT) errno = EAGAIN;
|
||||
return -1;
|
||||
}
|
||||
@@ -473,11 +524,18 @@ int msgsnd(int msqid, const void *msgp, size_t msgsz, int msgflg) {
|
||||
|
||||
ssize_t msgrcv(int msqid, void *msgp, size_t msgsz, long msgtyp, int msgflg) {
|
||||
if (msgtyp < 0) { errno = EINVAL; return -1; }
|
||||
struct msg_queue *q = msg_map(msqid);
|
||||
if (!q) return -1;
|
||||
struct msg_map *m = msg_get(msqid);
|
||||
if (!m) return -1;
|
||||
struct msg_queue *q = m->q;
|
||||
for (;;) {
|
||||
msg_lock(q);
|
||||
int32_t seen = atomic_load(&q->changed);
|
||||
if (msg_removed(q)) {
|
||||
msg_unlock(q, 0);
|
||||
msg_put(m);
|
||||
errno = EIDRM;
|
||||
return -1;
|
||||
}
|
||||
int best = -1;
|
||||
for (int i = 0; i < MSG_SLOTS; i++)
|
||||
if (q->slot[i].seq && (!msgtyp || q->slot[i].mtype == msgtyp) && (best < 0 || q->slot[i].seq < q->slot[best].seq))
|
||||
@@ -488,12 +546,12 @@ ssize_t msgrcv(int msqid, void *msgp, size_t msgsz, long msgtyp, int msgflg) {
|
||||
memcpy((long *)msgp + 1, q->slot[best].data, n);
|
||||
q->slot[best].seq = 0;
|
||||
msg_unlock(q, 1);
|
||||
munmap(q, sizeof(*q));
|
||||
msg_put(m);
|
||||
return (ssize_t)n;
|
||||
}
|
||||
msg_unlock(q, 0);
|
||||
if ((msgflg & IPC_NOWAIT) || (futex(&q->changed, FUTEX_WAIT, seen, NULL) != 0 && errno == EINTR)) {
|
||||
munmap(q, sizeof(*q));
|
||||
msg_put(m);
|
||||
if (msgflg & IPC_NOWAIT) errno = ENOMSG;
|
||||
return -1;
|
||||
}
|
||||
@@ -502,15 +560,28 @@ ssize_t msgrcv(int msqid, void *msgp, size_t msgsz, long msgtyp, int msgflg) {
|
||||
|
||||
int msgctl(int msqid, int cmd, struct msqid_ds *buf) {
|
||||
if (cmd != IPC_RMID) { errno = EINVAL; return -1; }
|
||||
struct msg_queue *q = msg_map(msqid);
|
||||
if (!q) return -1;
|
||||
pthread_mutex_lock(&g_lock);
|
||||
int rc = unlink_by_id("msg", msqid);
|
||||
pthread_mutex_unlock(&g_lock);
|
||||
int saved = errno;
|
||||
if (rc == 0) {
|
||||
__atomic_store_n(&q->magic, 0, __ATOMIC_SEQ_CST);
|
||||
atomic_fetch_add(&q->changed, 1);
|
||||
futex(&q->changed, FUTEX_WAKE, INT_MAX, NULL);
|
||||
}
|
||||
munmap(q, sizeof(*q));
|
||||
errno = saved;
|
||||
return rc;
|
||||
}
|
||||
|
||||
static void sysv_lock_before_fork(void) { pthread_mutex_lock(&g_lock); }
|
||||
static void sysv_unlock_after_fork(void) { pthread_mutex_unlock(&g_lock); }
|
||||
static void sysv_reset_after_fork(void) { pthread_mutex_init(&g_lock, NULL); }
|
||||
static void sysv_reset_after_fork(void) {
|
||||
pthread_mutex_init(&g_lock, NULL);
|
||||
for (int i = 0; i < MAX_OBJECTS; i++) g_msgs[i].refs = 0;
|
||||
}
|
||||
|
||||
__attribute__((constructor)) static void install_sysv_fork_handlers(void) {
|
||||
pthread_atfork(sysv_lock_before_fork, sysv_unlock_after_fork, sysv_reset_after_fork);
|
||||
|
||||
@@ -22,15 +22,17 @@ static const char *skip_digits(const char *s) {
|
||||
return end == s ? NULL : end;
|
||||
}
|
||||
|
||||
static int is_status_path(const char *path) {
|
||||
static long status_pid(const char *path) {
|
||||
const char *rest;
|
||||
if (path == NULL || strncmp(path, "/proc/", 6) != 0) return 0;
|
||||
long pid = 0;
|
||||
if (path == NULL || strncmp(path, "/proc/", 6) != 0) return -1;
|
||||
path += 6;
|
||||
if (strncmp(path, "self/", 5) == 0) rest = path + 4;
|
||||
else if (strncmp(path, "thread-self/", 12) == 0) rest = path + 11;
|
||||
else if ((rest = skip_digits(path)) == NULL) return 0;
|
||||
if (strncmp(rest, "/task/", 6) == 0 && (rest = skip_digits(rest + 6)) == NULL) return 0;
|
||||
return strcmp(rest, "/status") == 0;
|
||||
else if ((rest = skip_digits(path)) == NULL) return -1;
|
||||
else pid = strtol(path, NULL, 10);
|
||||
if (strncmp(rest, "/task/", 6) == 0 && (rest = skip_digits(rest + 6)) == NULL) return -1;
|
||||
return strcmp(rest, "/status") == 0 ? pid : -1;
|
||||
}
|
||||
|
||||
static int is_web_helper(const void *caller) {
|
||||
@@ -56,13 +58,26 @@ static int write_all(int fd, const char *data, size_t len) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int read_only_copy(const char *data, size_t len, int flags) {
|
||||
char path[] = "/tmp/.droiddeck-status-XXXXXX";
|
||||
int rw = mkostemp(path, O_CLOEXEC);
|
||||
if (rw < 0) return -1;
|
||||
int ro = -1;
|
||||
if (write_all(rw, data, len) == 0)
|
||||
ro = (int)syscall(SYS_openat, AT_FDCWD, path, O_RDONLY | (flags & O_CLOEXEC));
|
||||
unlink(path);
|
||||
close(rw);
|
||||
return ro;
|
||||
}
|
||||
|
||||
__attribute__((visibility("hidden"))) int bl_status_without_tracer(const char *path, int flags, const void *caller) {
|
||||
char text[STATUS_MAX];
|
||||
size_t len = 0;
|
||||
int saved = errno;
|
||||
int out = -1;
|
||||
|
||||
if ((flags & O_ACCMODE) != O_RDONLY || !is_status_path(path) || is_web_helper(caller)) return -1;
|
||||
long pid;
|
||||
if ((flags & O_ACCMODE) != O_RDONLY || (pid = status_pid(path)) < 0 || is_web_helper(caller)) return -1;
|
||||
int in = (int)syscall(SYS_openat, AT_FDCWD, path, O_RDONLY | O_CLOEXEC);
|
||||
if (in < 0) goto done;
|
||||
for (;;) {
|
||||
@@ -78,13 +93,16 @@ __attribute__((visibility("hidden"))) int bl_status_without_tracer(const char *p
|
||||
if (field == NULL) goto done;
|
||||
char *value = field + strlen(TRACER_FIELD);
|
||||
char *line_end = strchr(value, '\n');
|
||||
if (line_end == NULL) goto done;
|
||||
if (line_end == NULL || line_end == value) goto done;
|
||||
|
||||
memmove(value + 1, line_end, len - (size_t)(line_end - text) + 1);
|
||||
*value = '0';
|
||||
len = (size_t)(value + 1 - text) + strlen(value + 1);
|
||||
if (pid != 0 && pid != getpid() && (out = read_only_copy(text, len, flags)) >= 0) goto done;
|
||||
|
||||
out = memfd_create("status", (flags & O_CLOEXEC) ? MFD_CLOEXEC : 0);
|
||||
if (out < 0) goto done;
|
||||
if (write_all(out, text, (size_t)(value - text)) != 0 || write_all(out, "0", 1) != 0
|
||||
|| write_all(out, line_end, len - (size_t)(line_end - text)) != 0
|
||||
|| lseek(out, 0, SEEK_SET) != 0) {
|
||||
if (write_all(out, text, len) != 0 || lseek(out, 0, SEEK_SET) != 0) {
|
||||
close(out);
|
||||
out = -1;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,633 @@
|
||||
/* /dev/video-enc0 for Steam's Remote Play V4L2 encoder stage, backed by the app's MediaCodec encoder. */
|
||||
#define _GNU_SOURCE
|
||||
#include <dlfcn.h>
|
||||
#include <errno.h>
|
||||
#include <fcntl.h>
|
||||
#include <linux/videodev2.h>
|
||||
#include <poll.h>
|
||||
#include <pthread.h>
|
||||
#include <signal.h>
|
||||
#include <stdarg.h>
|
||||
#include <stdint.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/mman.h>
|
||||
#include <sys/socket.h>
|
||||
#include <sys/time.h>
|
||||
#include <sys/un.h>
|
||||
#include <time.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include "../../../app/src/main/cpp/venc/venc_proto.h"
|
||||
|
||||
#ifndef V4L2_CID_MPEG_VIDEO_PREPEND_SPSPPS_TO_IDR
|
||||
#define V4L2_CID_MPEG_VIDEO_PREPEND_SPSPPS_TO_IDR (V4L2_CID_MPEG_BASE + 644)
|
||||
#endif
|
||||
|
||||
#define VENC_DEVICE "/dev/video-enc0"
|
||||
#define VENC_INSTANCES 4
|
||||
#define VENC_OFFSET_STEP 0x1000000L
|
||||
#define VENC_CAPTURE_OFFSET (VENC_OFFSET_STEP * 64)
|
||||
|
||||
struct vq_buf {
|
||||
int memfd;
|
||||
uint32_t size;
|
||||
};
|
||||
|
||||
struct vq_item {
|
||||
uint32_t index, bytes, flags, sequence;
|
||||
struct timeval timestamp;
|
||||
};
|
||||
|
||||
struct vq {
|
||||
struct vq_buf bufs[VENC_MAX_BUFFERS];
|
||||
uint32_t count;
|
||||
struct vq_item queued[VENC_MAX_BUFFERS], done[VENC_MAX_BUFFERS];
|
||||
uint32_t nqueued, ndone;
|
||||
int streaming;
|
||||
};
|
||||
|
||||
struct venc {
|
||||
int used, fd;
|
||||
pid_t owner;
|
||||
uint32_t width, height, stride, crop_w, crop_h, raw_size;
|
||||
uint32_t coded_fourcc, coded_size;
|
||||
uint32_t fps_num, fps_den;
|
||||
uint32_t bitrate, peak, vbr, gop;
|
||||
int32_t h264_profile, h264_level, hevc_profile;
|
||||
int force_key, configured, sent_bitrate;
|
||||
uint32_t sequence;
|
||||
struct vq raw, coded;
|
||||
};
|
||||
|
||||
static pthread_mutex_t vn_lock = PTHREAD_MUTEX_INITIALIZER;
|
||||
static struct venc vn_all[VENC_INSTANCES];
|
||||
static int vn_open_count;
|
||||
|
||||
static void vn_marker(int streaming) {
|
||||
const char *dir = getenv("XDG_RUNTIME_DIR");
|
||||
char path[512];
|
||||
if (dir == NULL || snprintf(path, sizeof path, "%s/droiddeck-remote-play", dir) >= (int)sizeof path) return;
|
||||
if (!streaming) {
|
||||
unlink(path);
|
||||
return;
|
||||
}
|
||||
FILE *f = fopen(path, "w");
|
||||
if (f == NULL) return;
|
||||
fprintf(f, "%d\n", (int)getpid());
|
||||
fclose(f);
|
||||
}
|
||||
|
||||
static void vn_log(const char *fmt, ...) __attribute__((format(printf, 1, 2)));
|
||||
static void vn_log(const char *fmt, ...) {
|
||||
va_list ap;
|
||||
char line[256];
|
||||
va_start(ap, fmt);
|
||||
int n = vsnprintf(line, sizeof line - 1, fmt, ap);
|
||||
va_end(ap);
|
||||
if (n < 0) return;
|
||||
if (n > (int)sizeof line - 2) n = sizeof line - 2;
|
||||
line[n++] = '\n';
|
||||
if (write(2, "droiddeck-venc: ", 16) < 0 || write(2, line, n) < 0) return;
|
||||
}
|
||||
|
||||
static struct venc *vn_find(int fd) {
|
||||
if (fd < 0 || __atomic_load_n(&vn_open_count, __ATOMIC_ACQUIRE) == 0) return NULL;
|
||||
for (int i = 0; i < VENC_INSTANCES; i++) if (vn_all[i].used && vn_all[i].fd == fd) return &vn_all[i];
|
||||
return NULL;
|
||||
}
|
||||
|
||||
static int is_raw(uint32_t type) { return type == V4L2_BUF_TYPE_VIDEO_OUTPUT || type == V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE; }
|
||||
static int is_coded(uint32_t type) { return type == V4L2_BUF_TYPE_VIDEO_CAPTURE || type == V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE; }
|
||||
static int is_mplane(uint32_t type) { return type == V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE || type == V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE; }
|
||||
static struct vq *vn_queue(struct venc *v, uint32_t type) { return is_raw(type) ? &v->raw : is_coded(type) ? &v->coded : NULL; }
|
||||
|
||||
static void vn_sizes(struct venc *v) {
|
||||
if (v->stride < v->width) v->stride = v->width;
|
||||
v->raw_size = v->stride * v->height * 3 / 2;
|
||||
uint32_t coded = v->width * v->height * 3 / 2;
|
||||
if (coded < 512 * 1024) coded = 512 * 1024;
|
||||
if (v->coded_size < coded) v->coded_size = coded;
|
||||
}
|
||||
|
||||
static void vn_free_queue(struct vq *q) {
|
||||
for (uint32_t i = 0; i < q->count; i++) if (q->bufs[i].memfd >= 0) close(q->bufs[i].memfd);
|
||||
memset(q, 0, sizeof *q);
|
||||
}
|
||||
|
||||
__attribute__((visibility("hidden"))) int bl_venc_streaming(void) {
|
||||
return __atomic_load_n(&vn_open_count, __ATOMIC_ACQUIRE) > 0;
|
||||
}
|
||||
|
||||
__attribute__((visibility("hidden"))) int bl_venc_connect(void);
|
||||
|
||||
int bl_venc_connect(void) {
|
||||
const char *path = getenv("BL_VENC_SOCKET");
|
||||
if (path == NULL || *path == '\0') return -1;
|
||||
struct sockaddr_un addr = { .sun_family = AF_UNIX };
|
||||
if (strlen(path) >= sizeof addr.sun_path) return -1;
|
||||
strcpy(addr.sun_path, path);
|
||||
int fd = socket(AF_UNIX, SOCK_SEQPACKET | SOCK_CLOEXEC, 0);
|
||||
if (fd < 0) return -1;
|
||||
if (connect(fd, (struct sockaddr *)&addr, sizeof addr) != 0) {
|
||||
close(fd);
|
||||
return -1;
|
||||
}
|
||||
struct timeval tv = { .tv_sec = 2 };
|
||||
setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof tv);
|
||||
return fd;
|
||||
}
|
||||
|
||||
__attribute__((visibility("hidden"))) int bl_venc_open(const char *path, int flags) {
|
||||
(void)flags;
|
||||
if (path == NULL || strcmp(path, VENC_DEVICE) != 0) return -2;
|
||||
int fd = bl_venc_connect();
|
||||
if (fd < 0) return -2;
|
||||
pthread_mutex_lock(&vn_lock);
|
||||
struct venc *v = NULL;
|
||||
for (int i = 0; i < VENC_INSTANCES && v == NULL; i++) if (!vn_all[i].used) v = &vn_all[i];
|
||||
if (v == NULL) {
|
||||
pthread_mutex_unlock(&vn_lock);
|
||||
close(fd);
|
||||
errno = EBUSY;
|
||||
return -1;
|
||||
}
|
||||
memset(v, 0, sizeof *v);
|
||||
v->used = 1;
|
||||
v->fd = fd;
|
||||
v->owner = getpid();
|
||||
v->width = v->crop_w = 1280;
|
||||
v->height = v->crop_h = 720;
|
||||
v->coded_fourcc = V4L2_PIX_FMT_H264;
|
||||
v->fps_num = 1;
|
||||
v->fps_den = 60;
|
||||
v->bitrate = 20000000;
|
||||
v->gop = 0xffff;
|
||||
vn_sizes(v);
|
||||
if (__atomic_add_fetch(&vn_open_count, 1, __ATOMIC_RELEASE) == 1) vn_marker(1);
|
||||
pthread_mutex_unlock(&vn_lock);
|
||||
vn_log("opened %s as fd %d (MediaCodec through the app)", path, fd);
|
||||
return fd;
|
||||
}
|
||||
|
||||
static int vn_send(struct venc *v, const void *msg, size_t len, const int *fds, int nfds) {
|
||||
struct iovec iov = { .iov_base = (void *)msg, .iov_len = len };
|
||||
char control[CMSG_SPACE(sizeof(int) * VENC_MAX_BUFFERS * 2)];
|
||||
struct msghdr m = { .msg_iov = &iov, .msg_iovlen = 1 };
|
||||
if (nfds > 0) {
|
||||
memset(control, 0, sizeof control);
|
||||
m.msg_control = control;
|
||||
m.msg_controllen = CMSG_SPACE(sizeof(int) * nfds);
|
||||
struct cmsghdr *c = CMSG_FIRSTHDR(&m);
|
||||
c->cmsg_level = SOL_SOCKET;
|
||||
c->cmsg_type = SCM_RIGHTS;
|
||||
c->cmsg_len = CMSG_LEN(sizeof(int) * nfds);
|
||||
memcpy(CMSG_DATA(c), fds, sizeof(int) * nfds);
|
||||
}
|
||||
return sendmsg(v->fd, &m, MSG_NOSIGNAL) == (ssize_t)len ? 0 : -1;
|
||||
}
|
||||
|
||||
static int vn_configure(struct venc *v) {
|
||||
struct venc_config c = {
|
||||
.type = VENC_CONFIG,
|
||||
.codec = v->coded_fourcc == V4L2_PIX_FMT_HEVC ? VENC_HEVC : VENC_H264,
|
||||
.width = v->crop_w, .height = v->crop_h, .stride = v->stride, .rows = v->height,
|
||||
.fps_num = v->fps_num, .fps_den = v->fps_den,
|
||||
.bitrate = v->bitrate, .peak_bitrate = v->peak, .vbr = v->vbr, .gop = v->gop,
|
||||
.profile = v->coded_fourcc == V4L2_PIX_FMT_HEVC ? v->hevc_profile : v->h264_profile,
|
||||
.level = v->h264_level,
|
||||
.inputs = v->raw.count, .outputs = v->coded.count,
|
||||
.input_size = v->raw_size, .output_size = v->coded_size,
|
||||
};
|
||||
int fds[VENC_MAX_BUFFERS * 2], n = 0;
|
||||
for (uint32_t i = 0; i < v->raw.count; i++) fds[n++] = v->raw.bufs[i].memfd;
|
||||
for (uint32_t i = 0; i < v->coded.count; i++) fds[n++] = v->coded.bufs[i].memfd;
|
||||
if (vn_send(v, &c, sizeof c, fds, n) != 0) return -1;
|
||||
struct venc_done d;
|
||||
if (recv(v->fd, &d, sizeof d, 0) != (ssize_t)sizeof d || d.type != VENC_DONE || d.status != 0) {
|
||||
vn_log("the app's encoder refused %ux%u %s", c.width, c.height, c.codec == VENC_HEVC ? "HEVC" : "H.264");
|
||||
return -1;
|
||||
}
|
||||
vn_log("encoding %ux%u at %u/%u fps, %u kbit/s %s, %s", c.width, c.height, c.fps_den, c.fps_num,
|
||||
c.bitrate / 1000, c.vbr ? "VBR" : "CBR", c.codec == VENC_HEVC ? "HEVC" : "H.264");
|
||||
v->configured = 1;
|
||||
v->sent_bitrate = (int)v->bitrate;
|
||||
return 0;
|
||||
}
|
||||
|
||||
static void vn_pump(struct venc *v) {
|
||||
while (v->raw.streaming && v->coded.streaming && v->raw.nqueued > 0 && v->coded.nqueued > 0) {
|
||||
struct vq_item in = v->raw.queued[0], out = v->coded.queued[0];
|
||||
memmove(v->raw.queued, v->raw.queued + 1, --v->raw.nqueued * sizeof in);
|
||||
memmove(v->coded.queued, v->coded.queued + 1, --v->coded.nqueued * sizeof out);
|
||||
int ok = v->configured || vn_configure(v) == 0;
|
||||
if (ok && v->sent_bitrate != (int)v->bitrate) {
|
||||
struct venc_bitrate b = { .type = VENC_BITRATE, .bitrate = v->bitrate };
|
||||
if (vn_send(v, &b, sizeof b, NULL, 0) == 0) v->sent_bitrate = (int)v->bitrate;
|
||||
}
|
||||
struct venc_frame f = {
|
||||
.type = VENC_FRAME, .input = in.index, .output = out.index, .bytes = in.bytes,
|
||||
.keyframe = (uint32_t)v->force_key,
|
||||
.pts_us = (int64_t)in.timestamp.tv_sec * 1000000 + in.timestamp.tv_usec,
|
||||
};
|
||||
struct venc_done d = { 0 };
|
||||
ok = ok && vn_send(v, &f, sizeof f, NULL, 0) == 0 &&
|
||||
recv(v->fd, &d, sizeof d, 0) == (ssize_t)sizeof d && d.type == VENC_DONE && d.status == 0;
|
||||
if (!ok) vn_log("frame %u was not encoded (%s)", v->sequence, strerror(errno));
|
||||
v->force_key = 0;
|
||||
in.flags = V4L2_BUF_FLAG_DONE;
|
||||
out.bytes = ok ? d.bytes : 0;
|
||||
out.flags = V4L2_BUF_FLAG_DONE | (ok ? (d.keyframe ? V4L2_BUF_FLAG_KEYFRAME : V4L2_BUF_FLAG_PFRAME) : V4L2_BUF_FLAG_ERROR);
|
||||
out.timestamp = in.timestamp;
|
||||
in.sequence = out.sequence = v->sequence++;
|
||||
v->raw.done[v->raw.ndone++] = in;
|
||||
v->coded.done[v->coded.ndone++] = out;
|
||||
}
|
||||
}
|
||||
|
||||
static void vn_fill_format(struct venc *v, struct v4l2_format *f) {
|
||||
if (is_mplane(f->type)) {
|
||||
struct v4l2_pix_format_mplane *p = &f->fmt.pix_mp;
|
||||
memset(p, 0, sizeof *p);
|
||||
p->width = v->width;
|
||||
p->height = v->height;
|
||||
p->field = V4L2_FIELD_NONE;
|
||||
p->num_planes = 1;
|
||||
p->colorspace = V4L2_COLORSPACE_REC709;
|
||||
if (is_raw(f->type)) {
|
||||
p->pixelformat = V4L2_PIX_FMT_NV12;
|
||||
p->plane_fmt[0].bytesperline = v->stride;
|
||||
p->plane_fmt[0].sizeimage = v->raw_size;
|
||||
} else {
|
||||
p->pixelformat = v->coded_fourcc;
|
||||
p->plane_fmt[0].sizeimage = v->coded_size;
|
||||
}
|
||||
} else {
|
||||
struct v4l2_pix_format *p = &f->fmt.pix;
|
||||
memset(p, 0, sizeof *p);
|
||||
p->width = v->width;
|
||||
p->height = v->height;
|
||||
p->field = V4L2_FIELD_NONE;
|
||||
p->colorspace = V4L2_COLORSPACE_REC709;
|
||||
p->pixelformat = is_raw(f->type) ? V4L2_PIX_FMT_NV12 : v->coded_fourcc;
|
||||
p->bytesperline = is_raw(f->type) ? v->stride : 0;
|
||||
p->sizeimage = is_raw(f->type) ? v->raw_size : v->coded_size;
|
||||
}
|
||||
}
|
||||
|
||||
static int vn_set_format(struct venc *v, struct v4l2_format *f, int apply) {
|
||||
uint32_t w, h, fourcc, stride, size;
|
||||
if (is_mplane(f->type)) {
|
||||
w = f->fmt.pix_mp.width; h = f->fmt.pix_mp.height; fourcc = f->fmt.pix_mp.pixelformat;
|
||||
stride = f->fmt.pix_mp.plane_fmt[0].bytesperline; size = f->fmt.pix_mp.plane_fmt[0].sizeimage;
|
||||
} else if (is_raw(f->type) || is_coded(f->type)) {
|
||||
w = f->fmt.pix.width; h = f->fmt.pix.height; fourcc = f->fmt.pix.pixelformat;
|
||||
stride = f->fmt.pix.bytesperline; size = f->fmt.pix.sizeimage;
|
||||
} else {
|
||||
return -EINVAL;
|
||||
}
|
||||
struct venc t = *v;
|
||||
if (w >= 64 && h >= 64 && w <= 4096 && h <= 4096) {
|
||||
t.width = (w + 1) & ~1u;
|
||||
t.height = (h + 1) & ~1u;
|
||||
t.crop_w = t.width;
|
||||
t.crop_h = t.height;
|
||||
}
|
||||
if (is_raw(f->type)) {
|
||||
t.stride = stride;
|
||||
} else {
|
||||
t.coded_fourcc = fourcc == V4L2_PIX_FMT_HEVC ? V4L2_PIX_FMT_HEVC : V4L2_PIX_FMT_H264;
|
||||
t.coded_size = size;
|
||||
}
|
||||
vn_sizes(&t);
|
||||
if (apply) {
|
||||
if (t.width != v->width || t.height != v->height || t.coded_fourcc != v->coded_fourcc) v->configured = 0;
|
||||
*v = t;
|
||||
}
|
||||
vn_fill_format(&t, f);
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int vn_reqbufs(struct venc *v, struct v4l2_requestbuffers *r) {
|
||||
struct vq *q = vn_queue(v, r->type);
|
||||
if (q == NULL) return -EINVAL;
|
||||
if (r->memory != V4L2_MEMORY_MMAP) return -EINVAL;
|
||||
vn_free_queue(q);
|
||||
v->configured = 0;
|
||||
uint32_t n = r->count > VENC_MAX_BUFFERS ? VENC_MAX_BUFFERS : r->count;
|
||||
uint32_t size = is_raw(r->type) ? v->raw_size : v->coded_size;
|
||||
for (uint32_t i = 0; i < n; i++) {
|
||||
int fd = memfd_create("droiddeck-venc", MFD_CLOEXEC);
|
||||
if (fd < 0 || ftruncate(fd, size) != 0) {
|
||||
if (fd >= 0) close(fd);
|
||||
vn_free_queue(q);
|
||||
return -ENOMEM;
|
||||
}
|
||||
q->bufs[i].memfd = fd;
|
||||
q->bufs[i].size = size;
|
||||
q->count = i + 1;
|
||||
}
|
||||
r->count = n;
|
||||
#ifdef V4L2_BUF_CAP_SUPPORTS_MMAP
|
||||
r->capabilities = V4L2_BUF_CAP_SUPPORTS_MMAP;
|
||||
#endif
|
||||
return 0;
|
||||
}
|
||||
|
||||
static long vn_offset(struct v4l2_buffer *b) {
|
||||
return (is_raw(b->type) ? 0 : VENC_CAPTURE_OFFSET) + (long)(b->index + 1) * VENC_OFFSET_STEP;
|
||||
}
|
||||
|
||||
static void vn_describe(struct venc *v, struct v4l2_buffer *b, const struct vq_item *item) {
|
||||
struct vq *q = vn_queue(v, b->type);
|
||||
uint32_t size = q->bufs[b->index].size;
|
||||
b->memory = V4L2_MEMORY_MMAP;
|
||||
b->field = V4L2_FIELD_NONE;
|
||||
b->flags = V4L2_BUF_FLAG_MAPPED | (item ? item->flags : 0);
|
||||
if (item) {
|
||||
b->timestamp = item->timestamp;
|
||||
b->sequence = item->sequence;
|
||||
}
|
||||
if (is_mplane(b->type)) {
|
||||
if (b->m.planes == NULL || b->length < 1) return;
|
||||
b->length = 1;
|
||||
b->m.planes[0].length = size;
|
||||
b->m.planes[0].m.mem_offset = (uint32_t)vn_offset(b);
|
||||
b->m.planes[0].data_offset = 0;
|
||||
if (item) b->m.planes[0].bytesused = item->bytes;
|
||||
} else {
|
||||
b->length = size;
|
||||
b->m.offset = (uint32_t)vn_offset(b);
|
||||
if (item) b->bytesused = item->bytes;
|
||||
}
|
||||
}
|
||||
|
||||
static int vn_qbuf(struct venc *v, struct v4l2_buffer *b) {
|
||||
struct vq *q = vn_queue(v, b->type);
|
||||
if (q == NULL || b->index >= q->count || q->nqueued >= VENC_MAX_BUFFERS) return -EINVAL;
|
||||
struct vq_item item = { .index = b->index, .timestamp = b->timestamp };
|
||||
if (is_raw(b->type))
|
||||
item.bytes = is_mplane(b->type) ? (b->m.planes && b->length ? b->m.planes[0].bytesused : 0) : b->bytesused;
|
||||
if (item.bytes == 0 || item.bytes > q->bufs[b->index].size) item.bytes = q->bufs[b->index].size;
|
||||
q->queued[q->nqueued++] = item;
|
||||
vn_describe(v, b, NULL);
|
||||
b->flags |= V4L2_BUF_FLAG_QUEUED;
|
||||
vn_pump(v);
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int vn_dqbuf(struct venc *v, struct v4l2_buffer *b) {
|
||||
struct vq *q = vn_queue(v, b->type);
|
||||
if (q == NULL) return -EINVAL;
|
||||
if (q->ndone == 0) return -EAGAIN;
|
||||
struct vq_item item = q->done[0];
|
||||
memmove(q->done, q->done + 1, --q->ndone * sizeof item);
|
||||
b->index = item.index;
|
||||
vn_describe(v, b, &item);
|
||||
return 0;
|
||||
}
|
||||
|
||||
static void vn_set_control(struct venc *v, uint32_t id, int32_t value) {
|
||||
switch (id) {
|
||||
case V4L2_CID_MPEG_VIDEO_BITRATE: if (value > 0) v->bitrate = (uint32_t)value; break;
|
||||
case V4L2_CID_MPEG_VIDEO_BITRATE_PEAK: if (value > 0) v->peak = (uint32_t)value; break;
|
||||
case V4L2_CID_MPEG_VIDEO_BITRATE_MODE: v->vbr = value == V4L2_MPEG_VIDEO_BITRATE_MODE_VBR; v->configured = 0; break;
|
||||
case V4L2_CID_MPEG_VIDEO_GOP_SIZE: v->gop = (uint32_t)value; v->configured = 0; break;
|
||||
case V4L2_CID_MPEG_VIDEO_H264_PROFILE: v->h264_profile = value; v->configured = 0; break;
|
||||
case V4L2_CID_MPEG_VIDEO_H264_LEVEL: v->h264_level = value; v->configured = 0; break;
|
||||
case V4L2_CID_MPEG_VIDEO_HEVC_PROFILE: v->hevc_profile = value; v->configured = 0; break;
|
||||
case V4L2_CID_MPEG_VIDEO_FORCE_KEY_FRAME: v->force_key = 1; break;
|
||||
default: break;
|
||||
}
|
||||
}
|
||||
|
||||
static int vn_get_control(struct venc *v, uint32_t id, int32_t *value) {
|
||||
switch (id) {
|
||||
case V4L2_CID_MPEG_VIDEO_BITRATE: *value = (int32_t)v->bitrate; return 0;
|
||||
case V4L2_CID_MPEG_VIDEO_BITRATE_PEAK: *value = (int32_t)v->peak; return 0;
|
||||
case V4L2_CID_MPEG_VIDEO_GOP_SIZE: *value = (int32_t)v->gop; return 0;
|
||||
default: *value = 0; return 0;
|
||||
}
|
||||
}
|
||||
|
||||
static int vn_ioctl(struct venc *v, unsigned long req, void *arg) {
|
||||
switch (req) {
|
||||
case VIDIOC_QUERYCAP: {
|
||||
struct v4l2_capability *c = arg;
|
||||
memset(c, 0, sizeof *c);
|
||||
strcpy((char *)c->driver, "droiddeck_venc");
|
||||
strcpy((char *)c->card, "Android MediaCodec");
|
||||
strcpy((char *)c->bus_info, "platform:droiddeck-venc");
|
||||
c->version = 0x00060000;
|
||||
c->device_caps = V4L2_CAP_VIDEO_M2M_MPLANE | V4L2_CAP_VIDEO_M2M | V4L2_CAP_STREAMING;
|
||||
c->capabilities = c->device_caps | V4L2_CAP_DEVICE_CAPS;
|
||||
return 0;
|
||||
}
|
||||
case VIDIOC_ENUM_FMT: {
|
||||
struct v4l2_fmtdesc *d = arg;
|
||||
static const uint32_t coded[] = { V4L2_PIX_FMT_H264, V4L2_PIX_FMT_HEVC };
|
||||
if (is_raw(d->type) && d->index == 0) {
|
||||
d->pixelformat = V4L2_PIX_FMT_NV12;
|
||||
strcpy((char *)d->description, "Y/CbCr 4:2:0");
|
||||
d->flags = 0;
|
||||
} else if (is_coded(d->type) && d->index < 2) {
|
||||
d->pixelformat = coded[d->index];
|
||||
strcpy((char *)d->description, d->index ? "HEVC" : "H.264");
|
||||
d->flags = V4L2_FMT_FLAG_COMPRESSED;
|
||||
} else {
|
||||
return -EINVAL;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
case VIDIOC_ENUM_FRAMESIZES: {
|
||||
struct v4l2_frmsizeenum *s = arg;
|
||||
if (s->index != 0) return -EINVAL;
|
||||
s->type = V4L2_FRMSIZE_TYPE_STEPWISE;
|
||||
s->stepwise = (struct v4l2_frmsize_stepwise){ 64, 4096, 2, 64, 4096, 2 };
|
||||
return 0;
|
||||
}
|
||||
case VIDIOC_G_FMT: vn_fill_format(v, arg); return 0;
|
||||
case VIDIOC_S_FMT: return vn_set_format(v, arg, 1);
|
||||
case VIDIOC_TRY_FMT: return vn_set_format(v, arg, 0);
|
||||
case VIDIOC_REQBUFS: return vn_reqbufs(v, arg);
|
||||
case VIDIOC_QUERYBUF: {
|
||||
struct v4l2_buffer *b = arg;
|
||||
struct vq *q = vn_queue(v, b->type);
|
||||
if (q == NULL || b->index >= q->count) return -EINVAL;
|
||||
vn_describe(v, b, NULL);
|
||||
return 0;
|
||||
}
|
||||
case VIDIOC_QBUF: return vn_qbuf(v, arg);
|
||||
case VIDIOC_DQBUF: return vn_dqbuf(v, arg);
|
||||
case VIDIOC_STREAMON:
|
||||
case VIDIOC_STREAMOFF: {
|
||||
struct vq *q = vn_queue(v, *(uint32_t *)arg);
|
||||
if (q == NULL) return -EINVAL;
|
||||
q->streaming = req == VIDIOC_STREAMON;
|
||||
if (!q->streaming) q->nqueued = q->ndone = 0;
|
||||
vn_pump(v);
|
||||
return 0;
|
||||
}
|
||||
case VIDIOC_S_PARM:
|
||||
case VIDIOC_G_PARM: {
|
||||
struct v4l2_streamparm *p = arg;
|
||||
if (!is_raw(p->type)) return req == VIDIOC_G_PARM ? 0 : -EINVAL;
|
||||
struct v4l2_fract *t = &p->parm.output.timeperframe;
|
||||
if (req == VIDIOC_S_PARM && t->numerator > 0 && t->denominator > 0) {
|
||||
v->fps_num = t->numerator;
|
||||
v->fps_den = t->denominator;
|
||||
v->configured = 0;
|
||||
}
|
||||
p->parm.output.capability = V4L2_CAP_TIMEPERFRAME;
|
||||
t->numerator = v->fps_num;
|
||||
t->denominator = v->fps_den;
|
||||
return 0;
|
||||
}
|
||||
case VIDIOC_S_CTRL: {
|
||||
struct v4l2_control *c = arg;
|
||||
vn_set_control(v, c->id, c->value);
|
||||
return 0;
|
||||
}
|
||||
case VIDIOC_G_CTRL: {
|
||||
struct v4l2_control *c = arg;
|
||||
return vn_get_control(v, c->id, &c->value);
|
||||
}
|
||||
case VIDIOC_S_EXT_CTRLS:
|
||||
case VIDIOC_TRY_EXT_CTRLS:
|
||||
case VIDIOC_G_EXT_CTRLS: {
|
||||
struct v4l2_ext_controls *e = arg;
|
||||
for (uint32_t i = 0; i < e->count && e->controls; i++) {
|
||||
if (req == VIDIOC_S_EXT_CTRLS) vn_set_control(v, e->controls[i].id, e->controls[i].value);
|
||||
else if (req == VIDIOC_G_EXT_CTRLS) {
|
||||
int32_t value;
|
||||
vn_get_control(v, e->controls[i].id, &value);
|
||||
e->controls[i].value = value;
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
case VIDIOC_QUERYCTRL: {
|
||||
struct v4l2_queryctrl *q = arg;
|
||||
if (q->id & V4L2_CTRL_FLAG_NEXT_CTRL) return -EINVAL;
|
||||
q->type = V4L2_CTRL_TYPE_INTEGER;
|
||||
q->minimum = 0;
|
||||
q->maximum = 0x7fffffff;
|
||||
q->step = 1;
|
||||
q->flags = 0;
|
||||
return 0;
|
||||
}
|
||||
case VIDIOC_S_SELECTION:
|
||||
case VIDIOC_G_SELECTION: {
|
||||
struct v4l2_selection *s = arg;
|
||||
if (req == VIDIOC_S_SELECTION && s->r.width >= 64 && s->r.height >= 64 &&
|
||||
s->r.width <= v->width && s->r.height <= v->height) {
|
||||
v->crop_w = s->r.width & ~1u;
|
||||
v->crop_h = s->r.height & ~1u;
|
||||
v->configured = 0;
|
||||
}
|
||||
s->r = (struct v4l2_rect){ 0, 0, v->crop_w, v->crop_h };
|
||||
return 0;
|
||||
}
|
||||
case VIDIOC_SUBSCRIBE_EVENT:
|
||||
case VIDIOC_UNSUBSCRIBE_EVENT:
|
||||
case VIDIOC_ENCODER_CMD:
|
||||
case VIDIOC_TRY_ENCODER_CMD:
|
||||
return 0;
|
||||
case VIDIOC_DQEVENT:
|
||||
return -ENOENT;
|
||||
default: {
|
||||
static unsigned long logged[32];
|
||||
int seen = 0;
|
||||
for (int i = 0; i < 32 && logged[i]; i++) seen |= logged[i] == req;
|
||||
for (int i = 0; i < 32 && !seen; i++) if (!logged[i]) { logged[i] = req; break; }
|
||||
if (!seen) vn_log("unhandled ioctl 0x%lx", req);
|
||||
return -ENOTTY;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
__attribute__((visibility("hidden"))) int bl_venc_ioctl(int fd, unsigned long req, void *arg, int *rc) {
|
||||
struct venc *v = vn_find(fd);
|
||||
if (v == NULL) return 0;
|
||||
pthread_mutex_lock(&vn_lock);
|
||||
int r = arg ? vn_ioctl(v, req, arg) : -EFAULT;
|
||||
pthread_mutex_unlock(&vn_lock);
|
||||
if (r < 0) {
|
||||
errno = -r;
|
||||
*rc = -1;
|
||||
} else {
|
||||
*rc = 0;
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
__attribute__((visibility("hidden"))) int bl_venc_mmap(void *addr, size_t len, int prot, int flags, int fd, off_t off,
|
||||
void *(*real)(void *, size_t, int, int, int, off_t), void **out) {
|
||||
struct venc *v = vn_find(fd);
|
||||
if (v == NULL) return 0;
|
||||
pthread_mutex_lock(&vn_lock);
|
||||
struct vq *q = off >= VENC_CAPTURE_OFFSET ? &v->coded : &v->raw;
|
||||
long index = (off - (off >= VENC_CAPTURE_OFFSET ? VENC_CAPTURE_OFFSET : 0)) / VENC_OFFSET_STEP - 1;
|
||||
int memfd = index >= 0 && index < (long)q->count ? q->bufs[index].memfd : -1;
|
||||
pthread_mutex_unlock(&vn_lock);
|
||||
if (memfd < 0) {
|
||||
errno = EINVAL;
|
||||
*out = MAP_FAILED;
|
||||
} else {
|
||||
*out = real(addr, len, prot, (flags & ~MAP_PRIVATE) | MAP_SHARED, memfd, 0);
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
__attribute__((visibility("hidden"))) void bl_venc_closed(int fd) {
|
||||
struct venc *v = vn_find(fd);
|
||||
if (v == NULL) return;
|
||||
pthread_mutex_lock(&vn_lock);
|
||||
vn_free_queue(&v->raw);
|
||||
vn_free_queue(&v->coded);
|
||||
v->used = 0;
|
||||
/* A forked child closing its inherited copy must not end the stream for the parent. */
|
||||
if (__atomic_sub_fetch(&vn_open_count, 1, __ATOMIC_RELEASE) == 0 && v->owner == getpid()) vn_marker(0);
|
||||
pthread_mutex_unlock(&vn_lock);
|
||||
}
|
||||
|
||||
static short vn_ready(struct venc *v) {
|
||||
pthread_mutex_lock(&vn_lock);
|
||||
short r = (v->coded.ndone ? POLLIN | POLLRDNORM : 0) | (v->raw.ndone ? POLLOUT | POLLWRNORM : 0);
|
||||
pthread_mutex_unlock(&vn_lock);
|
||||
return r;
|
||||
}
|
||||
|
||||
static int vn_poll(struct pollfd *fds, nfds_t n, int timeout_ms, int (*real)(struct pollfd *, nfds_t, int)) {
|
||||
int ours = 0, ready = 0;
|
||||
int saved[64];
|
||||
if (n > 64) return real(fds, n, timeout_ms);
|
||||
for (nfds_t i = 0; i < n; i++) {
|
||||
saved[i] = fds[i].fd;
|
||||
struct venc *v = vn_find(fds[i].fd);
|
||||
if (v == NULL) continue;
|
||||
ours++;
|
||||
fds[i].revents = vn_ready(v) & (fds[i].events | POLLERR);
|
||||
if (fds[i].revents) ready++;
|
||||
fds[i].fd = -1;
|
||||
}
|
||||
if (ours == 0) return real(fds, n, timeout_ms);
|
||||
if (ready || timeout_ms < 0 || timeout_ms > 100) timeout_ms = ready ? 0 : 100;
|
||||
short keep[64];
|
||||
for (nfds_t i = 0; i < n; i++) keep[i] = fds[i].fd < 0 && saved[i] >= 0 ? fds[i].revents : 0;
|
||||
int r = n - ours > 0 ? real(fds, n, timeout_ms) : (timeout_ms && !ready ? real(NULL, 0, timeout_ms) : 0);
|
||||
if (r < 0) r = 0;
|
||||
for (nfds_t i = 0; i < n; i++) {
|
||||
if (fds[i].fd < 0 && saved[i] >= 0) fds[i].revents = keep[i];
|
||||
fds[i].fd = saved[i];
|
||||
}
|
||||
return r + ready;
|
||||
}
|
||||
|
||||
int poll(struct pollfd *fds, nfds_t n, int timeout_ms) {
|
||||
static int (*real)(struct pollfd *, nfds_t, int);
|
||||
if (!real) real = (int (*)(struct pollfd *, nfds_t, int))dlsym(RTLD_NEXT, "poll");
|
||||
if (__atomic_load_n(&vn_open_count, __ATOMIC_ACQUIRE) == 0) return real(fds, n, timeout_ms);
|
||||
return vn_poll(fds, n, timeout_ms, real);
|
||||
}
|
||||
Executable
+29
@@ -0,0 +1,29 @@
|
||||
#!/usr/bin/env bash
|
||||
# assemble.sh <extracted packages root> <out.tzst>
|
||||
# Packs the video side of SteamOS's PipeWire and WirePlumber: no audio plugins, no JACK.
|
||||
set -euo pipefail
|
||||
src=$1
|
||||
out=$2
|
||||
work=$(mktemp -d)
|
||||
trap 'rm -rf "$work"' EXIT
|
||||
b=$work/bundle
|
||||
mkdir -p "$b/bin" "$b/lib/pipewire-0.3" "$b/lib/spa-0.2" "$b/lib/wireplumber-0.5" "$b/share/licenses"
|
||||
|
||||
for tool in pipewire wireplumber wpctl; do cp "$src/usr/bin/$tool" "$b/bin/$tool"; done
|
||||
for library in libpipewire-0.3.so.0 libwireplumber-0.5.so.0; do cp -L "$src/usr/lib/$library" "$b/lib/$library"; done
|
||||
for module in "$src"/usr/lib/pipewire-0.3/libpipewire-module-*.so; do
|
||||
case ${module##*/} in *jack*) continue ;; esac
|
||||
cp "$module" "$b/lib/pipewire-0.3/"
|
||||
done
|
||||
cp "$src/usr/lib/spa-0.2/libspa.so" "$b/lib/spa-0.2/"
|
||||
for plugin in support control videoconvert v4l2; do cp -R "$src/usr/lib/spa-0.2/$plugin" "$b/lib/spa-0.2/$plugin"; done
|
||||
cp "$src"/usr/lib/wireplumber-0.5/*.so "$b/lib/wireplumber-0.5/"
|
||||
mkdir -p "$b/share/pipewire"
|
||||
cp "$src/usr/share/pipewire/pipewire.conf" "$src/usr/share/pipewire/client.conf" "$b/share/pipewire/"
|
||||
cp -R "$src/usr/share/wireplumber" "$b/share/wireplumber"
|
||||
for package in pipewire libpipewire wireplumber libwireplumber; do
|
||||
cp -R "$src/usr/share/licenses/$package" "$b/share/licenses/$package"
|
||||
done
|
||||
|
||||
mkdir -p "$(dirname "$out")"
|
||||
(cd "$b" && find . -type f | LC_ALL=C sort | tar -cf - -T -) | zstd -19 -q -f -o "$out"
|
||||
@@ -0,0 +1,4 @@
|
||||
55c9705ff5721f10ca18c42bd15c14b0af88cb5352f5400fda04c944a8b224f1 https://holo-packages.steamos.cloud/archlinux-deckard-hotfixes/release/0.4.x/libpipewire-1%3A1.6.8-1.2-aarch64.pkg.tar.zst
|
||||
8ea2d900326eaafdd2bbbfa47fa04f5d7515dbdcd9ede04213ba149f44f41da0 https://holo-packages.steamos.cloud/archlinux-deckard-hotfixes/release/0.4.x/pipewire-1%3A1.6.8-1.2-aarch64.pkg.tar.zst
|
||||
900a4c59f87806d85abe200bb014d755f73a16b2ba4fea63d6f32ff64fcf5e34 https://holo-packages.steamos.cloud/archlinux-deckard-hotfixes/release/0.4.x/libwireplumber-0.5.14-1.3-aarch64.pkg.tar.zst
|
||||
bf56f040cf09832e0a8135b56b0f6d2b9b29e2bddbd35be73d0bebe603eacafb https://holo-packages.steamos.cloud/archlinux-deckard-hotfixes/release/0.4.x/wireplumber-0.5.14-1.3-aarch64.pkg.tar.zst
|
||||
@@ -141,12 +141,18 @@ static int traced_by_match(const char *key) {
|
||||
return found;
|
||||
}
|
||||
|
||||
static long init_sys(long nr, long a, long b, long c) {
|
||||
static long (*real_syscall)(long, ...);
|
||||
if (!real_syscall) real_syscall = (long (*)(long, ...))dlsym(RTLD_NEXT, "syscall");
|
||||
return real_syscall(nr, a, b, c);
|
||||
}
|
||||
|
||||
static int program_32bit(const char *prog, int scripts) {
|
||||
char head[256];
|
||||
long fd = syscall(SYS_openat, AT_FDCWD, prog, O_RDONLY | O_CLOEXEC);
|
||||
long fd = init_sys(SYS_openat, AT_FDCWD, (long)prog, O_RDONLY | O_CLOEXEC);
|
||||
if (fd < 0) return 1;
|
||||
long n = syscall(SYS_read, fd, head, sizeof head - 1);
|
||||
syscall(SYS_close, fd);
|
||||
long n = init_sys(SYS_read, fd, (long)head, sizeof head - 1);
|
||||
init_sys(SYS_close, fd, 0, 0);
|
||||
if (n < 0) return 1;
|
||||
head[n] = 0;
|
||||
if (n >= 2 && head[0] == '#' && head[1] == '!') {
|
||||
@@ -166,10 +172,10 @@ static int fex_runs_32bit(void) {
|
||||
if (strcmp(program_invocation_short_name, "FEX") != 0 && strcmp(program_invocation_short_name, "FEXInterpreter") != 0)
|
||||
return 0;
|
||||
char args[PATH_MAX + 64];
|
||||
long fd = syscall(SYS_openat, AT_FDCWD, "/proc/self/cmdline", O_RDONLY | O_CLOEXEC);
|
||||
long fd = init_sys(SYS_openat, AT_FDCWD, (long)"/proc/self/cmdline", O_RDONLY | O_CLOEXEC);
|
||||
if (fd < 0) return 1;
|
||||
long n = syscall(SYS_read, fd, args, sizeof args - 1);
|
||||
syscall(SYS_close, fd);
|
||||
long n = init_sys(SYS_read, fd, (long)args, sizeof args - 1);
|
||||
init_sys(SYS_close, fd, 0, 0);
|
||||
if (n <= 0) return 1;
|
||||
args[n] = 0;
|
||||
const char *prog = args + strlen(args) + 1;
|
||||
|
||||
@@ -23,10 +23,11 @@ PACK_NAMES = ['proot', 'directaudio', 'tracking', 'xbox', 'comet']
|
||||
SOURCE_PATHS = ['app/build.gradle', 'app/src/main/cpp/fakeinput_steam.cpp', 'app/src/main/assets/pulseaudio.tzst',
|
||||
'tools/linuxfs', 'tools/proot', 'tools/aaudio-sink', 'tools/directaudio',
|
||||
'tools/gamescope/release.env', 'tools/droiddeck-esync/release.env',
|
||||
'tools/mangoapp', 'tools/msitools', 'tools/comet', 'tools/xbox', 'tools/build_local.sh',
|
||||
'tools/mangoapp', 'tools/msitools', 'tools/pipewire', 'tools/comet', 'tools/xbox', 'tools/build_local.sh',
|
||||
'tools/release/runtime_inputs.py', 'app/src/main/assets/desktop-removal',
|
||||
'tools/quest', 'tools/vr/src', 'tools/vr/driver_droiddeck', 'tools/vr/layer', 'tools/vr/build.sh',
|
||||
'app/src/main/cpp/waylandcomp/src/headpose_shm.h',
|
||||
'app/src/main/cpp/venc/venc_proto.h',
|
||||
'app/src/main/cpp/waylandcomp/src/spatialpose_shm.h',
|
||||
'app/src/main/cpp/adrenotools/src/hook/kgsl.h',
|
||||
'app/src/main/assets/graphics_driver/adrenotools-turnip25.1.0.tzst']
|
||||
@@ -75,7 +76,8 @@ def required():
|
||||
for name in ['turnip26.3.0-a6xx', 'turnip26.3.0-quest2']]
|
||||
paths += ['assets/linuxfs/' + name for name in ['libfakeinput.so', 'libblsession.so',
|
||||
'libblfastpath.so', 'libssbs.so', 'usr/local/bin/droiddeck-clipboard',
|
||||
'usr/local/bin/gamescope', 'usr/local/lib/droiddeck/uruntime']]
|
||||
'usr/local/bin/gamescope', 'usr/local/lib/droiddeck/uruntime',
|
||||
'usr/local/lib/droiddeck-pipewire.tzst']]
|
||||
for arch in ['x86_64', 'i386']:
|
||||
paths += ['assets/linuxfs/' + arch + '/' + lib for lib in ['libfakeinput.so', 'libblsession.so']]
|
||||
paths += ['assets/linuxfs/x86_64/' + lib for lib in
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
#define _GNU_SOURCE
|
||||
#include <errno.h>
|
||||
#include <pthread.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include <sys/ipc.h>
|
||||
#include <sys/msg.h>
|
||||
#include <sys/wait.h>
|
||||
#include <unistd.h>
|
||||
|
||||
struct note { long mtype; char text[32]; };
|
||||
|
||||
static int count_lines(const char *path) {
|
||||
FILE *f = fopen(path, "r");
|
||||
if (!f) return -1;
|
||||
int n = 0, c;
|
||||
while ((c = fgetc(f)) != EOF) n += c == '\n';
|
||||
fclose(f);
|
||||
return n;
|
||||
}
|
||||
|
||||
static void *wait_for_note(void *arg) {
|
||||
struct note n;
|
||||
long rc = msgrcv(*(int *)arg, &n, sizeof(n.text), 0, 0);
|
||||
return (void *)(rc < 0 && errno == EIDRM ? 1L : 0L);
|
||||
}
|
||||
|
||||
int main(void) {
|
||||
int q = msgget(0x5eed0002, IPC_CREAT | IPC_EXCL | 0600);
|
||||
if (q < 0) { perror("msgget"); return 1; }
|
||||
struct note n;
|
||||
if (msgrcv(q, &n, sizeof(n.text), 0, IPC_NOWAIT) != -1 || errno != ENOMSG) { printf("FAIL: empty queue\n"); return 1; }
|
||||
pid_t child = fork();
|
||||
if (child == 0) {
|
||||
struct note a = {2, "second"}, b = {1, "first"};
|
||||
return msgsnd(q, &a, sizeof(a.text), 0) || msgsnd(q, &b, sizeof(b.text), 0);
|
||||
}
|
||||
int status;
|
||||
waitpid(child, &status, 0);
|
||||
if (!WIFEXITED(status) || WEXITSTATUS(status)) { printf("FAIL: child send\n"); return 1; }
|
||||
if (msgrcv(q, &n, sizeof(n.text), 1, 0) < 0 || n.mtype != 1 || strcmp(n.text, "first")) { printf("FAIL: typed receive\n"); return 1; }
|
||||
if (msgrcv(q, &n, sizeof(n.text), 0, 0) < 0 || n.mtype != 2 || strcmp(n.text, "second")) { printf("FAIL: any receive\n"); return 1; }
|
||||
int maps = count_lines("/proc/self/maps");
|
||||
for (int i = 0; i < 2000; i++) {
|
||||
struct note p = {3, "poll"};
|
||||
if (msgsnd(q, &p, sizeof(p.text), 0) || msgrcv(q, &n, sizeof(n.text), 0, 0) < 0 ||
|
||||
msgrcv(q, &n, sizeof(n.text), 0, IPC_NOWAIT) != -1) { printf("FAIL: round %d\n", i); return 1; }
|
||||
}
|
||||
if (count_lines("/proc/self/maps") != maps) { printf("FAIL: mappings grew\n"); return 1; }
|
||||
pthread_t waiter;
|
||||
pthread_create(&waiter, NULL, wait_for_note, &q);
|
||||
usleep(100000);
|
||||
if (msgctl(q, IPC_RMID, NULL) != 0) { perror("msgctl"); return 1; }
|
||||
void *woken;
|
||||
pthread_join(waiter, &woken);
|
||||
if (!woken) { printf("FAIL: waiter not told the queue was removed\n"); return 1; }
|
||||
if (msgsnd(q, &n, sizeof(n.text), IPC_NOWAIT) != -1) { printf("FAIL: send to a removed queue\n"); return 1; }
|
||||
int again = msgget(0x5eed0002, IPC_CREAT | 0600);
|
||||
struct note r = {4, "again"};
|
||||
if (again < 0 || msgsnd(again, &r, sizeof(r.text), 0) || msgrcv(again, &n, sizeof(n.text), 0, 0) < 0 || strcmp(n.text, "again")) {
|
||||
printf("FAIL: queue made again after removal\n");
|
||||
return 1;
|
||||
}
|
||||
msgctl(again, IPC_RMID, NULL);
|
||||
int watched = msgget(0x5eed0003, IPC_CREAT | 0600);
|
||||
pid_t blocked = fork();
|
||||
if (blocked == 0) return msgrcv(watched, &n, sizeof(n.text), 0, 0) < 0 && errno == EIDRM ? 0 : 1;
|
||||
int filler[64];
|
||||
for (int i = 0; i < 64; i++) {
|
||||
struct note f = {5, "fill"};
|
||||
filler[i] = msgget(0x5eed0100 + i, IPC_CREAT | 0600);
|
||||
if (filler[i] < 0 || msgsnd(filler[i], &f, sizeof(f.text), 0)) { printf("FAIL: filler %d\n", i); return 1; }
|
||||
}
|
||||
usleep(100000);
|
||||
if (msgctl(watched, IPC_RMID, NULL) != 0) { perror("msgctl with a full cache"); return 1; }
|
||||
waitpid(blocked, &status, 0);
|
||||
if (!WIFEXITED(status) || WEXITSTATUS(status)) { printf("FAIL: waiter not woken with a full cache\n"); return 1; }
|
||||
int extra = msgget(0x5eed0200, IPC_CREAT | 0600);
|
||||
struct note x = {6, "extra"};
|
||||
if (extra < 0 || msgsnd(extra, &x, sizeof(x.text), 0) || msgrcv(extra, &n, sizeof(n.text), 6, 0) < 0 || strcmp(n.text, "extra")) {
|
||||
printf("FAIL: queue past a full cache\n");
|
||||
return 1;
|
||||
}
|
||||
msgctl(extra, IPC_RMID, NULL);
|
||||
for (int i = 0; i < 64; i++) msgctl(filler[i], IPC_RMID, NULL);
|
||||
printf("PASS: sysv msg\n");
|
||||
return 0;
|
||||
}
|
||||
@@ -412,6 +412,18 @@ class AgentTest(unittest.TestCase):
|
||||
with patch.object(agent, "cdp_eval", side_effect=agent.AgentError("NO_DEVTOOLS", "down")):
|
||||
self.assertEqual(1, agent.main(["--steam-asleep"]))
|
||||
|
||||
def test_supports_vr_command_separates_vr_flat_and_unknown_apps(self):
|
||||
with patch.dict(os.environ, {"BL_LAUNCH_DIR": str(self.dir.parent)}):
|
||||
for value, code in ((True, 0), (False, 5), (None, 1)):
|
||||
with self.subTest(value=value), patch.object(agent, "cdp_eval", return_value={"value": value}) as ask:
|
||||
self.assertEqual(code, agent.main(["--steam-supports-vr", "204360"]))
|
||||
self.assertIn('GetAppOverviewByGameID?.("204360")', ask.call_args.args[1])
|
||||
self.assertIn("vr_supported", ask.call_args.args[1])
|
||||
with patch.object(agent, "cdp_eval", side_effect=agent.AgentError("NO_DEVTOOLS", "down")):
|
||||
self.assertEqual(1, agent.main(["--steam-supports-vr", "204360"]))
|
||||
for bad in ([], ["1;x"], ["-1"], ["1", "2"]):
|
||||
self.assertEqual(2, agent.main(["--steam-supports-vr"] + bad))
|
||||
|
||||
def test_idle_inhibit_command_reports_whether_steam_reached_the_state(self):
|
||||
with patch.dict(os.environ, {"BL_LAUNCH_DIR": str(self.dir.parent)}):
|
||||
for value, code in ((True, 0), (False, 1), (None, 1)):
|
||||
|
||||
@@ -6,6 +6,7 @@ import os
|
||||
import runpy
|
||||
import shutil
|
||||
import struct
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
@@ -866,6 +867,22 @@ class AppInfoTest(unittest.TestCase):
|
||||
self.assertIn('"from_oslist" "linux"', vdf)
|
||||
self.assertIn('"to_oslist" "linux"', vdf)
|
||||
|
||||
def test_the_tool_runs_games_on_the_chosen_cores(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
tool, bin_dir = Path(tmp) / "droiddeck-fex", Path(tmp) / "bin"
|
||||
self.COMPAT["build_fex_tool"](str(tool))
|
||||
bin_dir.mkdir()
|
||||
(bin_dir / "taskset").write_text('#!/bin/sh\necho "taskset $*"\n')
|
||||
(bin_dir / "taskset").chmod(0o755)
|
||||
env = dict(os.environ, PATH="%s:%s" % (bin_dir, os.environ.get("PATH", "")), BL_GAME_CPUS="2-7")
|
||||
run = subprocess.run([str(tool / "droiddeck-fex-tool"), "waitforexitandrun", "/games/a/game"],
|
||||
env=env, capture_output=True, text=True, timeout=10)
|
||||
self.assertEqual(run.stdout,
|
||||
"taskset -c 2-7 /usr/local/bin/droiddeck-fex steam waitforexitandrun /games/a/game\n")
|
||||
self.assertIn("game cores 2-7", run.stderr)
|
||||
self.assertIn('exec /usr/local/bin/droiddeck-steamvr-game ${BL_TASKSET:-} '
|
||||
'/usr/local/bin/droiddeck-fex steam "$verb" "$@"', self.COMPAT["FEX_LAUNCHER_SH"])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -4,6 +4,7 @@ import os
|
||||
import shutil
|
||||
from pathlib import Path
|
||||
import runpy
|
||||
import shlex
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
@@ -94,6 +95,73 @@ class GameEnvironmentTest(unittest.TestCase):
|
||||
self.assertEqual(calls[0][0][1], str(root))
|
||||
self.assertEqual(calls[0][1]["DROIDDECK_SEED_SCRIPTS"], str(script))
|
||||
|
||||
SCRIPT = ('"evaluatorscript" { "0" { "appid" "228980" "compat_installscript" { "run process" { '
|
||||
'"x64 14.28.29334.0" { "hasrunkey" "HKEY_LOCAL_MACHINE\\\\Software\\\\Valve\\\\Steam\\\\Apps\\\\CommonRedist\\\\vcredist\\\\2019" '
|
||||
'"process 1" "%INSTALLDIR%\\\\x64.cmd" "requirement_os" { "Is64BitWindows" "1" } } '
|
||||
'"Setup" { "process 1" "%INSTALLDIR%\\\\setup.exe" } } } } }')
|
||||
REDIST = "[Software\\\\Wow6432Node\\\\Valve\\\\Steam\\\\Apps\\\\CommonRedist\\\\vcredist\\\\2019] 1\n\"x64 14.28.29334.0\"=dword:00000001\n"
|
||||
SETUP = "[Software\\\\Valve\\\\Steam\\\\Apps\\\\228980] 1\n\"Setup\"=dword:00000001\n"
|
||||
|
||||
def test_install_script_run_keys_default_to_the_app_key(self):
|
||||
keys = MODULE["run_keys"](MODULE["read_vdf"](self.SCRIPT))
|
||||
self.assertEqual(keys, {
|
||||
("hkey_local_machine\\software\\valve\\steam\\apps\\commonredist\\vcredist\\2019", "x64 14.28.29334.0"),
|
||||
("hkey_local_machine\\software\\valve\\steam\\apps\\228980", "setup"),
|
||||
})
|
||||
with self.assertRaises(ValueError):
|
||||
MODULE["read_vdf"]('"a" { "b" }')
|
||||
|
||||
def test_install_scripts_count_as_done_only_when_recorded_and_still_marked(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
script = Path(tmp) / "evaluatorscript_1.vdf"
|
||||
script.write_text(self.SCRIPT)
|
||||
prefix = Path(tmp) / "compat/pfx"
|
||||
env = {"STEAM_COMPAT_DATA_PATH": str(prefix.parent)}
|
||||
done = MODULE["install_scripts_done"]
|
||||
self.assertFalse(done([str(script)], env))
|
||||
prefix.mkdir(parents=True)
|
||||
MODULE["record_install_scripts"](MODULE["scripts_digest"]([str(script)]), env)
|
||||
self.assertFalse(done([str(script)], env))
|
||||
(prefix / "system.reg").write_text(self.REDIST)
|
||||
self.assertFalse(done([str(script)], env))
|
||||
(prefix / "system.reg").write_text(self.REDIST + self.SETUP)
|
||||
self.assertTrue(done([str(script)], env))
|
||||
script.write_text(self.SCRIPT.replace("x64.cmd", "x64-update.cmd"))
|
||||
self.assertFalse(done([str(script)], env))
|
||||
script.write_text('"InstallScript" { "Registry" { "HKEY_LOCAL_MACHINE\\\\Software\\\\Game" { "string" { "Path" "%INSTALLDIR%" } } } }')
|
||||
MODULE["record_install_scripts"](MODULE["scripts_digest"]([str(script)]), env)
|
||||
self.assertFalse(done([str(script)], env))
|
||||
|
||||
def test_the_evaluator_is_skipped_once_it_finished_the_same_scripts(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
root = Path(tmp)
|
||||
(root / "legacycompat").mkdir()
|
||||
evaluator = root / "legacycompat/iscriptevaluator.exe"
|
||||
evaluator.write_bytes(b"evaluator")
|
||||
script = root / "legacycompat/evaluatorscript_1.vdf"
|
||||
prefix = root / "compatdata/1/pfx"
|
||||
prefix.mkdir(parents=True)
|
||||
(prefix / "system.reg").write_text(self.REDIST + self.SETUP)
|
||||
runs = root / "runs"
|
||||
proton = root / "proton"
|
||||
proton.write_text("#!/bin/sh\necho run >> %s\nexit ${EXIT_CODE:-0}\n" % shlex.quote(str(runs)))
|
||||
proton.chmod(0o755)
|
||||
|
||||
def evaluate(exit_code="0"):
|
||||
script.write_text(self.SCRIPT if exit_code != "changed" else self.SCRIPT.replace("setup.exe", "setup-update.exe"))
|
||||
env = dict(os.environ, HOME=tmp, STEAM_COMPAT_CLIENT_INSTALL_PATH=str(root),
|
||||
STEAM_COMPAT_DATA_PATH=str(prefix.parent), EXIT_CODE="0" if exit_code == "changed" else exit_code)
|
||||
result = subprocess.run([sys.executable, str(BIN / "droiddeck-game-env"), str(proton), "run",
|
||||
str(evaluator), "legacycompat\\evaluatorscript_1.vdf"],
|
||||
env=env, text=True, capture_output=True)
|
||||
return result.returncode, len(runs.read_text().splitlines()) if runs.exists() else 0
|
||||
|
||||
self.assertEqual(evaluate("3"), (3, 1))
|
||||
self.assertFalse((prefix / ".droiddeck-install-scripts").exists())
|
||||
self.assertEqual(evaluate(), (0, 2))
|
||||
self.assertEqual(evaluate(), (0, 2))
|
||||
self.assertEqual(evaluate("changed"), (0, 3))
|
||||
|
||||
def test_profile_precedence_and_unset(self):
|
||||
env = {"KEEP": "inherited", "REMOVE": "inherited", "CUSTOM": "launch option"}
|
||||
config = {"version": 1, "shared": {"CUSTOM": "shared"}, "games": {"42": {"REMOVE": None, "CUSTOM": "game", "EMPTY": ""}}}
|
||||
|
||||
@@ -7,6 +7,7 @@ import tempfile
|
||||
import unittest
|
||||
|
||||
PRELOAD = Path(__file__).resolve().parents[1] / "linuxfs/preload"
|
||||
FASTPATH = Path(__file__).resolve().parents[1] / "proot/fastpath/fastpath.c"
|
||||
|
||||
# Opens each "<dirfd>\t<flags>\t<path>" case with openat2(RESOLVE_IN_ROOT) as FEX does: first through the kernel's own
|
||||
# openat2 on argv[1] when it has one, then, with openat2 failing ENOSYS as under proot, through the preload on argv[2].
|
||||
@@ -84,6 +85,62 @@ int main(int argc, char **argv) {
|
||||
}
|
||||
"""
|
||||
|
||||
COUNTER = r"""
|
||||
#define _GNU_SOURCE
|
||||
#include <dlfcn.h>
|
||||
#include <fcntl.h>
|
||||
#include <stdarg.h>
|
||||
#include <stdio.h>
|
||||
#include <sys/stat.h>
|
||||
#include <unistd.h>
|
||||
|
||||
static int opens, stats, links;
|
||||
|
||||
int openat(int dirfd, const char *path, int flags, ...) {
|
||||
va_list args;
|
||||
va_start(args, flags);
|
||||
mode_t mode = va_arg(args, int);
|
||||
va_end(args);
|
||||
opens++;
|
||||
return ((int (*)(int, const char *, int, ...))dlsym(RTLD_NEXT, "openat"))(dirfd, path, flags, mode);
|
||||
}
|
||||
|
||||
int fstatat(int dirfd, const char *path, struct stat *st, int flags) {
|
||||
stats++;
|
||||
return ((int (*)(int, const char *, struct stat *, int))dlsym(RTLD_NEXT, "fstatat"))(dirfd, path, st, flags);
|
||||
}
|
||||
|
||||
int fstatat64(int dirfd, const char *path, struct stat64 *st, int flags) {
|
||||
stats++;
|
||||
return ((int (*)(int, const char *, struct stat64 *, int))dlsym(RTLD_NEXT, "fstatat64"))(dirfd, path, st, flags);
|
||||
}
|
||||
|
||||
ssize_t readlinkat(int dirfd, const char *path, char *buf, size_t size) {
|
||||
links++;
|
||||
return ((ssize_t (*)(int, const char *, char *, size_t))dlsym(RTLD_NEXT, "readlinkat"))(dirfd, path, buf, size);
|
||||
}
|
||||
|
||||
__attribute__((destructor)) static void report(void) {
|
||||
fprintf(stderr, "calls %d %d %d\n", opens, stats, links);
|
||||
}
|
||||
"""
|
||||
|
||||
RAW_OPEN = r"""
|
||||
#define _GNU_SOURCE
|
||||
#include <fcntl.h>
|
||||
#include <stdio.h>
|
||||
#include <sys/syscall.h>
|
||||
#include <unistd.h>
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
char text[16] = "";
|
||||
long fd = syscall(SYS_openat, AT_FDCWD, argv[1], O_RDONLY | O_CLOEXEC, 0);
|
||||
if (fd < 0 || read((int)fd, text, sizeof(text) - 1) < 0) return 1;
|
||||
printf("%s\n", text);
|
||||
return syscall(SYS_openat, AT_FDCWD, argv[2], O_RDONLY | O_CLOEXEC, 0) == -1 ? 0 : 1;
|
||||
}
|
||||
"""
|
||||
|
||||
O_PATH = getattr(os, "O_PATH", 0o10000000)
|
||||
|
||||
# (dirfd: r = the tree, o = "/"), flags, path, expected: a path in the tree, an errno name, or "proc" for a file outside it.
|
||||
@@ -191,6 +248,37 @@ class Openat2PreloadTest(unittest.TestCase):
|
||||
lines = result.stdout.splitlines()
|
||||
cls.kernel = labels(lines[1:1 + len(CASES)], cls.trees[0], cls.outside) if lines[0] == "kernel" else None
|
||||
cls.preload = labels(lines[-len(every):], cls.trees[1], cls.outside)
|
||||
counter = cls.tmp / "counter.c"
|
||||
counter.write_text(COUNTER)
|
||||
(cls.tmp / "fp").mkdir()
|
||||
subprocess.run(["cc", "-O2", "-Wall", "-Werror", "-fPIC", "-shared", "-o", str(cls.tmp / "fp/libblfastpath.so"),
|
||||
str(counter), "-ldl"], check=True)
|
||||
tree = cls.tmp / "counted"
|
||||
make_tree(tree, cls.outside)
|
||||
counted = subprocess.run([str(cls.tmp / "openat2"), str(tree), str(tree)], input=cases, capture_output=True,
|
||||
text=True, env=dict(os.environ, LD_PRELOAD="%s:%s" % (cls.lib, cls.tmp / "fp/libblfastpath.so")),
|
||||
timeout=60)
|
||||
if counted.returncode != 0:
|
||||
raise AssertionError(counted.stdout + counted.stderr)
|
||||
cls.counted = labels(counted.stdout.splitlines()[-len(every):], tree, cls.outside)
|
||||
cls.calls = [int(n) for n in counted.stderr.split("calls ")[-1].split()]
|
||||
raw = cls.tmp / "raw_open.c"
|
||||
raw.write_text(RAW_OPEN)
|
||||
subprocess.run(["cc", "-O2", "-Wall", "-Werror", "-o", str(cls.tmp / "raw_open"), str(raw)], check=True)
|
||||
cls.raw = subprocess.run([str(cls.tmp / "raw_open"), str(tree / "etc/hostname"), str(tree / "missing")],
|
||||
capture_output=True, text=True, timeout=60,
|
||||
env=dict(os.environ, LD_PRELOAD="%s:%s" % (cls.lib, cls.tmp / "fp/libblfastpath.so")))
|
||||
(cls.tmp / "real").mkdir()
|
||||
subprocess.run(["cc", "-O2", "-Wall", "-Werror", "-fPIC", "-shared", "-pthread", "-o",
|
||||
str(cls.tmp / "real/libblfastpath.so"), str(FASTPATH), "-ldl"], check=True)
|
||||
shutil.copy(cls.tmp / "raw_open", cls.tmp / "FEX")
|
||||
try:
|
||||
cls.fex = subprocess.run([str(cls.tmp / "FEX"), str(tree / "etc/hostname"), str(tree / "missing")],
|
||||
capture_output=True, text=True, timeout=20,
|
||||
env=dict(os.environ, PROOT_FP_ROOT="/", PROOT_FP_KEY="test",
|
||||
LD_PRELOAD="%s:%s" % (cls.lib, cls.tmp / "real/libblfastpath.so")))
|
||||
except subprocess.TimeoutExpired:
|
||||
cls.fex = None
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
@@ -205,6 +293,20 @@ class Openat2PreloadTest(unittest.TestCase):
|
||||
for case, got in zip(HOST_CASES, self.preload[len(CASES):]):
|
||||
self.assertEqual(got, case[3], case)
|
||||
|
||||
def test_the_walk_asks_the_fast_path_when_it_is_loaded(self):
|
||||
self.assertEqual(self.counted, self.preload)
|
||||
self.assertTrue(all(n > 0 for n in self.calls), self.calls)
|
||||
|
||||
def test_a_raw_openat_syscall_asks_the_fast_path_too(self):
|
||||
self.assertEqual(self.raw.returncode, 0, self.raw.stderr)
|
||||
self.assertEqual(self.raw.stdout, "inside\n")
|
||||
self.assertEqual(self.raw.stderr.split("calls ")[-1].split(), ["2", "0", "0"])
|
||||
|
||||
def test_a_first_raw_openat_in_fex_does_not_wait_on_the_fast_path_starting(self):
|
||||
self.assertIsNotNone(self.fex, "hung")
|
||||
self.assertEqual(self.fex.returncode, 0, self.fex.stderr)
|
||||
self.assertEqual(self.fex.stdout, "inside\n")
|
||||
|
||||
def test_the_kernel_agrees(self):
|
||||
if self.kernel is None:
|
||||
self.skipTest("this kernel or sandbox has no openat2")
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
import os
|
||||
import subprocess
|
||||
import tarfile
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
SOURCE = Path(__file__).resolve().parents[1] / 'linuxfs/overlay/usr/local/bin/droiddeck-pipewire'
|
||||
|
||||
|
||||
class PipeWireHelperTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.temporary = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.temporary.cleanup)
|
||||
self.root = Path(self.temporary.name)
|
||||
self.lib = self.root / 'lib'
|
||||
self.runtime = self.root / 'run'
|
||||
self.lib.mkdir()
|
||||
self.runtime.mkdir()
|
||||
self.bundle = self.lib / 'droiddeck-pipewire.tzst'
|
||||
self.dir = self.lib / 'droiddeck-pipewire'
|
||||
text = SOURCE.read_text().replace('/usr/local/lib/droiddeck-pipewire', str(self.dir))
|
||||
self.helper = self.root / 'droiddeck-pipewire'
|
||||
self.helper.write_text(text)
|
||||
self.environment = dict(os.environ, XDG_RUNTIME_DIR=str(self.runtime))
|
||||
|
||||
def pack(self, daemon_body):
|
||||
tree = self.root / 'tree'
|
||||
for name, body in (('pipewire', daemon_body), ('wireplumber', 'exec sleep 30')):
|
||||
path = tree / 'bin' / name
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text('#!/bin/sh\n' + body + '\n')
|
||||
path.chmod(0o755)
|
||||
tar = self.root / 'bundle.tar'
|
||||
with tarfile.open(tar, 'w') as archive:
|
||||
archive.add(tree, arcname='.')
|
||||
subprocess.run(['zstd', '-q', '-f', str(tar), '-o', str(self.bundle)], check=True)
|
||||
|
||||
def run_helper(self, *args):
|
||||
with tempfile.TemporaryFile('w+') as out, tempfile.TemporaryFile('w+') as err:
|
||||
done = subprocess.run(['sh', str(self.helper), *args], env=self.environment, stdout=out, stderr=err,
|
||||
text=True, timeout=15)
|
||||
out.seek(0)
|
||||
err.seek(0)
|
||||
return subprocess.CompletedProcess(done.args, done.returncode, out.read(), err.read())
|
||||
|
||||
def tearDown(self):
|
||||
self.run_helper('stop')
|
||||
|
||||
def test_env_points_clients_at_the_bundle(self):
|
||||
out = self.run_helper('env').stdout
|
||||
for part in ('PIPEWIRE_CONFIG_DIR=%s/share/pipewire', 'PIPEWIRE_MODULE_DIR=%s/lib/pipewire-0.3',
|
||||
'SPA_PLUGIN_DIR=%s/lib/spa-0.2'):
|
||||
self.assertIn(part % self.dir, out)
|
||||
|
||||
def test_start_waits_for_the_socket_and_stop_ends_both_daemons(self):
|
||||
socket = self.runtime / 'pipewire-0'
|
||||
self.pack('python3 -c "import socket,sys; s=socket.socket(socket.AF_UNIX); s.bind(sys.argv[1]); '
|
||||
'import time; time.sleep(30)" "$XDG_RUNTIME_DIR/pipewire-0"')
|
||||
result = self.run_helper('start')
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertTrue(socket.is_socket())
|
||||
pids = (self.runtime / 'droiddeck-pipewire/pids').read_text().split()
|
||||
self.assertEqual(len(pids), 2)
|
||||
self.run_helper('stop')
|
||||
for pid in pids:
|
||||
subprocess.run(['sh', '-c', 'for i in 1 2 3 4 5 6 7 8 9 10; do kill -0 %s 2>/dev/null || exit 0; '
|
||||
'sleep 0.1; done; exit 1' % pid], check=True)
|
||||
|
||||
def test_start_fails_cleanly_when_pipewire_never_listens(self):
|
||||
self.pack('exec sleep 30')
|
||||
result = self.run_helper('start')
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertIn('did not open', result.stderr)
|
||||
self.assertFalse((self.runtime / 'droiddeck-pipewire/pids').exists())
|
||||
|
||||
def test_unchanged_bundle_is_not_unpacked_again(self):
|
||||
self.pack('exec sleep 30')
|
||||
self.run_helper('start')
|
||||
marker = self.dir / 'kept'
|
||||
marker.write_text('x')
|
||||
self.run_helper('start')
|
||||
self.assertTrue(marker.exists())
|
||||
self.pack('exec sleep 31')
|
||||
self.run_helper('start')
|
||||
self.assertFalse(marker.exists())
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -53,6 +53,8 @@ class SeedRedistsTest(unittest.TestCase):
|
||||
self.reg = self.steam / "steamapps/compatdata/1234/pfx/system.reg"
|
||||
self.reg.parent.mkdir(parents=True)
|
||||
self.reg.write_text("WINE REGISTRY Version 2\n")
|
||||
self.user = self.reg.with_name("user.reg")
|
||||
self.user.write_text('WINE REGISTRY Version 2\n\n[Software\\\\Unrelated] 1\n"Keep"="untouched"\n')
|
||||
|
||||
def game(self, name="Some Game", script=GAME_SCRIPT, library=None):
|
||||
root = Path(library or self.steam)
|
||||
@@ -81,6 +83,93 @@ class SeedRedistsTest(unittest.TestCase):
|
||||
self.run_seed(str(sd))
|
||||
self.assertIn('"VCRedist2022"=dword:00000001', self.reg.read_text())
|
||||
|
||||
def test_current_user_and_machine_markers_go_to_their_own_registries(self):
|
||||
self.game(script=GAME_SCRIPT + GAME_SCRIPT.replace("HKEY_LOCAL_MACHINE", "HKEY_CURRENT_USER").replace("VCRedist2022", "UserRedist"))
|
||||
with self.reg.open("a") as out:
|
||||
out.write('\n[Software\\\\Unrelated] 1\n"Keep"="machine"\n')
|
||||
for reg in (self.reg, self.user):
|
||||
os.utime(reg, ns=(1_000_000_000_123456789, 1_000_000_000_123456789))
|
||||
self.run_seed()
|
||||
system, user = self.reg.read_text(), self.user.read_text()
|
||||
self.assertEqual(system.count('"VCRedist2022"=dword:00000001'), 2)
|
||||
self.assertNotIn("UserRedist", system)
|
||||
self.assertEqual(user.count('"UserRedist"=dword:00000001'), 1)
|
||||
self.assertNotIn("Wow6432Node", user)
|
||||
self.assertNotIn("VCRedist2022", user)
|
||||
self.assertIn('"Keep"="machine"', system)
|
||||
self.assertIn('"Keep"="untouched"', user)
|
||||
self.run_seed()
|
||||
self.assertEqual(system, self.reg.read_text())
|
||||
self.assertEqual(user, self.user.read_text())
|
||||
for reg in (self.reg, self.user):
|
||||
self.assertEqual(reg.stat().st_mtime_ns, 1_000_000_000_123456789)
|
||||
|
||||
def test_a_user_marker_with_the_same_machine_path_and_value_is_separate(self):
|
||||
self.game(script=GAME_SCRIPT + GAME_SCRIPT.replace("HKEY_LOCAL_MACHINE", "HKEY_CURRENT_USER"))
|
||||
self.run_seed()
|
||||
system = self.reg.read_text()
|
||||
self.assertEqual(self.user.read_text().count('"VCRedist2022"=dword:00000001'), 1)
|
||||
self.user.write_text("WINE REGISTRY Version 2\n")
|
||||
self.run_seed()
|
||||
self.assertEqual(self.user.read_text().count('"VCRedist2022"=dword:00000001'), 1)
|
||||
self.assertEqual(system, self.reg.read_text())
|
||||
|
||||
def test_a_legacy_user_ledger_entry_is_checked_in_user_reg(self):
|
||||
self.game(script=GAME_SCRIPT.replace("HKEY_LOCAL_MACHINE", "HKEY_CURRENT_USER"))
|
||||
self.run_seed()
|
||||
system = self.reg.read_bytes()
|
||||
self.user.write_text("WINE REGISTRY Version 2\n")
|
||||
(self.reg.parent / ".droiddeck-redists-checked").write_text(subprocess.check_output(["stat", "-c", "%i %s %.9Y", str(self.reg)], text=True))
|
||||
self.run_seed()
|
||||
self.assertEqual(self.user.read_text().count('"VCRedist2022"=dword:00000001'), 1)
|
||||
self.assertEqual(system, self.reg.read_bytes())
|
||||
|
||||
def test_an_absent_user_registry_is_not_created_or_claimed(self):
|
||||
self.game(script=GAME_SCRIPT + GAME_SCRIPT.replace("HKEY_LOCAL_MACHINE", "HKEY_CURRENT_USER").replace("VCRedist2022", "UserRedist"))
|
||||
self.user.unlink()
|
||||
self.run_seed()
|
||||
self.assertFalse(self.user.exists())
|
||||
self.assertNotIn("UserRedist", (self.reg.parent / ".droiddeck-redists").read_text())
|
||||
self.assertEqual(self.reg.read_text().count('"VCRedist2022"=dword:00000001'), 2)
|
||||
system = self.reg.read_bytes()
|
||||
self.user.write_text("WINE REGISTRY Version 2\n")
|
||||
self.run_seed()
|
||||
self.assertIn('"UserRedist"=dword:00000001', self.user.read_text())
|
||||
self.run_seed()
|
||||
self.user.unlink()
|
||||
self.run_seed()
|
||||
self.assertFalse(self.user.exists())
|
||||
self.assertNotIn("UserRedist", (self.reg.parent / ".droiddeck-redists").read_text())
|
||||
self.assertEqual(system, self.reg.read_bytes())
|
||||
|
||||
@unittest.skipIf(os.name == "posix" and os.geteuid() == 0, "root can write through read-only mode bits")
|
||||
def test_an_unwritable_user_registry_does_not_claim_a_missing_marker(self):
|
||||
self.game(script=GAME_SCRIPT + GAME_SCRIPT.replace("HKEY_LOCAL_MACHINE", "HKEY_CURRENT_USER").replace("VCRedist2022", "UserRedist"))
|
||||
ledger = self.reg.parent / ".droiddeck-redists"
|
||||
ledger.write_text("HKEY_CURRENT_USER\\\\Software\\\\Valve\\\\Steam\\\\Apps\\\\CommonRedist\\\\vcredist\\\\2022\tUserRedist\n")
|
||||
user = self.user.read_bytes()
|
||||
self.user.chmod(0o444)
|
||||
try:
|
||||
self.run_seed()
|
||||
self.assertEqual(user, self.user.read_bytes())
|
||||
self.assertEqual(self.user.stat().st_mode & 0o777, 0o444)
|
||||
self.assertNotIn("UserRedist", ledger.read_text())
|
||||
self.assertEqual(self.reg.read_text().count('"VCRedist2022"=dword:00000001'), 2)
|
||||
finally:
|
||||
self.user.chmod(0o644)
|
||||
|
||||
def test_user_markers_in_a_default_prefix_and_another_library_are_seeded(self):
|
||||
default = self.steam / "steamapps/common/Proton Test/files/share/default_pfx"
|
||||
default.mkdir(parents=True)
|
||||
for name in ("system.reg", "user.reg"):
|
||||
(default / name).write_text("WINE REGISTRY Version 2\n")
|
||||
sd = self.tmp / "sd"
|
||||
self.game(library=sd, script=GAME_SCRIPT.replace("HKEY_LOCAL_MACHINE", "HKEY_CURRENT_USER"))
|
||||
self.run_seed(str(sd))
|
||||
self.assertIn('"VCRedist2022"=dword:00000001', (default / "user.reg").read_text())
|
||||
self.assertNotIn('"VCRedist2022"', (default / "system.reg").read_text())
|
||||
self.assertIn('"VCRedist2022"=dword:00000001', self.user.read_text())
|
||||
|
||||
def test_the_vc_runtime_is_recorded_for_every_architecture_and_view(self):
|
||||
self.run_seed()
|
||||
reg = self.reg.read_text()
|
||||
@@ -156,7 +245,7 @@ class SeedRedistsTest(unittest.TestCase):
|
||||
self.assertIn('"x64 14.99.1.0"=dword:00000001', self.reg.read_text())
|
||||
|
||||
def test_an_unchanged_registry_is_not_read_again(self):
|
||||
self.game()
|
||||
self.game(script=GAME_SCRIPT + GAME_SCRIPT.replace("HKEY_LOCAL_MACHINE", "HKEY_CURRENT_USER").replace("VCRedist2022", "UserRedist"))
|
||||
self.run_seed()
|
||||
self.run_seed()
|
||||
shim = self.tmp / "bin"
|
||||
@@ -166,9 +255,21 @@ class SeedRedistsTest(unittest.TestCase):
|
||||
(shim / "awk").chmod(0o755)
|
||||
env = dict(os.environ, DROIDDECK_LIBRARIES="", PATH="%s:%s" % (shim, os.environ["PATH"]))
|
||||
once = self.reg.read_text()
|
||||
user = self.user.read_text()
|
||||
subprocess.run(["bash", str(SCRIPT), str(self.steam)], env=env, capture_output=True, text=True, check=True)
|
||||
self.assertEqual(once, self.reg.read_text())
|
||||
self.assertEqual(user, self.user.read_text())
|
||||
self.assertNotIn(str(self.reg), log.read_text() if log.exists() else "")
|
||||
self.assertNotIn(str(self.user), log.read_text() if log.exists() else "")
|
||||
replaced = self.user.with_name("user.reg.new")
|
||||
replaced.write_text(user.replace('"UserRedist"', '"OtherValue"'))
|
||||
os.utime(replaced, ns=(self.user.stat().st_atime_ns, self.user.stat().st_mtime_ns))
|
||||
self.assertEqual(replaced.stat().st_size, self.user.stat().st_size)
|
||||
os.replace(replaced, self.user)
|
||||
subprocess.run(["bash", str(SCRIPT), str(self.steam)], env=env, capture_output=True, text=True, check=True)
|
||||
self.assertEqual(self.user.read_text().count('"UserRedist"=dword:00000001'), 1)
|
||||
self.assertIn('"OtherValue"=dword:00000001', self.user.read_text())
|
||||
self.assertEqual(once, self.reg.read_text())
|
||||
replaced = self.reg.with_name("system.reg.new")
|
||||
replaced.write_text("WINE REGISTRY Version 2\n")
|
||||
os.replace(replaced, self.reg)
|
||||
@@ -194,6 +295,39 @@ class SeedRedistsTest(unittest.TestCase):
|
||||
self.assertIn('"RockstarLauncher"=dword:00000001', reg)
|
||||
self.assertNotIn("Vulkan111080", (self.reg.parent / ".droiddeck-redists").read_text())
|
||||
|
||||
def test_a_current_user_vulkan_installer_is_left_to_run(self):
|
||||
self.game(script=VULKAN_SCRIPT.replace("HKEY_LOCAL_MACHINE", "HKEY_CURRENT_USER"))
|
||||
self.run_seed()
|
||||
self.assertIn('"RockstarLauncher"=dword:00000001', self.user.read_text())
|
||||
self.assertNotIn("Vulkan111080", self.user.read_text())
|
||||
self.assertNotIn("Vulkan111080", self.reg.read_text())
|
||||
self.assertNotIn("Vulkan111080", (self.reg.parent / ".droiddeck-redists").read_text())
|
||||
|
||||
def test_a_current_user_vulkan_marker_comes_out_of_only_its_own_hive(self):
|
||||
self.game(script=VULKAN_SCRIPT.replace("HKEY_LOCAL_MACHINE", "HKEY_CURRENT_USER"))
|
||||
self.run_seed()
|
||||
system = self.reg.read_bytes() + b'\n[Software\\\\Valve\\\\Steam\\\\Apps\\\\1174180] 1\n"Vulkan111080"=dword:00000001\n'
|
||||
self.reg.write_bytes(system)
|
||||
with self.user.open("a") as out:
|
||||
out.write('\n[Software\\\\Valve\\\\Steam\\\\Apps\\\\1174180] 1\n"Other"="keep"\n"Vulkan111080"=dword:00000001\n'
|
||||
'\n[Software\\\\Wow6432Node\\\\Valve\\\\Steam\\\\Apps\\\\1174180] 1\n"Vulkan111080"=dword:00000001\n'
|
||||
'\n[Software\\\\Valve\\\\Steam\\\\Apps\\\\22380] 1\n"Vulkan111080"=dword:00000001\n')
|
||||
with (self.reg.parent / ".droiddeck-redists").open("a") as out:
|
||||
out.write("HKEY_CURRENT_USER\\\\Software\\\\Valve\\\\Steam\\\\Apps\\\\1174180\tVulkan111080\n")
|
||||
os.utime(self.user, ns=(1_000_000_000_123456789, 1_000_000_000_123456789))
|
||||
self.run_seed()
|
||||
user = self.user.read_text()
|
||||
self.assertEqual(user.count('"Vulkan111080"'), 2, "the other path and the unseeded user view stay")
|
||||
self.assertIn('"Other"="keep"', user)
|
||||
self.assertEqual(system, self.reg.read_bytes())
|
||||
self.assertNotIn("Vulkan111080", (self.reg.parent / ".droiddeck-redists").read_text())
|
||||
self.assertEqual(self.user.stat().st_mtime_ns, 1_000_000_000_123456789)
|
||||
with self.user.open("a") as out:
|
||||
out.write('\n[Software\\\\Valve\\\\Steam\\\\Apps\\\\1174180] 1\n"Vulkan111080"=dword:00000001\n')
|
||||
user = self.user.read_bytes()
|
||||
self.run_seed()
|
||||
self.assertEqual(user, self.user.read_bytes())
|
||||
|
||||
def test_a_vulkan_marker_an_earlier_seeding_wrote_comes_out_once(self):
|
||||
self.rdr2()
|
||||
marker = "HKEY_LOCAL_MACHINE\\\\Software\\\\Valve\\\\Steam\\\\Apps\\\\1174180\tVulkan111080"
|
||||
|
||||
@@ -20,6 +20,15 @@ class SysvPreloadTest(unittest.TestCase):
|
||||
result = subprocess.run([binary], capture_output=True, text=True, timeout=10, env=env)
|
||||
self.assertIn('PASS: sysv otime', result.stdout, result.stdout + result.stderr)
|
||||
|
||||
def test_message_queue_mapping_is_reused_and_removal_wakes_waiters(self):
|
||||
with tempfile.TemporaryDirectory() as folder:
|
||||
binary = str(Path(folder) / 'test-sysv-msg')
|
||||
subprocess.run(['gcc', '-Wall', '-Wextra', '-O2', '-pthread', '-o', binary,
|
||||
str(Path(__file__).resolve().parent / 'sysv_msg_harness.c'), str(PRELOAD / 'sysv.c')], check=True)
|
||||
env = dict(os.environ, BL_SYSV_DIR=folder)
|
||||
result = subprocess.run([binary], capture_output=True, text=True, timeout=20, env=env)
|
||||
self.assertIn('PASS: sysv msg', result.stdout, result.stdout + result.stderr)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,227 @@
|
||||
import array
|
||||
import mmap
|
||||
import os
|
||||
import socket
|
||||
import struct
|
||||
import subprocess
|
||||
import tempfile
|
||||
import threading
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
PROTO = ROOT / 'app/src/main/cpp/venc/venc_proto.h'
|
||||
VENC = ROOT / 'tools/linuxfs/preload/venc.c'
|
||||
TOUCH = ROOT / 'tools/linuxfs/preload/rptouch.c'
|
||||
|
||||
DRIVER = r'''
|
||||
#include <errno.h>
|
||||
#include <linux/videodev2.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include <sys/mman.h>
|
||||
|
||||
int bl_venc_open(const char *path, int flags);
|
||||
int bl_venc_ioctl(int fd, unsigned long req, void *arg, int *rc);
|
||||
int bl_venc_mmap(void *addr, size_t len, int prot, int flags, int fd, off_t off,
|
||||
void *(*real)(void *, size_t, int, int, int, off_t), void **out);
|
||||
void bl_venc_closed(int fd);
|
||||
|
||||
static int fd;
|
||||
static int call(unsigned long req, void *arg) {
|
||||
int rc;
|
||||
if (!bl_venc_ioctl(fd, req, arg, &rc)) return -100;
|
||||
return rc < 0 ? -errno : 0;
|
||||
}
|
||||
|
||||
int main(void) {
|
||||
if (bl_venc_open("/dev/video0", 0) != -2) return 2;
|
||||
fd = bl_venc_open("/dev/video-enc0", 0);
|
||||
if (fd < 0) return 3;
|
||||
struct v4l2_capability cap;
|
||||
if (call(VIDIOC_QUERYCAP, &cap) || !(cap.device_caps & V4L2_CAP_VIDEO_M2M_MPLANE)) return 4;
|
||||
struct v4l2_format f = { .type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE };
|
||||
f.fmt.pix_mp.width = 640; f.fmt.pix_mp.height = 360; f.fmt.pix_mp.pixelformat = V4L2_PIX_FMT_NV12;
|
||||
if (call(VIDIOC_S_FMT, &f) || f.fmt.pix_mp.plane_fmt[0].sizeimage != 640 * 360 * 3 / 2) return 5;
|
||||
f = (struct v4l2_format){ .type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE };
|
||||
f.fmt.pix_mp.pixelformat = V4L2_PIX_FMT_HEVC;
|
||||
if (call(VIDIOC_S_FMT, &f) || f.fmt.pix_mp.pixelformat != V4L2_PIX_FMT_HEVC) return 6;
|
||||
struct v4l2_control c = { V4L2_CID_MPEG_VIDEO_BITRATE, 8000000 };
|
||||
if (call(VIDIOC_S_CTRL, &c)) return 7;
|
||||
unsigned types[2] = { V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE, V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE };
|
||||
unsigned char *maps[2][2];
|
||||
for (int t = 0; t < 2; t++) {
|
||||
struct v4l2_requestbuffers r = { .count = 2, .type = types[t], .memory = V4L2_MEMORY_MMAP };
|
||||
if (call(VIDIOC_REQBUFS, &r) || r.count != 2) return 8;
|
||||
for (int i = 0; i < 2; i++) {
|
||||
struct v4l2_plane p;
|
||||
struct v4l2_buffer b = { .index = i, .type = types[t], .memory = V4L2_MEMORY_MMAP, .length = 1, .m.planes = &p };
|
||||
if (call(VIDIOC_QUERYBUF, &b)) return 9;
|
||||
void *m;
|
||||
if (!bl_venc_mmap(NULL, p.length, PROT_READ | PROT_WRITE, MAP_SHARED, fd, p.m.mem_offset, mmap, &m) ||
|
||||
m == MAP_FAILED) return 10;
|
||||
maps[t][i] = m;
|
||||
if (t == 1 && call(VIDIOC_QBUF, &b)) return 11;
|
||||
}
|
||||
if (call(VIDIOC_STREAMON, &types[t])) return 12;
|
||||
}
|
||||
struct v4l2_plane cp;
|
||||
struct v4l2_buffer cb = { .type = types[1], .memory = V4L2_MEMORY_MMAP, .length = 1, .m.planes = &cp };
|
||||
if (call(VIDIOC_DQBUF, &cb) != -EAGAIN) return 13;
|
||||
for (int frame = 0; frame < 3; frame++) {
|
||||
memset(maps[0][frame % 2], 'a' + frame, 640 * 360);
|
||||
struct v4l2_plane p = { .bytesused = 640 * 360 * 3 / 2 };
|
||||
struct v4l2_buffer b = { .index = frame % 2, .type = types[0], .memory = V4L2_MEMORY_MMAP, .length = 1, .m.planes = &p };
|
||||
b.timestamp.tv_sec = frame;
|
||||
if (frame == 1) {
|
||||
struct v4l2_control k = { V4L2_CID_MPEG_VIDEO_FORCE_KEY_FRAME, 1 };
|
||||
call(VIDIOC_S_CTRL, &k);
|
||||
}
|
||||
if (call(VIDIOC_QBUF, &b)) return 14;
|
||||
if (call(VIDIOC_DQBUF, &cb)) return 15;
|
||||
printf("%d %u %d %ld %.*s\n", frame, cp.bytesused, !!(cb.flags & V4L2_BUF_FLAG_KEYFRAME),
|
||||
(long)cb.timestamp.tv_sec, (int)cp.bytesused, maps[1][cb.index]);
|
||||
if (call(VIDIOC_DQBUF, &b)) return 16;
|
||||
if (call(VIDIOC_QBUF, &cb)) return 17;
|
||||
}
|
||||
bl_venc_closed(fd);
|
||||
return 0;
|
||||
}
|
||||
'''
|
||||
|
||||
TOUCH_DRIVER = r'''
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <sys/wait.h>
|
||||
#include <unistd.h>
|
||||
|
||||
int bl_venc_open(const char *path, int flags);
|
||||
void bl_venc_closed(int fd);
|
||||
int XTestFakeMotionEvent(void *dpy, int screen, int x, int y, unsigned long delay);
|
||||
int XTestFakeButtonEvent(void *dpy, unsigned int button, int press, unsigned long delay);
|
||||
int XDisplayWidth(void *dpy, int screen) { return 1281; }
|
||||
int XDisplayHeight(void *dpy, int screen) { return 721; }
|
||||
|
||||
int main(void) {
|
||||
XTestFakeButtonEvent(NULL, 1, 1, 0);
|
||||
XTestFakeButtonEvent(NULL, 1, 0, 0);
|
||||
int fd = bl_venc_open("/dev/video-enc0", 0);
|
||||
if (fd < 0) return 3;
|
||||
XTestFakeMotionEvent(NULL, 0, 1280, 360, 0);
|
||||
XTestFakeButtonEvent(NULL, 1, 1, 0);
|
||||
XTestFakeMotionEvent(NULL, 0, 640, 0, 0);
|
||||
XTestFakeButtonEvent(NULL, 3, 1, 0);
|
||||
XTestFakeButtonEvent(NULL, 1, 0, 0);
|
||||
char marker[512];
|
||||
snprintf(marker, sizeof marker, "%s/droiddeck-remote-play", getenv("XDG_RUNTIME_DIR"));
|
||||
if (access(marker, F_OK) != 0) return 4;
|
||||
pid_t child = fork();
|
||||
if (child == 0) { bl_venc_closed(fd); _exit(access(marker, F_OK) == 0 ? 0 : 1); }
|
||||
int status;
|
||||
waitpid(child, &status, 0);
|
||||
if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) return 5;
|
||||
bl_venc_closed(fd);
|
||||
if (access(marker, F_OK) == 0) return 6;
|
||||
XTestFakeButtonEvent(NULL, 1, 1, 0);
|
||||
usleep(200000);
|
||||
return 0;
|
||||
}
|
||||
'''
|
||||
|
||||
CONFIG = struct.Struct('<' + 'I' * 12 + 'ii' + 'I' * 4)
|
||||
FRAME = struct.Struct('<IIIII4xq')
|
||||
DONE = struct.Struct('<IiII')
|
||||
|
||||
|
||||
class FakeEncoder(threading.Thread):
|
||||
def __init__(self, path):
|
||||
super().__init__(daemon=True)
|
||||
self.listener = socket.socket(socket.AF_UNIX, socket.SOCK_SEQPACKET)
|
||||
self.listener.bind(path)
|
||||
self.listener.listen(1)
|
||||
self.configs, self.frames, self.touches = [], [], []
|
||||
|
||||
def run(self):
|
||||
while True:
|
||||
try:
|
||||
conn, _ = self.listener.accept()
|
||||
except OSError:
|
||||
return
|
||||
threading.Thread(target=self.serve, args=(conn,), daemon=True).start()
|
||||
|
||||
def serve(self, conn):
|
||||
outputs = []
|
||||
while True:
|
||||
fds = array.array('i')
|
||||
msg, ancdata, _, _ = conn.recvmsg(256, socket.CMSG_LEN(32 * fds.itemsize))
|
||||
if not msg:
|
||||
return
|
||||
for level, kind, data in ancdata:
|
||||
if level == socket.SOL_SOCKET and kind == socket.SCM_RIGHTS:
|
||||
fds.frombytes(data[:len(data) - len(data) % fds.itemsize])
|
||||
kind = struct.unpack_from('<I', msg)[0]
|
||||
if kind == 5:
|
||||
self.touches.append(struct.unpack('<IIII', msg)[1:])
|
||||
elif kind == 1:
|
||||
c = CONFIG.unpack(msg)
|
||||
self.configs.append(c)
|
||||
inputs, size = c[14], c[17]
|
||||
outputs = [mmap.mmap(fd, size) for fd in fds[inputs:]]
|
||||
for fd in fds:
|
||||
os.close(fd)
|
||||
conn.send(DONE.pack(3, 0, 0, 0))
|
||||
elif kind == 2:
|
||||
_, _, output, nbytes, key, pts = FRAME.unpack(msg)
|
||||
self.frames.append((nbytes, key, pts))
|
||||
payload = b'frame%d' % len(self.frames)
|
||||
outputs[output][:len(payload)] = payload
|
||||
conn.send(DONE.pack(3, 0, len(payload), 1 if key or len(self.frames) == 1 else 0))
|
||||
|
||||
|
||||
class VencEmulatorTest(unittest.TestCase):
|
||||
def test_steam_style_session_round_trips_through_the_app_socket(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
tmp = Path(tmp)
|
||||
driver = tmp / 'driver.c'
|
||||
driver.write_text(DRIVER)
|
||||
binary = tmp / 'driver'
|
||||
subprocess.run(['cc', '-O1', '-pthread', '-o', str(binary), str(driver), str(VENC), '-ldl'],
|
||||
check=True)
|
||||
sock = tmp / 'venc.sock'
|
||||
server = FakeEncoder(str(sock))
|
||||
self.addCleanup(server.listener.close)
|
||||
server.start()
|
||||
done = subprocess.run([str(binary)], env=dict(os.environ, BL_VENC_SOCKET=str(sock)),
|
||||
capture_output=True, text=True, timeout=20)
|
||||
self.assertEqual(done.returncode, 0, done.stdout + done.stderr)
|
||||
self.assertEqual(done.stdout.split('\n')[:3],
|
||||
['0 6 1 0 frame1', '1 6 1 1 frame2', '2 6 0 2 frame3'])
|
||||
self.assertEqual(len(server.configs), 1)
|
||||
config = server.configs[0]
|
||||
self.assertEqual(config[1], 1)
|
||||
self.assertEqual(config[2:6], (640, 360, 640, 360))
|
||||
self.assertEqual(config[8], 8000000)
|
||||
self.assertEqual([f[1] for f in server.frames], [0, 1, 0])
|
||||
self.assertEqual([f[2] for f in server.frames], [0, 1000000, 2000000])
|
||||
self.assertTrue(all(f[0] == 640 * 360 * 3 // 2 for f in server.frames))
|
||||
|
||||
def test_remote_touch_and_stream_marker_follow_the_streaming_process(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
tmp = Path(tmp)
|
||||
driver = tmp / 'touch.c'
|
||||
driver.write_text(TOUCH_DRIVER)
|
||||
binary = tmp / 'touch'
|
||||
subprocess.run(['cc', '-O1', '-pthread', '-rdynamic', '-o', str(binary), str(driver), str(VENC), str(TOUCH),
|
||||
'-ldl'], check=True)
|
||||
sock = tmp / 'venc.sock'
|
||||
server = FakeEncoder(str(sock))
|
||||
self.addCleanup(server.listener.close)
|
||||
server.start()
|
||||
done = subprocess.run([str(binary)], env=dict(os.environ, BL_VENC_SOCKET=str(sock), XDG_RUNTIME_DIR=str(tmp)),
|
||||
capture_output=True, text=True, timeout=20)
|
||||
self.assertEqual(done.returncode, 0, done.stderr)
|
||||
self.assertEqual(server.touches, [(0, 65535, 32767), (1, 32767, 0), (2, 32767, 0)])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -30,6 +30,7 @@
|
||||
#include "handcam_shm.h"
|
||||
#include "hand_skeleton.h"
|
||||
#include "index_pose.h"
|
||||
#include "pad_controller_config.h"
|
||||
#include "joycon_shm.h"
|
||||
#include "presenter.h"
|
||||
#include "spatial_tracking.h"
|
||||
@@ -1027,45 +1028,57 @@ public:
|
||||
pose_.qWorldFromDriverRotation.w = pose_.qDriverFromHeadRotation.w = pose_.qRotation.w = 1;
|
||||
}
|
||||
|
||||
void SetProfile(PadProfile profile) { profile_ = profile; }
|
||||
|
||||
EVRInitError Activate(uint32_t id) override {
|
||||
id_ = id;
|
||||
PropertyContainerHandle_t c = VRProperties()->TrackedDeviceToPropertyContainer(id_);
|
||||
XrTrackingFile tracking;
|
||||
DroidDeckXrTracking packet{};
|
||||
xrMode_ = tracking.Read(&packet) && XrTrackingFile::Fresh(packet);
|
||||
VRProperties()->SetStringProperty(c, Prop_ModelNumber_String, xrMode_ ? "DroidDeck Quest Touch" : "DroidDeck Pad Hand");
|
||||
VRProperties()->SetStringProperty(c, Prop_ManufacturerName_String, xrMode_ ? "Meta" : "DroidDeck");
|
||||
const PadProfile profile = xrMode_ ? PadProfile::Touch : profile_;
|
||||
touch_ = profile == PadProfile::Touch;
|
||||
index_ = profile == PadProfile::Index;
|
||||
const char *model = touch_ ? "DroidDeck Quest Touch" : index_ ? "DroidDeck Index Hand" : "DroidDeck Pad Hand";
|
||||
VRProperties()->SetStringProperty(c, Prop_ModelNumber_String, model);
|
||||
VRProperties()->SetStringProperty(c, Prop_ManufacturerName_String, touch_ ? "Meta" : index_ ? "Valve" : "DroidDeck");
|
||||
VRProperties()->SetStringProperty(c, Prop_TrackingSystemName_String, "droiddeck");
|
||||
VRProperties()->SetStringProperty(c, Prop_RenderModelName_String, xrMode_ ?
|
||||
VRProperties()->SetStringProperty(c, Prop_RenderModelName_String, touch_ ?
|
||||
(right_ ? "oculus_quest_plus_controller_right" : "oculus_quest_plus_controller_left") :
|
||||
(right_ ? "{indexcontroller}valve_controller_knu_1_0_right" : "{indexcontroller}valve_controller_knu_1_0_left"));
|
||||
VRProperties()->SetStringProperty(c, Prop_ControllerType_String, xrMode_ ? "oculus_touch" : "vive_controller");
|
||||
VRProperties()->SetStringProperty(c, Prop_InputProfilePath_String, xrMode_ ?
|
||||
"{oculus}/input/touch_profile.json" : "{htc}/input/vive_controller_profile.json");
|
||||
VRProperties()->SetStringProperty(c, Prop_ControllerType_String, touch_ ? "oculus_touch" : index_ ? "knuckles" : "vive_controller");
|
||||
VRProperties()->SetStringProperty(c, Prop_InputProfilePath_String, touch_ ? "{oculus}/input/touch_profile.json" :
|
||||
index_ ? "{indexcontroller}/input/index_controller_profile.json" : "{htc}/input/vive_controller_profile.json");
|
||||
VRProperties()->SetInt32Property(c, Prop_ControllerRoleHint_Int32,
|
||||
right_ ? TrackedControllerRole_RightHand : TrackedControllerRole_LeftHand);
|
||||
VRProperties()->SetInt32Property(c, Prop_DeviceClass_Int32, TrackedDeviceClass_Controller);
|
||||
auto in = VRDriverInput();
|
||||
const bool stick = touch_ || index_;
|
||||
const char *stickPath = touch_ ? "/input/joystick" : "/input/thumbstick";
|
||||
const auto path = [](const char *base, const char *leaf) { return std::string(base) + leaf; };
|
||||
in->CreateBooleanComponent(c, "/input/system/click", &system_);
|
||||
in->CreateBooleanComponent(c, "/input/application_menu/click", &menu_);
|
||||
in->CreateBooleanComponent(c, "/input/grip/click", &grip_);
|
||||
if (!index_) in->CreateBooleanComponent(c, "/input/application_menu/click", &menu_);
|
||||
in->CreateBooleanComponent(c, stick ? "/input/grip/touch" : "/input/grip/click", &grip_);
|
||||
in->CreateBooleanComponent(c, "/input/trigger/click", &triggerClick_);
|
||||
in->CreateScalarComponent(c, "/input/trigger/value", &trigger_, VRScalarType_Absolute, VRScalarUnits_NormalizedOneSided);
|
||||
in->CreateScalarComponent(c, xrMode_ ? "/input/joystick/x" : "/input/trackpad/x", &padX_, VRScalarType_Absolute, VRScalarUnits_NormalizedTwoSided);
|
||||
in->CreateScalarComponent(c, xrMode_ ? "/input/joystick/y" : "/input/trackpad/y", &padY_, VRScalarType_Absolute, VRScalarUnits_NormalizedTwoSided);
|
||||
in->CreateBooleanComponent(c, xrMode_ ? "/input/joystick/click" : "/input/trackpad/click", &padClick_);
|
||||
in->CreateBooleanComponent(c, xrMode_ ? "/input/joystick/touch" : "/input/trackpad/touch", &padTouch_);
|
||||
if (xrMode_) {
|
||||
const char *axisBase = stick ? stickPath : "/input/trackpad";
|
||||
in->CreateScalarComponent(c, path(axisBase, "/x").c_str(), &padX_, VRScalarType_Absolute, VRScalarUnits_NormalizedTwoSided);
|
||||
in->CreateScalarComponent(c, path(axisBase, "/y").c_str(), &padY_, VRScalarType_Absolute, VRScalarUnits_NormalizedTwoSided);
|
||||
in->CreateBooleanComponent(c, path(axisBase, "/click").c_str(), &padClick_);
|
||||
in->CreateBooleanComponent(c, path(axisBase, "/touch").c_str(), &padTouch_);
|
||||
if (stick) {
|
||||
const bool letters = touch_ && !right_;
|
||||
in->CreateScalarComponent(c, "/input/grip/value", &gripValue_, VRScalarType_Absolute, VRScalarUnits_NormalizedOneSided);
|
||||
if (index_) in->CreateScalarComponent(c, "/input/grip/force", &gripForce_, VRScalarType_Absolute, VRScalarUnits_NormalizedOneSided);
|
||||
in->CreateBooleanComponent(c, "/input/trigger/touch", &triggerTouch_);
|
||||
in->CreateBooleanComponent(c, right_ ? "/input/a/click" : "/input/x/click", &primaryClick_);
|
||||
in->CreateBooleanComponent(c, right_ ? "/input/b/click" : "/input/y/click", &secondaryClick_);
|
||||
in->CreateBooleanComponent(c, right_ ? "/input/a/touch" : "/input/x/touch", &primaryTouch_);
|
||||
in->CreateBooleanComponent(c, right_ ? "/input/b/touch" : "/input/y/touch", &secondaryTouch_);
|
||||
in->CreateBooleanComponent(c, "/input/thumbrest/touch", &thumbrestTouch_);
|
||||
in->CreateBooleanComponent(c, letters ? "/input/x/click" : "/input/a/click", &primaryClick_);
|
||||
in->CreateBooleanComponent(c, letters ? "/input/y/click" : "/input/b/click", &secondaryClick_);
|
||||
in->CreateBooleanComponent(c, letters ? "/input/x/touch" : "/input/a/touch", &primaryTouch_);
|
||||
in->CreateBooleanComponent(c, letters ? "/input/y/touch" : "/input/b/touch", &secondaryTouch_);
|
||||
if (touch_) in->CreateBooleanComponent(c, "/input/thumbrest/touch", &thumbrestTouch_);
|
||||
}
|
||||
in->CreateHapticComponent(c, "/output/haptic", &haptic_);
|
||||
Log("%s hand activated (%s)", right_ ? "right" : "left", xrMode_ ? "Quest Touch" : "game pad");
|
||||
Log("%s hand activated (%s)", right_ ? "right" : "left", xrMode_ ? "Quest Touch" : model);
|
||||
return VRInitError_None;
|
||||
}
|
||||
void Deactivate() override { ClearInputs(); id_ = k_unTrackedDeviceIndexInvalid; }
|
||||
@@ -1085,11 +1098,14 @@ public:
|
||||
if (id_ == k_unTrackedDeviceIndexInvalid) return;
|
||||
auto in = VRDriverInput();
|
||||
EVRInputError error = VRInputError_None;
|
||||
for (VRInputComponentHandle_t h : {system_, menu_, grip_, triggerClick_, padClick_, padTouch_}) {
|
||||
for (VRInputComponentHandle_t h : {system_, menu_, grip_, triggerClick_, padClick_, padTouch_, triggerTouch_,
|
||||
primaryClick_, secondaryClick_, primaryTouch_, secondaryTouch_}) {
|
||||
if (!h) continue;
|
||||
const auto result = in->UpdateBooleanComponent(h, false, 0);
|
||||
if (result != VRInputError_None) error = result;
|
||||
}
|
||||
for (VRInputComponentHandle_t h : {trigger_, padX_, padY_}) {
|
||||
for (VRInputComponentHandle_t h : {trigger_, padX_, padY_, gripValue_, gripForce_}) {
|
||||
if (!h) continue;
|
||||
const auto result = in->UpdateScalarComponent(h, 0.0f, 0);
|
||||
if (result != VRInputError_None) error = result;
|
||||
}
|
||||
@@ -1183,16 +1199,14 @@ public:
|
||||
p.result = valid ? TrackingResult_Running_OK : TrackingResult_Running_OutOfRange;
|
||||
auto in = VRDriverInput();
|
||||
const uint32_t b = pad ? pad->buttons : 0;
|
||||
in->UpdateBooleanComponent(system_, right_ && (b & PAD_GUIDE), 0);
|
||||
in->UpdateBooleanComponent(menu_, (b & (right_ ? PAD_START : PAD_SELECT)) != 0, 0);
|
||||
const auto gripError = in->UpdateBooleanComponent(grip_, opticalInputs_.grip, 0);
|
||||
if (gripValue_) in->UpdateScalarComponent(gripValue_, opticalInputs_.grip ? 1.0f : 0.0f, 0);
|
||||
const auto clickError = in->UpdateBooleanComponent(triggerClick_, opticalInputs_.click, 0);
|
||||
const auto triggerError = in->UpdateScalarComponent(trigger_, opticalInputs_.trigger, 0);
|
||||
if (triggerTouch_) in->UpdateBooleanComponent(triggerTouch_, opticalInputs_.trigger > 0.05f, 0);
|
||||
const float x = pad ? pad->axes[right_ ? 2 : 0]/32767.0f : 0;
|
||||
const float y = pad ? -pad->axes[right_ ? 3 : 1]/32767.0f : 0;
|
||||
in->UpdateScalarComponent(padX_, x, 0); in->UpdateScalarComponent(padY_, y, 0);
|
||||
in->UpdateBooleanComponent(padTouch_, x*x+y*y > 0.01f || (b & (right_ ? PAD_A : PAD_X)), 0);
|
||||
in->UpdateBooleanComponent(padClick_, (b & (right_ ? (PAD_A|PAD_R3) : PAD_X)) != 0, 0);
|
||||
UpdatePadButtons(b, x, y, true);
|
||||
LogOpticalInputs(hand, inputValid, valid, now, connection, origin, inputEpochs, gripError, clickError, triggerError);
|
||||
pose_ = p;
|
||||
VRServerDriverHost()->TrackedDevicePoseUpdated(id_, p, sizeof(p));
|
||||
@@ -1251,19 +1265,42 @@ public:
|
||||
auto in = VRDriverInput();
|
||||
const uint32_t b = pad->buttons;
|
||||
const float trig = pad->axes[right_ ? 4 : 5] / 255.0f;
|
||||
const bool touch = !sticksMoveHands && stickX * stickX + stickY * stickY > 0.01f;
|
||||
in->UpdateBooleanComponent(system_, right_ && (b & PAD_GUIDE), 0);
|
||||
in->UpdateBooleanComponent(menu_, (b & (right_ ? PAD_START : PAD_SELECT)) != 0, 0);
|
||||
in->UpdateBooleanComponent(grip_, (b & (right_ ? PAD_RB : PAD_LB)) != 0, 0);
|
||||
const bool grip = (b & (right_ ? PAD_RB : PAD_LB)) != 0;
|
||||
in->UpdateScalarComponent(trigger_, trig, 0);
|
||||
in->UpdateBooleanComponent(triggerClick_, trig > 0.6f, 0);
|
||||
in->UpdateScalarComponent(padX_, touch ? stickX : 0.0f, 0);
|
||||
in->UpdateScalarComponent(padY_, touch ? stickY : 0.0f, 0);
|
||||
in->UpdateBooleanComponent(padTouch_, touch || (b & (right_ ? PAD_A : PAD_X)), 0);
|
||||
in->UpdateBooleanComponent(padClick_, (b & (right_ ? (PAD_A | PAD_R3) : PAD_X)) != 0, 0);
|
||||
if (triggerTouch_) in->UpdateBooleanComponent(triggerTouch_, trig > 0.05f, 0);
|
||||
in->UpdateBooleanComponent(grip_, grip, 0);
|
||||
if (gripValue_) in->UpdateScalarComponent(gripValue_, grip ? 1.0f : 0.0f, 0);
|
||||
if (gripForce_) in->UpdateScalarComponent(gripForce_, grip ? 1.0f : 0.0f, 0);
|
||||
UpdatePadButtons(b, stickX, stickY, !sticksMoveHands);
|
||||
}
|
||||
|
||||
private:
|
||||
// Face buttons, menus and the stick, for both the game pad and optical hands.
|
||||
void UpdatePadButtons(uint32_t b, float stickX, float stickY, bool stickToGame) {
|
||||
auto in = VRDriverInput();
|
||||
const bool touch = stickToGame && stickX * stickX + stickY * stickY > 0.01f;
|
||||
in->UpdateBooleanComponent(system_, right_ && (b & PAD_GUIDE), 0);
|
||||
in->UpdateScalarComponent(padX_, touch ? stickX : 0.0f, 0);
|
||||
in->UpdateScalarComponent(padY_, touch ? stickY : 0.0f, 0);
|
||||
if (!touch_ && !index_) {
|
||||
in->UpdateBooleanComponent(menu_, (b & (right_ ? PAD_START : PAD_SELECT)) != 0, 0);
|
||||
in->UpdateBooleanComponent(padTouch_, touch || (b & (right_ ? PAD_A : PAD_X)), 0);
|
||||
in->UpdateBooleanComponent(padClick_, (b & (right_ ? (PAD_A | PAD_R3) : PAD_X)) != 0, 0);
|
||||
return;
|
||||
}
|
||||
// Touch and Index: face buttons are their own inputs and the stick is a thumbstick.
|
||||
const bool primary = b & (right_ ? PAD_A : PAD_X), secondary = b & (right_ ? PAD_B : PAD_Y);
|
||||
const bool both = (b & PAD_L3) && (b & PAD_R3);
|
||||
if (menu_) in->UpdateBooleanComponent(menu_, !right_ && (b & (PAD_START | PAD_SELECT)), 0);
|
||||
in->UpdateBooleanComponent(primaryClick_, primary, 0);
|
||||
in->UpdateBooleanComponent(secondaryClick_, secondary, 0);
|
||||
in->UpdateBooleanComponent(primaryTouch_, primary, 0);
|
||||
in->UpdateBooleanComponent(secondaryTouch_, secondary, 0);
|
||||
in->UpdateBooleanComponent(padTouch_, touch, 0);
|
||||
in->UpdateBooleanComponent(padClick_, !both && (b & (right_ ? PAD_R3 : PAD_L3)), 0);
|
||||
}
|
||||
|
||||
void LogOpticalInputs(const dd_spatial_hand &hand, bool inputValid, bool poseValid, int64_t now,
|
||||
uint64_t connection, uint64_t origin, uint16_t inputEpochs, EVRInputError gripError,
|
||||
EVRInputError clickError, EVRInputError triggerError) {
|
||||
@@ -1297,14 +1334,15 @@ private:
|
||||
static constexpr int16_t kGrabTrigger = 153;
|
||||
static constexpr float kStickDeadzone = 0.12f, kHandRangeX = 0.40f, kHandRangeUp = 0.50f, kHandRangeDown = 0.30f, kHandSmoothing = 0.05f, kHandPivot = 0.45f;
|
||||
bool right_;
|
||||
bool xrMode_ = false;
|
||||
bool xrMode_ = false, touch_ = false, index_ = false;
|
||||
PadProfile profile_ = PadProfile::Index;
|
||||
uint32_t id_ = k_unTrackedDeviceIndexInvalid;
|
||||
DriverPose_t pose_ = {};
|
||||
float pull_ = 0.0f, handX_ = 0.0f, handY_ = 0.0f;
|
||||
std::chrono::steady_clock::time_point lastUpdate_ = std::chrono::steady_clock::now();
|
||||
VRInputComponentHandle_t system_ = 0, menu_ = 0, grip_ = 0, triggerClick_ = 0, trigger_ = 0, padX_ = 0, padY_ = 0,
|
||||
padClick_ = 0, padTouch_ = 0, haptic_ = 0;
|
||||
VRInputComponentHandle_t gripValue_ = 0, triggerTouch_ = 0, primaryClick_ = 0, secondaryClick_ = 0,
|
||||
VRInputComponentHandle_t gripValue_ = 0, gripForce_ = 0, triggerTouch_ = 0, primaryClick_ = 0, secondaryClick_ = 0,
|
||||
primaryTouch_ = 0, secondaryTouch_ = 0, thumbrestTouch_ = 0;
|
||||
};
|
||||
|
||||
@@ -1552,9 +1590,9 @@ private:
|
||||
if (fresh) PublishChaperone(xr);
|
||||
DriverPose_t head = GetPose();
|
||||
VRServerDriverHost()->TrackedDevicePoseUpdated(id_, head, sizeof(head));
|
||||
for (int hand = 0; hand < 2; hand++) if (hands_[hand]) {
|
||||
for (int hand = 0; hand < 2; hand++) if (CardboardController *pad = ActiveHand(hand)) {
|
||||
DroidDeckXrHand state = fresh ? xr.hands[hand] : DroidDeckXrHand{};
|
||||
hands_[hand]->UpdateXr(state, fresh ? xr.predicted_ns : 0);
|
||||
pad->UpdateXr(state, fresh ? xr.predicted_ns : 0);
|
||||
}
|
||||
VRDriverInput()->UpdateBooleanComponent(proximity_, fresh, 0);
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(2));
|
||||
@@ -1594,9 +1632,10 @@ private:
|
||||
VRServerDriverHost()->TrackedDevicePoseUpdated(id_, head, sizeof(DriverPose_t));
|
||||
const bool lumaJoyCons = (spatial.flags & DD_SPATIAL_ACTIVE) && (spatial.flags & DD_SPATIAL_JOYCONS);
|
||||
const bool optical = !lumaJoyCons && (spatial.flags & DD_SPATIAL_ACTIVE) && (spatial.flags & DD_SPATIAL_HANDS);
|
||||
if (!optical && havePad && (pad.buttons & PAD_L3) && !(lastPad_.buttons & PAD_L3)) {
|
||||
sticksMoveHands_ = !sticksMoveHands_;
|
||||
Log("sticks now move %s", sticksMoveHands_ ? "the hands" : "in the game");
|
||||
const uint32_t chord = PAD_L3 | PAD_R3;
|
||||
if (!optical && havePad && (pad.buttons & chord) == chord && (lastPad_.buttons & chord) != chord) {
|
||||
sticksMoveHands_.store(!sticksMoveHands_.load());
|
||||
Log("sticks now move %s", sticksMoveHands_.load() ? "the hands" : "in the game");
|
||||
}
|
||||
const float dt = std::min(std::chrono::duration<float>(now - lastReach_).count(), 0.1f);
|
||||
lastReach_ = now;
|
||||
@@ -1638,7 +1677,7 @@ private:
|
||||
if (joyCon || bare) wantHand_[side] = true;
|
||||
const bool covered = handControllers_[side] && handControllers_[side]->Update(joyCon, bare, head.qRotation, nowNs,
|
||||
lumaJoyCons ? &spatial : nullptr);
|
||||
CardboardController *hand = hands_[side];
|
||||
CardboardController *hand = ActiveHand(side);
|
||||
if (!hand) continue;
|
||||
if (otherControllers_ || covered || bare || lumaJoyCons) {
|
||||
if (!padHandOff_[side]) hand->Disconnect();
|
||||
@@ -1650,7 +1689,7 @@ private:
|
||||
havePad ? &pad : nullptr, SpatialNow(), spatial.connection, spatial.origin,
|
||||
uint16_t(spatial.input_epochs >> (side*16)),
|
||||
spatial.flags & DD_SPATIAL_STEADY_AIM ? &spatial.head : nullptr);
|
||||
else hand->Update(head, havePad ? &pad : nullptr, sticksMoveHands_, reach_);
|
||||
else hand->Update(head, havePad ? &pad : nullptr, sticksMoveHands_.load(), reach_);
|
||||
}
|
||||
if (havePad) lastPad_ = pad;
|
||||
lastSent = now;
|
||||
@@ -1713,6 +1752,18 @@ private:
|
||||
PropertyContainerHandle_t container_ = k_ulInvalidPropertyContainer;
|
||||
public:
|
||||
void SetHands(CardboardController *left, CardboardController *right) { hands_[0] = left; hands_[1] = right; }
|
||||
void SetSticksMoveHands(bool on) { sticksMoveHands_ = on; }
|
||||
|
||||
// Called only from the pose thread: a replaced pair is disconnected there, so it never races an update.
|
||||
CardboardController *ActiveHand(int side) {
|
||||
CardboardController *wanted = hands_[side].load();
|
||||
if (wanted != active_[side]) {
|
||||
if (active_[side]) active_[side]->Disconnect();
|
||||
active_[side] = wanted;
|
||||
padHandOff_[side] = false;
|
||||
}
|
||||
return wanted;
|
||||
}
|
||||
void SetHandControllers(HandController *left, HandController *right) { handControllers_[0] = left; handControllers_[1] = right; }
|
||||
bool WantsHand(int side) const { return wantHand_[side].load(); }
|
||||
|
||||
@@ -1729,12 +1780,13 @@ private:
|
||||
PadState lastPad_;
|
||||
VRInputComponentHandle_t proximity_ = 0;
|
||||
bool worn_ = true;
|
||||
bool sticksMoveHands_ = true;
|
||||
std::atomic<bool> sticksMoveHands_{false};
|
||||
float reach_ = 0.0f;
|
||||
std::chrono::steady_clock::time_point lastReach_ = std::chrono::steady_clock::now();
|
||||
std::chrono::steady_clock::time_point lastScan_{};
|
||||
bool otherControllers_ = false;
|
||||
CardboardController *hands_[2] = {nullptr, nullptr};
|
||||
std::atomic<CardboardController *> hands_[2] = {nullptr, nullptr};
|
||||
CardboardController *active_[2] = {nullptr, nullptr};
|
||||
bool padHandOff_[2] = {false, false};
|
||||
ShmFile<droiddeck_joycon> joyConFile_{kJoyConPath, DROIDDECK_JOYCON_MAGIC, DROIDDECK_JOYCON_VERSION, "Joy-Con"};
|
||||
uint32_t lastJoyConSeq_ = 0;
|
||||
@@ -1767,11 +1819,8 @@ public:
|
||||
Log("DroidDeck Cardboard driver loaded");
|
||||
if (!VRServerDriverHost()->TrackedDeviceAdded("droiddeck-cardboard-hmd", TrackedDeviceClass_HMD, &hmd_))
|
||||
Log("TrackedDeviceAdded failed");
|
||||
if (VRSettings()->GetBool(kSettingsSection, "gamepadControllers")) {
|
||||
VRServerDriverHost()->TrackedDeviceAdded("droiddeck-pad-left", TrackedDeviceClass_Controller, &left_);
|
||||
VRServerDriverHost()->TrackedDeviceAdded("droiddeck-pad-right", TrackedDeviceClass_Controller, &right_);
|
||||
hmd_.SetHands(&left_, &right_);
|
||||
}
|
||||
padsEnabled_ = VRSettings()->GetBool(kSettingsSection, "gamepadControllers");
|
||||
ApplyPadConfig(true);
|
||||
hmd_.SetHandControllers(&handLeft_, &handRight_);
|
||||
return VRInitError_None;
|
||||
}
|
||||
@@ -1782,6 +1831,11 @@ public:
|
||||
}
|
||||
const char *const *GetInterfaceVersions() override { return k_InterfaceVersions; }
|
||||
void RunFrame() override {
|
||||
const auto now = std::chrono::steady_clock::now();
|
||||
if (now - lastConfigCheck_ > std::chrono::seconds(1)) {
|
||||
lastConfigCheck_ = now;
|
||||
ApplyPadConfig(false);
|
||||
}
|
||||
for (int side = 0; side < 2; side++) {
|
||||
if (handAdded_[side] || !hmd_.WantsHand(side)) continue;
|
||||
handAdded_[side] = true;
|
||||
@@ -1803,9 +1857,11 @@ public:
|
||||
if (!h.componentHandle) continue;
|
||||
if (h.componentHandle == handLeft_.Haptic()) SendRumble(DROIDDECK_JOYCON_RUMBLE_SLOT, h);
|
||||
else if (h.componentHandle == handRight_.Haptic()) SendRumble(DROIDDECK_JOYCON_RUMBLE_SLOT + 1, h);
|
||||
else if (h.componentHandle == left_.Haptic() || h.componentHandle == right_.Haptic()) {
|
||||
if (left_.XrMode()) SendHaptic(h.componentHandle == right_.Haptic() ? 1 : 0, h);
|
||||
else for (int p = 0; p < kPadProfiles; p++) {
|
||||
if (!padAdded_[p] || (h.componentHandle != pads_[p][0].Haptic() && h.componentHandle != pads_[p][1].Haptic())) continue;
|
||||
if (pads_[p][0].XrMode()) SendHaptic(h.componentHandle == pads_[p][1].Haptic() ? 1 : 0, h);
|
||||
else SendRumble(0, h);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1852,8 +1908,46 @@ private:
|
||||
target.frequency = std::max(pulse.fFrequency, 0.f);
|
||||
__atomic_store_n(&haptics_->seq, (sequence | 1u) + 1u, __ATOMIC_RELEASE);
|
||||
}
|
||||
// SteamVR fixes a device's input profile when it activates, so each type gets its own pair,
|
||||
// added the first time it is chosen; devices cannot be removed, only disconnected.
|
||||
void ApplyPadConfig(bool initial) {
|
||||
// The file is a few bytes, so compare what it says; two quick writes can share an mtime.
|
||||
const PadControllerConfig pads = read_pad_controller_config("/run/droiddeck/" DROIDDECK_VR_CONTROLLERS_FILE);
|
||||
if (!initial && pads.profile == configProfile_ && pads.sticksMoveHands == configSticks_) return;
|
||||
configProfile_ = pads.profile;
|
||||
if (initial || pads.sticksMoveHands != configSticks_) hmd_.SetSticksMoveHands(pads.sticksMoveHands);
|
||||
configSticks_ = pads.sticksMoveHands;
|
||||
const PadProfile profile = padsEnabled_ ? pads.profile : PadProfile::Off;
|
||||
if (!initial && profile == profile_) return;
|
||||
profile_ = profile;
|
||||
Log("game pad hands: %s, sticks start in %s", pad_profile_name(profile), pads.sticksMoveHands ? "the hands" : "the game");
|
||||
if (profile == PadProfile::Off) { hmd_.SetHands(nullptr, nullptr); return; }
|
||||
const int p = int(profile) - 1;
|
||||
if (!padAdded_[p]) {
|
||||
static const char *const kNames[kPadProfiles][2] = {
|
||||
{"droiddeck-pad-left", "droiddeck-pad-right"},
|
||||
{"droiddeck-pad-touch-left", "droiddeck-pad-touch-right"},
|
||||
{"droiddeck-pad-vive-left", "droiddeck-pad-vive-right"},
|
||||
};
|
||||
for (int side = 0; side < 2; side++) {
|
||||
pads_[p][side].SetProfile(profile);
|
||||
VRServerDriverHost()->TrackedDeviceAdded(kNames[p][side], TrackedDeviceClass_Controller, &pads_[p][side]);
|
||||
}
|
||||
padAdded_[p] = true;
|
||||
}
|
||||
hmd_.SetHands(&pads_[p][0], &pads_[p][1]);
|
||||
}
|
||||
|
||||
static constexpr int kPadProfiles = 3;
|
||||
CardboardHmd hmd_;
|
||||
CardboardController left_{false}, right_{true};
|
||||
CardboardController pads_[kPadProfiles][2] = {{CardboardController(false), CardboardController(true)},
|
||||
{CardboardController(false), CardboardController(true)},
|
||||
{CardboardController(false), CardboardController(true)}};
|
||||
bool padAdded_[kPadProfiles] = {false, false, false};
|
||||
bool padsEnabled_ = true, configSticks_ = false;
|
||||
PadProfile profile_ = PadProfile::Off;
|
||||
PadProfile configProfile_ = PadProfile::Index;
|
||||
std::chrono::steady_clock::time_point lastConfigCheck_{};
|
||||
HandController handLeft_{false}, handRight_{true};
|
||||
bool handAdded_[2] = {false, false};
|
||||
};
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
#pragma once
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
|
||||
#define DROIDDECK_VR_CONTROLLERS_FILE "droiddeck-vr-controllers"
|
||||
|
||||
enum class PadProfile { Off, Index, Touch, Vive };
|
||||
|
||||
struct PadControllerConfig {
|
||||
PadProfile profile = PadProfile::Index;
|
||||
bool sticksMoveHands = false;
|
||||
};
|
||||
|
||||
// One key=value per line, written by the app before SteamVR starts.
|
||||
inline PadControllerConfig pad_controller_config(const char *text) {
|
||||
PadControllerConfig config;
|
||||
if (!text) return config;
|
||||
for (const char *line = text; *line;) {
|
||||
const char *end = std::strchr(line, '\n');
|
||||
const size_t length = end ? size_t(end - line) : std::strlen(line);
|
||||
const auto is = [&](const char *expected) {
|
||||
return std::strlen(expected) == length && !std::strncmp(line, expected, length);
|
||||
};
|
||||
if (is("emulate=off")) config.profile = PadProfile::Off;
|
||||
else if (is("emulate=index")) config.profile = PadProfile::Index;
|
||||
else if (is("emulate=touch")) config.profile = PadProfile::Touch;
|
||||
else if (is("emulate=vive")) config.profile = PadProfile::Vive;
|
||||
else if (is("sticks=hands")) config.sticksMoveHands = true;
|
||||
else if (is("sticks=game")) config.sticksMoveHands = false;
|
||||
if (!end) break;
|
||||
line = end + 1;
|
||||
}
|
||||
return config;
|
||||
}
|
||||
|
||||
inline PadControllerConfig read_pad_controller_config(const char *path) {
|
||||
char text[256] = {};
|
||||
if (FILE *f = std::fopen(path, "r")) {
|
||||
const size_t n = std::fread(text, 1, sizeof(text) - 1, f);
|
||||
text[n] = 0;
|
||||
std::fclose(f);
|
||||
}
|
||||
return pad_controller_config(text);
|
||||
}
|
||||
|
||||
inline const char *pad_profile_name(PadProfile profile) {
|
||||
switch (profile) {
|
||||
case PadProfile::Off: return "off";
|
||||
case PadProfile::Index: return "Index";
|
||||
case PadProfile::Touch: return "Quest Touch";
|
||||
case PadProfile::Vive: return "Vive";
|
||||
}
|
||||
return "?";
|
||||
}
|
||||
@@ -80,6 +80,7 @@ int main() {
|
||||
Context context;
|
||||
VRDriverContext() = &context;
|
||||
CardboardController controller(false);
|
||||
controller.SetProfile(PadProfile::Vive);
|
||||
assert(controller.Activate(1) == VRInitError_None);
|
||||
const auto gripHandle=context.input.handles.at("/input/grip/click");
|
||||
const auto clickHandle=context.input.handles.at("/input/trigger/click");
|
||||
@@ -260,4 +261,46 @@ int main() {
|
||||
joyCon.Update(nullptr, false, {1,0,0,0}, now, &spatial);
|
||||
assert(!joyCon.GetPose().deviceIsConnected && context.input.values.at(joyTrigger) == 0);
|
||||
puts("PASS: optical controller recovery and Luma Joy-Con camera, fallback, head loss and origin changes");
|
||||
|
||||
for (const PadProfile profile : {PadProfile::Index, PadProfile::Touch}) {
|
||||
auto &padContext = context;
|
||||
padContext.input.handles.clear();
|
||||
CardboardController pad(true);
|
||||
pad.SetProfile(profile);
|
||||
assert(pad.Activate(2) == VRInitError_None);
|
||||
const auto &h = padContext.input.handles;
|
||||
const std::string stick = profile == PadProfile::Touch ? "/input/joystick" : "/input/thumbstick";
|
||||
assert(!h.count("/input/trackpad/x") && h.count("/input/b/click") && h.count("/input/grip/value"));
|
||||
assert(h.count("/input/application_menu/click") == (profile == PadProfile::Touch));
|
||||
DriverPose_t head{};
|
||||
head.qRotation.w = 1;
|
||||
PadState state{};
|
||||
state.buttons = PAD_A | PAD_RB;
|
||||
state.axes[2] = 32767;
|
||||
state.axes[4] = 255;
|
||||
pad.Update(head, &state, false, 0);
|
||||
const auto value = [&](const std::string &name) { return padContext.input.values.at(h.at(name)); };
|
||||
assert(value("/input/a/click") == 1 && value("/input/b/click") == 0);
|
||||
assert(value(stick + "/x") == 1 && value(stick + "/touch") == 1 && value(stick + "/click") == 0);
|
||||
assert(value("/input/grip/value") == 1 && value("/input/trigger/value") == 1);
|
||||
pad.Update(head, &state, true, 0);
|
||||
assert(value(stick + "/x") == 0);
|
||||
state = {};
|
||||
state.buttons = PAD_R3;
|
||||
pad.Update(head, &state, false, 0);
|
||||
assert(value(stick + "/click") == 1);
|
||||
state.buttons = PAD_L3 | PAD_R3;
|
||||
pad.Update(head, &state, false, 0);
|
||||
assert(value(stick + "/click") == 0);
|
||||
dd_spatial_hand optical{};
|
||||
state = {};
|
||||
state.buttons = PAD_A;
|
||||
pad.UpdateOptical(optical, false, &state, 1000000000, 1, 1);
|
||||
assert(value("/input/a/click") == 1 && value(stick + "/click") == 0 && value(stick + "/touch") == 0);
|
||||
state.buttons = PAD_B | PAD_R3;
|
||||
pad.UpdateOptical(optical, false, &state, 1000000001, 1, 1);
|
||||
assert(value("/input/b/click") == 1 && value("/input/a/click") == 0 && value(stick + "/click") == 1);
|
||||
assert(!padContext.input.values.count(0));
|
||||
}
|
||||
puts("PASS: game pad hands as Index and Quest Touch thumbstick controllers");
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
#include "../src/pad_controller_config.h"
|
||||
#include <cassert>
|
||||
#include <cstdio>
|
||||
|
||||
int main() {
|
||||
auto config = pad_controller_config(nullptr);
|
||||
assert(config.profile == PadProfile::Index && !config.sticksMoveHands);
|
||||
config = pad_controller_config("emulate=touch\nsticks=hands\n");
|
||||
assert(config.profile == PadProfile::Touch && config.sticksMoveHands);
|
||||
config = pad_controller_config("emulate=off");
|
||||
assert(config.profile == PadProfile::Off);
|
||||
config = pad_controller_config("emulate=vive\nsticks=game");
|
||||
assert(config.profile == PadProfile::Vive && !config.sticksMoveHands);
|
||||
config = pad_controller_config("emulate=offline\nsticks=handsome\n");
|
||||
assert(config.profile == PadProfile::Index && !config.sticksMoveHands);
|
||||
assert(read_pad_controller_config("/nonexistent/droiddeck").profile == PadProfile::Index);
|
||||
std::puts("pad controller config ok");
|
||||
return 0;
|
||||
}
|
||||
Reference in new issue
Block a user