Merge remote-tracking branch 'droiddeck/main' into feat/malibridge

# Conflicts:
#	README.md
#	app/src/main/java/com/droiddeck/launcher/gpu/TurnipDriver.java
#	app/src/main/java/com/droiddeck/launcher/runtime/BwrapSpawner.kt
#	app/src/main/res/values-ar/strings.xml
#	app/src/main/res/values-b+es+419/strings.xml
#	app/src/main/res/values-bg/strings.xml
#	app/src/main/res/values-cs/strings.xml
#	app/src/main/res/values-da/strings.xml
#	app/src/main/res/values-de/strings.xml
#	app/src/main/res/values-el/strings.xml
#	app/src/main/res/values-es/strings.xml
#	app/src/main/res/values-fi/strings.xml
#	app/src/main/res/values-fr/strings.xml
#	app/src/main/res/values-hi/strings.xml
#	app/src/main/res/values-hu/strings.xml
#	app/src/main/res/values-in/strings.xml
#	app/src/main/res/values-it/strings.xml
#	app/src/main/res/values-ja/strings.xml
#	app/src/main/res/values-ko/strings.xml
#	app/src/main/res/values-ms/strings.xml
#	app/src/main/res/values-nb/strings.xml
#	app/src/main/res/values-nl/strings.xml
#	app/src/main/res/values-pl/strings.xml
#	app/src/main/res/values-pt-rPT/strings.xml
#	app/src/main/res/values-pt/strings.xml
#	app/src/main/res/values-ro/strings.xml
#	app/src/main/res/values-ru/strings.xml
#	app/src/main/res/values-sv/strings.xml
#	app/src/main/res/values-th/strings.xml
#	app/src/main/res/values-tr/strings.xml
#	app/src/main/res/values-uk/strings.xml
#	app/src/main/res/values-vi/strings.xml
#	app/src/main/res/values-zh-rCN/strings.xml
#	app/src/main/res/values-zh-rHK/strings.xml
#	app/src/main/res/values-zh-rTW/strings.xml
#	app/src/main/res/values/strings.xml
#	tools/linuxfs/overlay/usr/local/bin/droiddeck-game-env
This commit is contained in:
maxjivi05 committed 2026-10-30 11:58:55 -04:00
commit 0a5955d6fa
731 files changed
+54131 -2491

No files matched your search

+1 -1
View File
@@ -45,7 +45,7 @@ lib=$out/x86_64/libwebkitinput.so
gcc -m64 -shared -fPIC -O2 -Wall -Wextra -nostdlib -fno-stack-protector -fno-builtin -fvisibility=hidden \
-o "$lib" tools/linuxfs/fex/webkitinput.c
strip --strip-unneeded "$lib"
if objdump -p "$lib" | grep -q NEEDED || [ "$(nm -D --undefined-only "$lib" | awk '{print $1 $2}' | LC_ALL=C sort | tr '\n' ' ')" != "wdlsym wg_object_get_data wg_object_set wg_object_set_data wg_type_check_instance_is_a wgtk_container_forall wgtk_container_get_type wgtk_key_snooper_install wgtk_widget_get_toplevel wwebkit_user_script_new wwebkit_user_script_unref wwebkit_web_view_get_type wwebkit_web_view_get_uri wwebkit_web_view_run_javascript " ]; then
if objdump -p "$lib" | grep -q NEEDED || [ "$(nm -D --undefined-only "$lib" | awk '{print $1 $2}' | LC_ALL=C sort | tr '\n' ' ')" != "wdlsym wg_getenv wg_object_get_data wg_object_set wg_object_set_data wg_type_check_instance_is_a wgtk_container_forall wgtk_container_get_type wgtk_key_snooper_install wgtk_widget_get_toplevel wwebkit_user_script_new wwebkit_user_script_unref wwebkit_web_view_get_type wwebkit_web_view_get_uri wwebkit_web_view_run_javascript " ]; then
echo "$lib must need nothing but weak GLib, GTK and WebKit calls" >&2
exit 1
fi
+33 -1
View File
@@ -11,6 +11,7 @@ export MOZ_DISABLE_CONTENT_SANDBOX=1 MOZ_DISABLE_GMP_SANDBOX=1 MOZ_DISABLE_RDD_S
export MOZ_DISABLE_SOCKET_PROCESS_SANDBOX=1 MOZ_DISABLE_UTILITY_SANDBOX=1
export MOZ_SHM_NO_SEALS=1
export KWIN_COMPOSE=Q QT_QUICK_BACKEND=software LIBGL_ALWAYS_SOFTWARE=1 GALLIUM_DRIVER=llvmpipe
export KWIN_USE_OVERLAYS=0
[ -e /etc/mpv/mpv.conf ] || { mkdir -p /etc/mpv && echo gpu-sw=yes >/etc/mpv/mpv.conf; } 2>/dev/null
for conf in client client-rt; do
mkdir -p "/etc/pipewire/$conf.conf.d" && printf 'context.properties = {\n module.rt = false\n}\n' >"/etc/pipewire/$conf.conf.d/droiddeck-rt.conf"
@@ -35,7 +36,7 @@ cat > /usr/share/applications/droiddeck-steam-x64.desktop <<'ENTRY'
Type=Application
Name=Steam x86-64 (FEX, experimental)
Comment=Valve's x86-64 Linux client under FEX, in its own home with its own login
Exec=qterminal -e /usr/local/bin/droiddeck-steam-x64
Exec=konsole -e /usr/local/bin/droiddeck-steam-x64
Icon=steam
Categories=System;
ENTRY
@@ -43,6 +44,20 @@ python3 /usr/local/bin/droiddeck-pad-defaults 2>&1 | sed 's/^/[pads] /'
( while sleep 30; do python3 /usr/local/bin/droiddeck-pad-defaults 2>&1 | sed 's/^/[pads] /'; done ) &
python3 /usr/local/bin/droiddeck-desktop-gpu 2>&1 | sed 's/^/[gpu] /'
/usr/local/bin/droiddeck-desktop-window-rules 2>&1 | sed 's/^/[rules] /'
( python3 /usr/local/bin/droiddeck-library-perms 2>&1 | sed 's/^/[perms] /' ) &
mkdir -p /usr/local/share/applications
cat > /usr/local/share/applications/droiddeck-ime.desktop <<'ENTRY'
[Desktop Entry]
Type=Application
Name=Android keyboard
Exec=/usr/local/bin/droiddeck-ime
NoDisplay=true
X-KDE-Wayland-VirtualKeyboard=true
ENTRY
input_method=$(kreadconfig6 --file kwinrc --group Wayland --key InputMethod 2>/dev/null)
case $input_method in
''|*/droiddeck-ime.desktop) kwriteconfig6 --file kwinrc --group Wayland --key InputMethod /usr/local/share/applications/droiddeck-ime.desktop ;;
esac
python3 /usr/local/bin/droiddeck-open --install 2>&1 | sed 's/^/[open] /'
export APPIMAGE_EXTRACT_AND_RUN=1
[ -e /etc/xdg/kiorc ] || printf '[Executable scripts]\nbehaviourOnLaunch=execute\n' >/etc/xdg/kiorc 2>/dev/null
@@ -55,6 +70,19 @@ if [ ! -e "$HOME/.config/droiddeck-desktop-icons" ]; then
touch "$HOME/.config/droiddeck-desktop-icons"
fi
[ -f "$desktop_dir/Return.desktop" ] && cp -f /usr/share/applications/droiddeck-return-gaming.desktop "$desktop_dir/Return.desktop" 2>/dev/null
if command -v flatpak >/dev/null 2>&1 && [ ! -d /var/lib/pacman ]; then
FLATPAK_BWRAP=/usr/local/bin/droiddeck-bwrap flatpak remote-add --user --if-not-exists flathub https://dl.flathub.org/repo/flathub.flatpakrepo >/dev/null 2>&1 &
fi
skel_done=$HOME/.local/share/droiddeck/skel-copied
if [ -d /etc/skel ] && [ ! -e "$skel_done" ]; then
cp -rn /etc/skel/. "$HOME/" 2>/dev/null
mkdir -p "${skel_done%/*}" && : > "$skel_done"
fi
if [ -x /usr/lib/snapd/snap-confine ] && [ ! -d /var/lib/pacman ]; then
/usr/local/bin/droiddeck-snapd >/dev/null 2>&1 &
export XDG_DATA_DIRS=/var/lib/snapd/desktop:${XDG_DATA_DIRS:-/usr/local/share:/usr/share}
export PATH=$PATH:/snap/bin
fi
update-mime-database /usr/share/mime >/dev/null 2>&1 &
[ -f /usr/share/icons/hicolor/icon-theme.cache ] || gtk-update-icon-cache -q -t /usr/share/icons/hicolor 2>/dev/null &
[ -f /usr/share/glib-2.0/schemas/gschemas.compiled ] || glib-compile-schemas /usr/share/glib-2.0/schemas 2>/dev/null
@@ -82,6 +110,10 @@ if [ "$(cat /usr/share/droiddeck/kwin-compositor 2>/dev/null)" = opengl ]; then
if [ -z "${KWIN_RENDER_NODES:-}" ] && [ -c /dev/dri/renderD0 ]; then
export KWIN_RENDER_NODES=/dev/dri/renderD0
fi
mkdir -p /run/droiddeck/kwin
printf '#!/bin/sh\nGALLIUM_THREAD=0 exec /usr/bin/kwin_wayland "$@"\n' > /run/droiddeck/kwin/kwin_wayland
chmod 755 /run/droiddeck/kwin/kwin_wayland
export PATH=/run/droiddeck/kwin:$PATH
fi
echo "== droiddeck-desktop: Plasma on $WAYLAND_DISPLAY"
dbus-run-session -- startplasma-wayland
+54 -7
View File
@@ -1,6 +1,7 @@
#!/usr/bin/python3
import os
import re
import shutil
HOME = os.environ.get("HOME", "/root")
SYSTEM_DIR = "/usr/share/applications"
@@ -9,6 +10,8 @@ FLATPAK_DIR = os.path.join(HOME, ".local/share/flatpak/exports/share/application
USER_DIR = os.path.join(HOME, ".local/share/applications")
MARK = "X-DroidDeck-GPU=1"
SKIP = re.compile(r"^(steam|droiddeck-game-|droiddeck-steam|steamdeck-)", re.I)
CHROMIUM_ENV = "env -u WAYLAND_DISPLAY XDG_SESSION_TYPE=x11 ELECTRON_DISABLE_SANDBOX=1 "
CHROMIUM_FLAGS = " --no-sandbox --ozone-platform=x11"
def enabled():
@@ -25,6 +28,33 @@ def main_group(text):
return lines[:start + 1], lines[start + 1:end], lines[end:]
def split_program(exec_line):
if exec_line.startswith('"'):
end = exec_line.find('"', 1)
if end < 0:
return None, None
return exec_line[:end + 1], exec_line[end + 1:]
program, _, rest = exec_line.partition(" ")
return program, (" " + rest) if rest else ""
def chromium(exec_line):
program, _ = split_program(exec_line)
if not program:
return False
program = program.strip('"')
path = program if os.path.isabs(program) else shutil.which(program)
if not path:
return False
here = os.path.dirname(os.path.realpath(path))
return any(os.path.exists(os.path.join(d, "chrome-sandbox")) for d in (here, os.path.dirname(here)))
def chromium_exec(exec_line):
program, rest = split_program(exec_line)
return CHROMIUM_ENV + program + CHROMIUM_FLAGS + rest
def gpu_exec(exec_line):
"""The Exec that runs a program on the GPU; a Flatpak app goes through its launcher, which
keeps it on gamescope's X server instead of the desktop's Wayland socket."""
@@ -33,7 +63,7 @@ def gpu_exec(exec_line):
return "droiddeck-gpu " + exec_line
def wrap(text):
def wrap(text, gpu_on=True):
head, group, rest = main_group(text)
if group is None:
return None
@@ -42,14 +72,30 @@ def wrap(text):
if "=" in l and not l.lstrip().startswith("#"):
k, v = l.split("=", 1)
keys.setdefault(k.strip(), v)
cats = set(filter(None, keys.get("Categories", "").split(";")))
if not cats & {"Game", "Emulator"}:
return None
if keys.get("Type", "Application") != "Application" or keys.get("NoDisplay", "").lower() == "true":
return None
exec_line = keys.get("Exec", "").strip()
if not exec_line or exec_line.startswith("droiddeck-gpu "):
return None
cats = set(filter(None, keys.get("Categories", "").split(";")))
gpu = gpu_on and bool(cats & {"Game", "Emulator"})
browser = chromium(exec_line)
if not gpu and not browser:
return None
if browser:
exec_line = chromium_exec(exec_line)
if not gpu:
def fix(lines):
return ["Exec=" + chromium_exec(l[5:].strip()) if l.startswith("Exec=") and chromium(l[5:].strip()) else l
for l in lines]
out_group = fix(group)
while out_group and not out_group[-1].strip():
out_group.pop()
out_group.append(MARK)
out_rest = fix(rest)
if out_rest and out_rest[0].strip():
out_rest.insert(0, "")
return "\n".join(head + out_group + out_rest) + "\n"
out_group = []
actions = keys.get("Actions", "")
for l in group:
@@ -68,7 +114,8 @@ def wrap(text):
wrapped_rest = []
for l in rest:
if l.startswith("Exec=") and not l[5:].startswith("droiddeck-gpu "):
l = "Exec=" + gpu_exec(l[5:])
action = l[5:].strip()
l = "Exec=" + gpu_exec(chromium_exec(action) if chromium(action) else action)
wrapped_rest.append(l)
if wrapped_rest and wrapped_rest[0].strip():
wrapped_rest.insert(0, "")
@@ -87,7 +134,7 @@ def main():
on = enabled()
os.makedirs(USER_DIR, exist_ok=True)
written = set()
sources = [d for d in (SYSTEM_DIR, LOCAL_DIR, FLATPAK_DIR) if os.path.isdir(d)] if on else []
sources = [d for d in (SYSTEM_DIR, LOCAL_DIR, FLATPAK_DIR) if os.path.isdir(d)]
for source in sources:
for name in sorted(os.listdir(source)):
if not name.endswith(".desktop") or SKIP.match(name):
@@ -97,7 +144,7 @@ def main():
continue
try:
with open(os.path.join(source, name), encoding="utf-8", errors="replace") as f:
text = wrap(f.read())
text = wrap(f.read(), on)
except OSError:
continue
if text is None:
+43
View File
@@ -22,6 +22,7 @@ extern void webkit_web_view_run_javascript(void *view, const char *script, void
extern WebKitUserScript *webkit_user_script_new(const char *source, int frames, int time,
const char *const *allow, const char *const *block) __attribute__((weak));
extern void webkit_user_script_unref(WebKitUserScript *script) __attribute__((weak));
extern const char *g_getenv(const char *name) __attribute__((weak));
static const char NAV_SCRIPT[] =
"(()=>{let open=-1e9,arrowAt=-1e9,ringed=null,ringOutline='',ringOffset='',settleTimer=0,settling=false,redirecting=false;"
@@ -196,3 +197,45 @@ __attribute__((visibility("default"))) void webkit_user_content_manager_add_scri
}
next(manager, script);
}
static int starts(const char *text, const char *prefix)
{
while (*prefix)
if (*text++ != *prefix++)
return 0;
return 1;
}
static int fab_uri(const char *uri)
{
if (!uri)
return 0;
if (starts(uri, "https://"))
uri += 8;
else if (starts(uri, "http://"))
uri += 7;
else
return 0;
if (starts(uri, "www."))
uri += 4;
if (!starts(uri, "fab.com"))
return 0;
uri += 7;
return !*uri || *uri == '/' || *uri == '?' || *uri == '#' || *uri == ':';
}
static int hidden_launcher(void)
{
const char *hidden = g_getenv ? g_getenv("DROIDDECK_EPIC_HIDDEN") : 0;
return hidden && hidden[0] == '1' && !hidden[1];
}
__attribute__((visibility("default"))) void webkit_web_view_load_uri(void *view, const char *uri)
{
static void (*next)(void *, const char *);
if (!next && dlsym)
next = (void (*)(void *, const char *))dlsym((void *)-1l, "webkit_web_view_load_uri");
if (!next)
return;
next(view, hidden_launcher() && fab_uri(uri) ? "about:blank" : uri);
}
@@ -605,9 +605,56 @@ KEYBOARD_CHECK_SECONDS = 30
KEYBOARD_JS = r"""
(() => {
const self = window.__droiddeckKeyboard || (window.__droiddeckKeyboard = { watched: new WeakSet(), last: null });
self.wrapped = self.wrapped || new WeakSet();
self.route = self.route === true;
self.wrap = vkm => {
if (!vkm || self.wrapped.has(vkm) || typeof vkm.ShowVirtualKeyboard !== "function") return;
self.wrapped.add(vkm);
const show = vkm.ShowVirtualKeyboard;
vkm.ShowVirtualKeyboard = function (ref, props, modal) {
if (self.route && !modal && typeof this.SetActiveVirtualKeyboardTarget === "function" &&
!this.BUseVRKeyboard?.() && !this.m_Instance?.IsDesktopOverlayWindow?.()) {
this.SetActiveVirtualKeyboardTarget(ref, props);
self.follow(this);
if (typeof window.__BINDING__ === "function") window.__BINDING__("request");
return;
}
return show.call(this, ref, props, modal);
};
};
self.editing = vkm => {
let el = null;
try { el = vkm?.m_ownerWindow?.document?.activeElement || null; } catch (e) {}
if (!el) return null;
return el.tagName === "TEXTAREA" || el.isContentEditable === true ||
(el.tagName === "INPUT" && !/^(button|checkbox|radio|range|submit|reset|file|image|color)$/i.test(el.type || ""));
};
self.follow = vkm => {
self.active = vkm;
self.missed = 0;
self.seen = false;
self.follower = self.follower || setInterval(() => {
if (!self.active) return;
const ref = self.active.m_currentVirtualKeyboardRef;
const editing = self.editing(self.active);
const valid = !!ref && (editing !== null ? editing :
(typeof ref.BIsElementValidForInput !== "function" || ref.BIsElementValidForInput()));
if (valid) self.seen = true;
if (self.route && ref && (valid || !self.seen)) {
self.missed = 0;
return;
}
if (++self.missed < 2) return;
self.active = null;
clearInterval(self.follower);
self.follower = null;
if (typeof window.__BINDING__ === "function") window.__BINDING__("dismiss");
}, 150);
};
self.check = () => {
let showing = false;
for (const win of Array.from(globalThis.SteamUIStore?.WindowStore?.SteamUIWindows || [])) {
self.wrap(win?.VirtualKeyboardManager);
const value = win?.VirtualKeyboardManager?.IsShowingVirtualKeyboard;
if (!value) continue;
if (!self.watched.has(value) && typeof value.Subscribe === "function") {
@@ -626,6 +673,29 @@ KEYBOARD_JS = r"""
return self.check();
})()
""".replace("__BINDING__", KEYBOARD_BINDING)
KEYBOARD_ROUTE_SECONDS = 0.5
KEYBOARD_ROUTE_JS = r"""
(route => {
const self = window.__droiddeckKeyboard;
if (!self) return false;
self.route = route;
if (!route) return true;
for (const win of Array.from(globalThis.SteamUIStore?.WindowStore?.SteamUIWindows || [])) {
const vkm = win?.VirtualKeyboardManager;
if (vkm?.m_bIsInlineVirtualKeyboardOpen?.m_currentValue === true && vkm?.m_bIsVirtualKeyboardModal?.m_currentValue !== true &&
typeof vkm.SetVirtualKeyboardHidden === "function") {
const ref = vkm.m_currentVirtualKeyboardRef, props = vkm.m_ActiveElementProps;
vkm.SetVirtualKeyboardHidden();
if (ref && typeof vkm.SetActiveVirtualKeyboardTarget === "function") {
vkm.SetActiveVirtualKeyboardTarget(ref, props);
if (typeof self.follow === "function") self.follow(vkm);
}
if (typeof window.__BINDING__ === "function") window.__BINDING__("request");
}
}
return true;
})(__ROUTE__)
""".replace("__BINDING__", KEYBOARD_BINDING)
class KeyboardWatcher(threading.Thread):
@@ -633,8 +703,14 @@ class KeyboardWatcher(threading.Thread):
super().__init__(daemon=True, name="keyboard")
self.agent_dir = agent_dir
self.path = agent_dir / "keyboard.json"
self.request_path = agent_dir / "keyboard-request.json"
self.dismiss_path = agent_dir / "keyboard-dismiss.json"
self.dismissals = 0
self.route_path = agent_dir / "keyboard-route"
self.showing = None
self.seq = 0
self.requests = 0
self.route = None
self.next_id = 0
self.attached = False
@@ -645,6 +721,30 @@ class KeyboardWatcher(threading.Thread):
self.seq += 1
write_json(self.path, {"steamKeyboard": showing, "seq": self.seq})
def request(self):
self.requests += 1
write_json(self.request_path, {"seq": self.requests})
def dismiss(self):
self.dismissals += 1
write_json(self.dismiss_path, {"seq": self.dismissals})
def wanted_route(self):
try:
return self.route_path.read_text().strip() == "bottom"
except OSError:
return False
def apply_route(self, ws, force=False):
route = self.wanted_route()
if route == self.route and not force:
return
result = self.call(ws, "Runtime.evaluate", {
"expression": KEYBOARD_ROUTE_JS.replace("__ROUTE__", "true" if route else "false"), "returnByValue": True})
if result.get("exceptionDetails"):
raise AgentError("JS_EXCEPTION", json.dumps(result["exceptionDetails"])[:500])
self.route = route
def run(self):
failures, last = 0, None
while True:
@@ -671,10 +771,18 @@ class KeyboardWatcher(threading.Thread):
try:
self.call(ws, "Runtime.addBinding", {"name": KEYBOARD_BINDING})
self.report(self.install(ws))
self.apply_route(ws, force=True)
self.attached = True
installed = time.monotonic()
while True:
if not ws.buffer and not select.select([ws.s], [], [], KEYBOARD_CHECK_SECONDS)[0]:
self.report(self.install(ws))
wait = min(KEYBOARD_ROUTE_SECONDS, KEYBOARD_CHECK_SECONDS)
if not ws.buffer and not select.select([ws.s], [], [], wait)[0]:
if time.monotonic() - installed >= KEYBOARD_CHECK_SECONDS:
self.report(self.install(ws))
self.apply_route(ws, force=True)
installed = time.monotonic()
else:
self.apply_route(ws)
continue
self.event(json.loads(ws.recv()))
finally:
@@ -702,7 +810,12 @@ class KeyboardWatcher(threading.Thread):
def event(self, message):
params = message.get("params") or {}
if message.get("method") == "Runtime.bindingCalled" and params.get("name") == KEYBOARD_BINDING:
self.report(params.get("payload") == "true")
if params.get("payload") == "request":
self.request()
elif params.get("payload") == "dismiss":
self.dismiss()
else:
self.report(params.get("payload") == "true")
def steam_idle_inhibit(agent_dir, inhibit):
@@ -1,5 +1,6 @@
#!/usr/bin/python3
import base64
import fcntl
import json
import os
import signal
@@ -87,6 +88,7 @@ class Spec:
self.info_fds = []
self.json_fds = []
self.keep_fds = []
self.lock_files = []
self.command = []
self.argv0 = None
@@ -159,6 +161,8 @@ def parse(argv):
read_fd(int(args[0]))
elif a == "--sync-fd":
s.keep_fds.append(int(args[0]))
elif a == "--lock-file":
s.lock_files.append(args[0])
elif a == "--info-fd":
s.info_fds.append(int(args[0]))
elif a == "--json-status-fd":
@@ -203,6 +207,31 @@ def remaps_nothing(s):
return True
def host_path(s, path):
for op in reversed(s.ops):
if op["t"] != "bind":
continue
dest = op["dest"].rstrip("/")
if path == dest or path.startswith(dest + "/"):
return op["src"].rstrip("/") + path[len(dest):]
return path
def hold_locks(s):
for path in s.lock_files:
try:
fd = os.open(host_path(s, path), os.O_RDONLY)
except OSError as e:
sys.stderr.write("bwrap: Can't open lock file %s: %s\n" % (path, e.strerror))
sys.exit(1)
try:
fcntl.lockf(fd, fcntl.LOCK_SH | fcntl.LOCK_NB)
except OSError as e:
sys.stderr.write("bwrap: Can't lock file %s: %s\n" % (path, e.strerror))
sys.exit(1)
os.set_inheritable(fd, True)
def report_pid(s, pid):
for fd in s.info_fds:
try:
@@ -282,7 +311,7 @@ def run_by_app(s):
if payload is None:
break
if kind == b"P":
report_pid(s, int(payload))
report_pid(s, os.getpid())
elif kind == b"O":
out.write(payload)
out.flush()
@@ -301,6 +330,7 @@ def run_by_app(s):
def main():
s = parse(expand(sys.argv[1:]))
hold_locks(s)
if remaps_nothing(s):
run_here(s)
else:
+31
View File
@@ -0,0 +1,31 @@
#!/bin/bash
free_name() {
local dir=$1 name=$2 base ext n=2
[ -e "$dir/$name" ] || { echo "$name"; return; }
base=${name%.*} ext=
[ "$base" != "$name" ] && [ -n "$base" ] && ext=.${name##*.} || base=$name
while [ -e "$dir/$base ($n)$ext" ]; do n=$((n + 1)); done
echo "$base ($n)$ext"
}
share() {
local android=$HOME/Storage/$1 link=$HOME/$2 f
[ -d "$android" ] && [ -w "$android" ] || return 0
[ "$(readlink "$link" 2>/dev/null)" = "$android" ] && return 0
if [ -L "$link" ]; then
rm -f "$link"
elif [ -d "$link" ]; then
shopt -s dotglob nullglob
for f in "$link"/*; do
mv -n -- "$f" "$android/$(free_name "$android" "${f##*/}")" || return 1
done
shopt -u dotglob nullglob
rmdir "$link" 2>/dev/null || mv "$link" "$link.old.$$" || return 1
elif [ -e "$link" ]; then
mv "$link" "$link.old.$$" || return 1
fi
ln -s "$android" "$link"
}
status=0
share Download Downloads || status=1
share Documents Documents || status=1
exit $status
+22
View File
@@ -0,0 +1,22 @@
#!/bin/bash
set -u
export FLATPAK_BWRAP=/usr/local/bin/droiddeck-bwrap
cores="libretro-core-info libretro-beetle-pce-fast libretro-beetle-psx libretro-beetle-vb libretro-beetle-wswan
libretro-bsnes-mercury-performance libretro-desmume libretro-gambatte libretro-genesisplusgx libretro-mgba
libretro-nestopia libretro-sameboy libretro-snes9x"
case "${1:-}" in
install)
echo "== STEP RetroArch"
droiddeck-root /usr/bin/apt-get update -q || { echo "== FAIL apt-get update"; exit 1; }
droiddeck-root /usr/bin/apt-get install -y -q retroarch retroarch-assets $cores || { echo "== FAIL apt-get install"; exit 1; }
echo "== STEP PPSSPP"
flatpak remote-add --user --if-not-exists flathub https://dl.flathub.org/repo/flathub.flatpakrepo || { echo "== FAIL flathub"; exit 1; }
flatpak install --user -y --noninteractive flathub org.ppsspp.PPSSPP || { echo "== FAIL org.ppsspp.PPSSPP"; exit 1; }
printf '#!/bin/sh\nexec /usr/local/bin/droiddeck-flatpak-run org.ppsspp.PPSSPP "$@"\n' > /usr/local/bin/PPSSPPSDL.new &&
chmod 755 /usr/local/bin/PPSSPPSDL.new && mv -f /usr/local/bin/PPSSPPSDL.new /usr/local/bin/PPSSPPSDL || { echo "== FAIL PPSSPPSDL"; exit 1; }
;;
*)
echo "usage: droiddeck-emulators install" >&2
exit 2
;;
esac
@@ -100,6 +100,10 @@ CLIENT_ENV = {
"JSC_useDFGJIT": "0",
"JSC_useFTLJIT": "0",
}
HIDDEN_ENV = {
"DROIDDECK_EPIC_HIDDEN": "1",
"EGL_DISABLE_STORE_PREWARM": "1",
}
KEPT_ENV = ("HOME", "USER", "LOGNAME", "LANG", "LANGUAGE", "LC_ALL", "LC_MESSAGES", "TZ", "XDG_RUNTIME_DIR", "BL_LAUNCH_DIR")
LAUNCH_VERBS = ("waitforexitandrun", "run", "runinprefix")
EPIC_ARGS = ("-auth_", "-epic")
@@ -725,7 +729,7 @@ def fex_environment(fex, files, env):
return result
def client_environment(base, fex, files, display, bus, broker, a11y=None):
def client_environment(base, fex, files, display, bus, broker, a11y=None, hidden=False):
env = {name: base[name] for name in KEPT_ENV if base.get(name)}
env.setdefault("HOME", HOME)
env.setdefault("LANG", "C.UTF-8")
@@ -734,6 +738,8 @@ def client_environment(base, fex, files, display, bus, broker, a11y=None):
env["DBUS_SESSION_BUS_ADDRESS"] = bus
env[BROKER_ENV] = broker
env.update(CLIENT_ENV)
if hidden:
env.update(HIDDEN_ENV)
if a11y:
for name in A11Y_OFF:
env.pop(name, None)
@@ -1248,7 +1254,7 @@ class Session:
path = broker_path()
self.broker = Broker(path, self.mode, base)
write_json(instance_file(), {"pid": os.getpid(), "mode": self.mode, "bus": bus, "broker": path})
env = client_environment(base, fex, files, display, bus, path, self.a11y)
env = client_environment(base, fex, files, display, bus, path, self.a11y, hidden=self.mode == "hidden")
self.command = [fex["bin"], os.path.join(app_dir, "AppRun")]
self.env = env
say("starting the Epic Games Launcher %s (%s, display %s)" % (current.get("app"), self.mode, display))
@@ -5,6 +5,7 @@ step() { echo "== STEP $*"; }
fail() { echo "== FAIL $*"; exit 1; }
[ "$(id -u)" = 0 ] || fail "needs root: install Flatpak from the launcher's Store, which runs this as root"
if command -v pacman >/dev/null 2>&1; then
PACKAGES="flatpak ostree appstream libxmlb libmalcontent libfyaml accountsservice composefs xdg-dbus-proxy"
while read -r pkg probe; do
[ -n "$pkg" ] || continue
@@ -77,7 +78,13 @@ done
mv -f "$WORK/installed.new" "$WORK/installed"
find "$WORK/pkg" -type f -mtime +1 -delete 2>/dev/null
missing=$(for f in /usr/bin/flatpak /usr/lib/libflatpak.so.0 /usr/lib/libostree-1.so.1 /usr/bin/xdg-dbus-proxy; do
else
command -v flatpak >/dev/null 2>&1 || fail "Flatpak is missing from the runtime"
WORK=$(mktemp -d)
trap 'rm -rf "$WORK"' EXIT
fi
missing=$(for f in /usr/bin/flatpak /usr/lib/libflatpak.so.0 /usr/lib/libostree-1.so.1 /usr/lib/aarch64-linux-gnu/libflatpak.so.0 /usr/lib/aarch64-linux-gnu/libostree-1.so.1 /usr/bin/xdg-dbus-proxy; do
[ -e "$f" ] || continue
ldd "$f" 2>&1 | grep -E 'not found|version .* not found'
done | sort -u)
[ -z "$missing" ] || { echo "$missing"; fail "Flatpak is missing libraries"; }
@@ -97,7 +104,7 @@ Description=Central repository of Flatpak applications
Icon=https://dl.flathub.org/repo/logo.svg
GPGKey=mQINBFlD2sABEADsiUZUOYBg1UdDaWkEdJYkTSZD68214m8Q1fbrP5AptaUfCl8KYKFMNoAJRBXn9FbE6q6VBzghHXj/rSnA8WPnkbaEWR7xltOqzB1yHpCQ1l8xSfH5N02DMUBSRtD/rOYsBKbaJcOgW0K21sX+BecMY/AI2yADvCJEjhVKrjR9yfRX+NQEhDcbXUFRGt9ZT+TI5yT4xcwbvvTu7aFUR/dH7+wjrQ7lzoGlZGFFrQXSs2WI0WaYHWDeCwymtohXryF8lcWQkhH8UhfNJVBJFgCY8Q6UHkZG0FxMu8xnIDBMjBmSZKwKQn0nwzwM2afskZEnmNPYDI8nuNsSZBZSAw+ThhkdCZHZZRwzmjzyRuLLVFpOj3XryXwZcSefNMPDkZAuWWzPYjxS80cm2hG1WfqrG0Gl8+iX69cbQchb7gbEb0RtqNskTo9DDmO0bNKNnMbzmIJ3/rTbSahKSwtewklqSP/01o0WKZiy+n/RAkUKOFBprjJtWOZkc8SPXV/rnoS2dWsJWQZhuPPtv3tefdDiEyp7ePrfgfKxuHpZES0IZRiFI4J/nAUP5bix+srcIxOVqAam68CbAlPvWTivRUMRVbKjJiGXIOJ78wAMjqPg3QIC0GQ0EPAWwAOzzpdgbnG7TCQetaVV8rSYCuirlPYN+bJIwBtkOC9SWLoPMVZTwQARAQABtC5GbGF0aHViIFJlcG8gU2lnbmluZyBLZXkgPGZsYXRodWJAZmxhdGh1Yi5vcmc+iQJUBBMBCAA+FiEEblwF2XnHba+TwIE1QYTdTZB6fK4FAllD2sACGwMFCRLMAwAFCwkIBwIGFQgJCgsCBBYCAwECHgECF4AACgkQQYTdTZB6fK5RJQ/+Ptd4sWxaiAW91FFk7+wmYOkEe1NY2UDNJjEEz34PNP/1RoxveHDt43kYJQ23OWaPJuZAbu+fWtjRYcMBzOsMCaFcRSHFiDIC9aTp4ux/mo+IEeyarYt/oyKb5t5lta6xaAqg7rwt65jW5/aQjnS4h7eFZ+dAKta7Y/fljNrOznUp81/SMcx4QA5G2Pw0hs4Xrxg59oONOTFGBgA6FF8WQghrpR7SnEe0FSEOVsAjwQ13Cfkfa7b70omXSWp7GWfUzgBKyoWxKTqzMN3RQHjjhPJcsQnrqH5enUu4Pcb2LcMFpzimHnUgb9ft72DP5wxfzHGAWOUiUXHbAekfq5iFks8cha/RST6wkxG3Rf44Zn09aOxh1btMcGL+5xb1G0BuCQnA0fP/kDYIPwh9z22EqwRQOspIcvGeLVkFeIfubxpcMdOfQqQnZtHMCabV5Q/Rk9K1ZGc8M2hlg8gHbXMFch2xJ0Wu72eXbA/UY5MskEeBgawTQnQOK/vNm7t0AJMpWK26Qg6178UmRghmeZDj9uNRc3EI1nSbgvmGlpDmCxaAGqaGL1zW4KPW5yN25/qeqXcgCvUjZLI9PNq3Kvizp1lUrbx7heRiSoazCucvHQ1VHUzcPVLUKKTkoTP8okThnRRRsBcZ1+jI4yMWIDLOCT7IW3FePr+3xyuy5eEo9a25Ag0EWUPa7AEQALT/CmSyZ8LWlRYQZKYw417p7Z2hxqd6TjwkwM3IQ1irumkWcTZBZIbBgrSOg6CcXD2oWydCQHWi9qaxhuhEl2bJL5LskmBcMxVdQeD0LLHd8QUnbnnIby8ocvWN1alPfvJFjCUTrmD22U1ycOzRw2lIe4kiQONbOZtdWrVImQQSndjFlisitbmlWHvHm2lOOYy8+GJB7YffVV193hmnBSJffCy4bvkuLxsI+n1DhOzc7MPV3z6HGk4HiEcF0yyt9tCYhpsxHFdBoq2h771HfAcS0s98EVAqYMFnf9em+4cnYpdI6mhIfS1FQiKl6DBAYA8tT3ggla00DurPo0JwX/zN+PaO5h/6O9aCZwV7G6rbkgMuqMergXaf8oP38gr0z+MqWnkfM63Bodq68GP4l4hd02BoFBbDf38TMuGQB14+twJMdfbAxo2MbgluvQgfwHfZ2ca6gyEY+9s/YD1gugLjV+S6CB51WkFNe1z4tAPgJZNxUcKCbeaHNbthl8Hks/pY9RCEseX/EdfzF18epbSjJMPh4DPQXbUoFwmyuYcoBOPmvZHNl9hK7B/1RP8w1ZrXk8qdupC0SNbafX7270B7lMMVImzZetGsM9ypXJ6llhp3FwW09iseNyGJGPsr/dvTMGDXqOPfU/9SAS1LSTY4K9PbRtdrBE318YX8mIk5ABEBAAGJBHIEGAEIACYWIQRuXAXZecdtr5PAgTVBhN1NkHp8rgUCWUPa7AIbAgUJEswDAAJACRBBhN1NkHp8rsF0IAQZAQgAHRYhBFSmzd2JGfsgQgDYrFYnAunj7X7oBQJZQ9rsAAoJEFYnAunj7X7oR6AP/0KYmiAFeqx14Z43/6s2gt3VhxlSd8bmcVV7oJFbMhdHBIeWBp2BvsUf00I0Zl14ZkwCKfLwbbORC2eIxvzJ+QWjGfPhDmS4XUSmhlXxWnYEveSek5Tde+fmu6lqKM8CHg5BNx4GWIX/vdLi1wWJZyhrUwwICAxkuhKxuP2Z1An48930eslTD2GGcjByc27+9cIZjHKa07I/aLffo04V+oMT9/tgzoquzgpVV4jwekADo2MJjhkkPveSNI420bgT+Q7Fi1l0X1aFUniBvQMsaBa27PngWm6xE2ZYvh7nWCdd5g0c0eLIHxWwzV1lZ4Ryx4ITO/VL25ItECcjhTRdYa64sA62MYSaB0x3eR+SihpgP3wSNPFu3MJo6FKTFdi4CBAEmpWHFW7FcRmd+cQXeFrHLN3iNVWryy0HK/CUEJmiZEmpNiXecl4vPIIuyF0zgSCztQtKoMr+injpmQGC/rF/ELBVZTUSLNB350S0Ztvw0FKWDAJSxFmoxt3xycqvvt47rxTrhi78nkk6jATKGyvP55sO+K7Q7Wh0DXA69hvPrYW2eu8jGCdVGxi6HX7L1qcfEd0378S71dZ3g9o6KKl1OsDWWQ6MJ6FGBZedl/ibRfs8p5+sbCX3lQSjEFy3rx6n0rUrXx8U2qb+RCLzJlmC5MNBOTDJwHPcX6gKsUcXZrEQALmRHoo3SrewO41RCr+5nUlqiqV3AohBMhnQbGzyHf2+drutIaoh7Rj80XRh2bkkuPLwlNPf+bTXwNVGse4bej7B3oV6Ae1N7lTNVF4Qh+1OowtGjmfJPWo0z1s6HFJVxoIof9z58Msvgao0zrKGqaMWaNQ6LUeC9g9Aj/9Uqjbo8X54aLiYs8Z1WNc06jKP+gv8AWLtv6CR+l2kLez1YMDucjm7v6iuCMVAmZdmxhg5I/X2+OM3vBsqPDdQpr2TPDLX3rCrSBiS0gOQ6DwN5N5QeTkxmY/7QO8bgLo/Wzu1iilH4vMKW6LBKCaRx5UEJxKpL4wkgITsYKneIt3NTHo5EOuaYk+y2+Dvt6EQFiuMsdbfUjs3seIHsghX/cbPJa4YUqZAL8C4OtVHaijwGo0ymt9MWvS9yNKMyT0JhN2/BdeOVWrHk7wXXJn/ZjpXilicXKPx4udCF76meE+6N2u/T+RYZ7fP1QMEtNZNmYDOfA6sViuPDfQSHLNbauJBo/n1sRYAsL5mcG22UDchJrlKvmK3EOADCQg+myrm8006LltubNB4wWNzHDJ0Ls2JGzQZCd/xGyVmUiidCBUrD537WdknOYE4FD7P0cHaM9brKJ/M8LkEH0zUlo73bY4XagbnCqve6PvQb5G2Z55qhWphd6f4B6DGed86zJEa/RhS
REPO
if ! flatpak remote-list --user --columns=name 2>/dev/null | grep -qx flathub; then
if ! flatpak remote-list --columns=name 2>/dev/null | grep -qx flathub; then
out=$(flatpak remote-add --user --if-not-exists flathub "$WORK/flathub.flatpakrepo" 2>&1)
rc=$?
echo "$out"
@@ -107,6 +107,15 @@ def godot_sentry(game):
return {"WINEDLLOVERRIDES": ";".join(n + "=d" for n in sentry)}, [], "Godot: Sentry crash handler off"
@fix
def d3dgear_hook(game):
"""D3DGear's capture DLL left beside a game (The Crew 2) is loaded by it and hooks the DXGI swapchain;
under Wine the hook faults over a thousand times within seconds and the game never presents again:
black screen while the sound keeps playing."""
if "d3dgear64.dll" in game.files:
return {"WINEDLLOVERRIDES": "d3dgear64=d"}, [], "D3DGear capture hook off (it stops the game drawing)"
@fix
def deep_rock_gdk_raytracing(game):
if game.stem == "fsd-wingdk-shipping" and not any(game.has_arg(arg) for arg in ("-raytracing", "-noraytracing")):
@@ -122,6 +131,12 @@ def arkham_city_x87(game):
@fix
def teardown_vsync(game):
if game.stem == "teardown":
return {"vblank_mode": "2"}, [], "Teardown: OpenGL keeps the game's own vsync"
@fix
def protonfixes_off(game):
if game.stem in ("blackops3", "darksoulsremastered"):
@@ -142,6 +157,12 @@ def robocop_rogue_city_feature_level(game):
return {"VKD3D_FEATURE_LEVEL": "12_1"}, [], "RoboCop: Rogue City: D3D12 feature level 12_1"
@fix
def reskate_feature_level(game):
if "skate.exe" in game.files and "reskate.dll" in game.files:
return {"VKD3D_FEATURE_LEVEL": "12_1"}, [], "ReSkate (skate.): D3D12 feature level 12_1"
@fix
def cyberpunk_feature_level(game):
if game.stem == "cyberpunk2077" or (
@@ -254,7 +275,10 @@ def engine_fixes(exe, args):
for check in FIXES:
found = check(game)
if found:
env.update(found[0])
for name, value in found[0].items():
if name == "WINEDLLOVERRIDES" and env.get(name):
value = env[name] + ";" + value
env[name] = value
extra += found[1]
notes.append(found[2])
return env, extra, notes
@@ -339,6 +363,99 @@ def game_cores(env):
print("droiddeck-game-env: could not use game cores %r (%s)" % (text, error), file=sys.stderr)
def core_speeds(cores, root="/sys/devices/system/cpu"):
"""Each core's capacity, else its top clock; None when some core reports neither."""
for name in ("cpu_capacity", "cpufreq/cpuinfo_max_freq"):
speeds = {}
for core in cores:
try:
with open("%s/cpu%d/%s" % (root, core, name)) as f:
speeds[core] = int(f.read().strip())
except (OSError, ValueError):
break
else:
return speeds
return None
def fastest_first(cores):
"""The cores, fastest first; cores of equal or unknown speed keep their numeric order."""
cores = sorted(cores)
speeds = core_speeds(cores)
return sorted(cores, key=lambda core: -speeds[core]) if speeds else cores
def proton_cpu_limit(command, env):
"""This game's entry in Proton's own default_cpu_limit list: a core count, another value such as "P" as text, or None."""
app_id = env.get("SteamGameId", "")
if not command or not app_id.isdigit():
return None
try:
if os.path.getsize(command[0]) > 4 * 1024 * 1024:
return None
with open(command[0], encoding="utf-8", errors="replace") as f:
text = f.read()
except OSError:
return None
table = re.search(r"^default_cpu_limit = \{(.*?)^\}", text, re.M | re.S)
match = table and re.search(r'^\s*"%s"\s*:\s*"?(\w+)' % app_id, table.group(1), re.M)
if not match:
return None
value = match.group(1)
return int(value) if value.isdigit() else value
def cpu_topology(env, command=()):
"""Windows sees the game's cores fastest first, so a thread a game pins to CPU 0 runs on the fastest core."""
if "PROTON_CPU_TOPOLOGY" in env:
return
if "WINE_CPU_TOPOLOGY" in env:
if env["WINE_CPU_TOPOLOGY"]:
env["PROTON_CPU_TOPOLOGY"] = env["WINE_CPU_TOPOLOGY"]
return
picked = bool(env.get("DROIDDECK_GAME_CORES", "").strip() or env.get("BL_GAME_CPUS", "").strip())
fastest = env.get("DROIDDECK_FASTEST_CORES", "").strip() != "0" and game_id(env) is not None
if not (picked or fastest):
return
try:
cores = sorted(os.sched_getaffinity(0))
except OSError:
return
online = online_cores()
if not cores or cores[-1] >= len(online):
return
picked = picked and not set(cores) >= online
if fastest:
limit = None if picked else proton_cpu_limit(command, env)
if isinstance(limit, str):
return
cores = fastest_first(cores)[:limit or None]
elif set(cores) >= online:
return
if cores == sorted(online):
return
env["WINE_CPU_TOPOLOGY"] = env["PROTON_CPU_TOPOLOGY"] = "%d:%s" % (len(cores), ",".join(map(str, cores)))
print("droiddeck-game-env: Windows sees %d cores (%s)" % (len(cores), env["WINE_CPU_TOPOLOGY"]), file=sys.stderr)
def gl_vsync(env):
"""OpenGL stops waiting for each screen refresh; Steam's Frame Limit still holds the game through gamescope."""
# Wine asks for interval 1 on every GL window, and WineD3D's front-buffer drawing (DirectDraw,
# Direct3D 1-7) never lowers it, so those games ran at the refresh rate with no limit set.
if "vblank_mode" in env or game_id(env) is None:
return False
env["vblank_mode"] = "0"
return True
def game_images(env):
if game_id(env) is None:
return False
env.setdefault("GAMESCOPE_WSI_MIN_IMAGE_COUNT", "8")
env.setdefault("GAMESCOPE_WSI_ENSURE_MIN_IMAGE_COUNT", "1")
return True
def apply_config(env, config, app_id, fixes=None):
if config.get("version") != 1:
raise ValueError("unsupported environment configuration")
@@ -379,6 +496,59 @@ def bridge_feature_level(env):
return "Mali bridge: VKD3D_FEATURE_LEVEL %s capped at 12_0 (no ray tracing or mesh shaders)" % was
GAME_DEBUG_CHANNELS = (
"timestamp", "pid", "tid", "seh", "unwind", "threadname", "debugstr", "loaddll", "mscoree",
)
WINE_DEBUG_SELECTOR = re.compile(r"(?:(trace|warn|err|fixme))?([+-])([A-Za-z_][A-Za-z0-9_]*)")
def game_debug_channels(*values):
"""Normalize Wine selectors, retaining custom channels before required diagnostics."""
selectors = {}
for value in values:
if not isinstance(value, str) or "\0" in value or len(value) > 8192:
continue
for part in value.split(","):
part = part.strip()
match = WINE_DEBUG_SELECTOR.fullmatch(part)
if match is None:
continue
key = (match[1] or "", match[3])
# Move the last value to the end: global +/-all and per-class selectors
# have ordered semantics, so replacing a value in its old position is wrong.
selectors.pop(key, None)
selectors[key] = part
for channel in GAME_DEBUG_CHANNELS:
key = ("", channel)
selectors.pop(key, None)
selectors[key] = "+" + channel
formatted = ",".join(selectors.values())
if len(formatted) > 8192:
formatted = ",".join("+" + channel for channel in GAME_DEBUG_CHANNELS)
return formatted
def apply_game_debug_logs(env, config, debug_dir):
"""Apply app-owned diagnostics to a real game, without editing its launch command."""
if not isinstance(config, dict) or config.get("version") != 1 or config.get("gameDebugLogs") is not True:
return env
if (not isinstance(debug_dir, str) or "\0" in debug_dir or len(debug_dir) > 8192
or not os.path.isabs(debug_dir) or not os.path.isdir(debug_dir)):
print("droiddeck-game-env: game debug logs skipped; session log directory unavailable", file=sys.stderr)
return env
result = dict(env)
result.update({
"PROTON_LOG": "1",
"PROTON_LOG_DIR": debug_dir,
"PROTON_CRASH_REPORT_DIR": debug_dir,
"DXVK_LOG_PATH": debug_dir,
"DXVK_LOG_LEVEL": "debug",
"VKD3D_DEBUG": "info",
"WINEDEBUG": game_debug_channels(env.get("WINEDEBUG"), env.get("PROTON_LOG")),
})
return result
def sync_config(config, app_id):
games = config.get("games", {})
return {
@@ -580,6 +750,7 @@ def main():
return 2
env = game_gpu(os.environ.copy())
mic_enabled = env.get("BL_MIC_ENABLED")
debug_dir = env.get("BL_DEBUG_DIR", "")
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)
@@ -590,12 +761,17 @@ def main():
digest = None
app_id = game_id(env)
if app_id:
gl_default = gl_vsync(env)
waiting = len(command) > 1 and command[1] == "waitforexitandrun"
if waiting:
game_images(env)
fixes = {}
if waiting:
command = skip_red_launcher(command)
ubisoft_overlay_off(env)
fixes, extra, notes = engine_fixes(command[2], command[3:]) if len(command) > 2 else ({}, [], [])
if not gl_default:
fixes.pop("vblank_mode", None)
for note in notes:
print("droiddeck-game-env: " + note, file=sys.stderr)
command += extra
@@ -604,10 +780,13 @@ def main():
own = fixes.get("WINEDLLOVERRIDES")
fixes["WINEDLLOVERRIDES"] = components + ";" + own if own else components
path = Path.home() / ".config/droiddeck/game-environment.json"
config = {}
try:
with path.open(encoding="utf-8") as source:
config = json.load(source)
if waiting:
if "vblank_mode" in config.get("shared", {}):
fixes.pop("vblank_mode", None)
env = apply_config(env, config, app_id, fixes)
else:
env = apply_config(env, sync_config(config, app_id), app_id)
@@ -616,6 +795,13 @@ def main():
env = apply_config(env, {"version": 1}, app_id, fixes)
except (OSError, ValueError, TypeError, AttributeError):
print("droiddeck-game-env: invalid configuration; using inherited environment", file=sys.stderr)
if waiting:
before_debug = env
env = apply_game_debug_logs(env, config, debug_dir)
if env is not before_debug:
print("droiddeck-game-env: game debug logs enabled for this launch", file=sys.stderr)
if gl_default and env.get("vblank_mode") == "0":
print("droiddeck-game-env: OpenGL does not wait for the screen refresh (vblank_mode=0)", file=sys.stderr)
if app_id and len(command) > 1 and command[1] == "waitforexitandrun":
command = offline_without_anticheat(command, env)
if mic_enabled == "0":
@@ -626,6 +812,7 @@ def main():
print("droiddeck-game-env: " + note, file=sys.stderr)
env = force_ssbs(command, env)
game_cores(env)
cpu_topology(env, command)
try:
xbox = runpy.run_path(str(Path(__file__).with_name("droiddeck-xbox")))
except Exception as error:
@@ -0,0 +1,344 @@
#!/usr/bin/python3
"""GOG patch installers and the lease shared by maintenance and game launches."""
import fcntl
import errno
import json
import os
from pathlib import Path
import runpy
import subprocess
import sys
import tempfile
import time
BIN = Path(__file__).resolve().parent
IDLE = {"wineserver", "services.exe", "winedevice.exe", "explorer.exe", "rpcss.exe", "plugplay.exe",
"conhost.exe", "lsass.exe", "svchost.exe", "steam.exe", "wineboot.exe", "winemenubuilder.exe"}
def control(folder):
folder = Path(folder).resolve(strict=True)
root = folder / ".droiddeck-gog"
if root.is_symlink():
raise ValueError("GOG control directory is a symbolic link")
root.mkdir(exist_ok=True)
return root
def read(path):
if path.is_symlink():
raise ValueError("GOG metadata is a symbolic link")
return json.loads(path.read_text(encoding="utf-8"))
def write(path, value):
if path.is_symlink():
raise ValueError("GOG metadata is a symbolic link")
descriptor, name = tempfile.mkstemp(prefix=path.name + ".", suffix=".new", dir=path.parent)
temporary = Path(name)
try:
with os.fdopen(descriptor, "w") as stream:
json.dump(value, stream)
stream.flush()
os.fsync(stream.fileno())
os.replace(temporary, path)
directory = os.open(path.parent, os.O_RDONLY | os.O_DIRECTORY)
try:
try:
os.fsync(directory)
except OSError as error:
if error.errno not in (errno.EINVAL, errno.ENOTSUP):
raise
finally:
os.close(directory)
finally:
temporary.unlink(missing_ok=True)
def lock_file(root):
return os.fdopen(os.open(root / "lease", os.O_RDWR | os.O_CREAT | os.O_NOFOLLOW, 0o600), "r+")
def generation(pid):
try:
return Path("/proc/%s/stat" % pid).read_text().rsplit(")", 1)[1].split()[19]
except (OSError, IndexError):
return None
def lease(folder, owner):
root = control(folder)
with lock_file(root) as stream:
fcntl.lockf(stream, fcntl.LOCK_SH | fcntl.LOCK_NB)
sidecar = read(Path(folder) / ".droiddeck-store.json")
if sidecar.get("state", "installed") != "installed":
raise ValueError("Resume or recover the GOG update before playing")
journal = root / "operation.json"
if journal.exists() and read(journal).get("phase") != "download":
raise ValueError("GOG maintenance is incomplete")
start = generation(owner)
if start is None:
raise ValueError("Game launcher has exited")
print("ready", flush=True)
sys.stdout.close()
while generation(owner) == start:
time.sleep(0.25)
return 0
def desktop_environment(base, proc=Path("/proc")):
env = dict(base)
if env.get("DROIDDECK_GOG_DESKTOP") != "1":
return env
deadline = time.monotonic() + 45
while True:
for entry in proc.iterdir():
if not entry.name.isdigit():
continue
try:
command = (entry / "cmdline").read_bytes().split(b"\0")[0]
if command != b"/usr/bin/plasmashell":
continue
values = dict(os.fsdecode(item).split("=", 1) for item in (entry / "environ").read_bytes().split(b"\0") if b"=" in item)
if values.get("BL_DESKTOP") != "1" or values.get("XDG_RUNTIME_DIR") != env.get("XDG_RUNTIME_DIR"):
continue
if not values.get("DISPLAY") or values.get("WAYLAND_DISPLAY") == env.get("WAYLAND_DISPLAY"):
continue
for key in ("DISPLAY", "WAYLAND_DISPLAY", "XAUTHORITY", "DBUS_SESSION_BUS_ADDRESS", "BL_DESKTOP"):
if key in values:
env[key] = values[key]
return env
except (OSError, ValueError):
continue
if time.monotonic() >= deadline:
raise ValueError("The desktop display is not ready; resume the Linux session and verify recovery before retrying")
time.sleep(0.25)
def target_for(folder, appid, game):
run = runpy.run_path(str(BIN / "droiddeck-proton-run"))["main"].__globals__
root = os.environ.get("STEAM_COMPAT_CLIENT_INSTALL_PATH") or run["STEAM_ROOT"]
target = run["shortcut_target"](str(int(appid) & 0xffffffff), str(game), str(folder), root)
target.install = str(folder)
return run, root, target
def runner(folder, appid, game, graphical=False):
run, root, target = target_for(folder, appid, game)
available = run["tools"](root)
name, _ = run["choose_tool"](target.appid, run["mapping"](root), available)
if name is None:
raise ValueError("No Proton tool is installed for this game")
tool, command = available[name]
base = desktop_environment(os.environ) if graphical else dict(os.environ)
env = run["environment"](base, target, tool, root, window=base.get("BL_DESKTOP") == "1")
env["DROIDDECK_GOG_MAINTENANCE"] = "1"
# Installer copy routines use x87 integer loads/stores; reduced precision corrupts paths (FEX #5827).
env["FEX_X87REDUCEDPRECISION"] = "0"
env.pop("BL_STORE_EXIT", None)
return str(Path(tool) / command), env, target.compatdata
def active(prefix, proc=Path("/proc")):
result = []
prefix = os.path.realpath(os.path.join(prefix, "pfx"))
for entry in proc.iterdir():
if not entry.name.isdigit():
continue
try:
env = dict(part.split(b"=", 1) for part in (entry / "environ").read_bytes().split(b"\0") if b"=" in part)
if os.path.realpath(os.fsdecode(env.get(b"WINEPREFIX", b""))) != prefix:
continue
args = (entry / "cmdline").read_bytes().split(b"\0")
name = os.fsdecode(args[0]).replace("\\", "/").rsplit("/", 1)[-1].lower()
if name not in IDLE:
result.append(int(entry.name))
except (OSError, ValueError):
continue
return result
def idle(folder, appid, game):
_, _, target = target_for(folder, appid, game)
if active(target.compatdata):
raise ValueError("Close the GOG game before maintenance")
return 0
def validate_installer(folder, installer):
root = control(folder)
path = Path(installer)
if path.is_symlink() or not path.resolve(strict=True).is_relative_to(root / "downloads") or path.suffix.lower() != ".exe":
raise ValueError("The patch executable is outside GOG download storage")
with path.open("rb") as stream:
if stream.read(2) != b"MZ":
raise ValueError("The GOG patch is not a Windows executable")
return path
def installer_arguments(path):
with path.open("rb") as stream:
data = stream.read(4 * 1024 * 1024)
return ["/NOGUI"] if b"Inno Setup Setup Data" in data else []
def start(folder, appid, installer, game):
root = control(folder)
validate_installer(folder, installer)
with lock_file(root) as stream:
fcntl.lockf(stream, fcntl.LOCK_EX | fcntl.LOCK_NB)
journal = read(root / "operation.json")
if journal.get("phase") != "patch-ready":
raise ValueError("The patch must be selected again before it can run")
idle(folder, appid, game)
journal["phase"] = "patch-starting"
write(root / "operation.json", journal)
write(root / "patch-status.json", {"state": "starting", "startedAt": time.time()})
with (root / "patch.log").open("ab") as log:
subprocess.Popen([sys.executable, str(Path(__file__).resolve()), "run", folder, appid, installer, game],
stdin=subprocess.DEVNULL, stdout=log, stderr=log, start_new_session=True, close_fds=True)
return 0
def status(folder):
root = control(folder)
path = root / "patch-status.json"
result = read(path)
ended = result.get("state") == "running" and generation(result.get("pid")) != result.get("generation")
abandoned = result.get("state") == "starting" and time.time() - result.get("startedAt", 0) > 60
if ended or abandoned:
result = {"state": "uncertain", "reason": "The patch helper ended without a confirmed result; verify recovery before retrying"}
write(path, result)
journal = read(root / "operation.json")
journal["phase"] = "patch-uncertain"
write(root / "operation.json", journal)
print(json.dumps(result), flush=True)
return 0
def run_patch(folder, appid, installer, game):
root = control(folder)
try:
with lock_file(root) as stream:
fcntl.lockf(stream, fcntl.LOCK_EX)
path = validate_installer(folder, installer)
command, env, prefix = runner(folder, appid, game, True)
if active(prefix):
raise ValueError("Close the GOG game before applying the patch")
journal = read(root / "operation.json")
if journal.get("phase") != "patch-starting":
raise ValueError("The patch is already running or needs recovery")
journal["phase"] = "patch-applying"
write(root / "operation.json", journal)
sidecar_path = Path(folder) / ".droiddeck-store.json"
sidecar = read(sidecar_path)
sidecar["state"] = "updating"
write(sidecar_path, sidecar)
installed_path = root / "installed.json"
if installed_path.is_file():
installed = read(installed_path)
installed.update(verified=False, manifest={}, files=[])
write(installed_path, installed)
write(root / "patch-status.json", {"state": "running", "pid": os.getpid(), "generation": generation(os.getpid())})
os.makedirs(prefix, exist_ok=True)
setup = runpy.run_path(str(BIN / "droiddeck-store-launch"))["main"].__globals__
previous = dict(os.environ)
try:
os.environ.update(env)
pfx = Path(prefix) / "pfx"
if not (pfx / "system.reg").is_file() or not (pfx / "drive_c/windows/system32/reg.exe").is_file():
subprocess.run([command, "run", "wineboot.exe", "-u"], env=env, timeout=90, check=True)
if not (pfx / "drive_c/windows/system32/reg.exe").is_file():
raise ValueError("Proton did not initialize the game's registry tool")
result = setup["apply_gog_registry"](Path(folder), prefix, command, installation=journal.get("before"))
if not result.startswith(("ready", "written=")):
raise ValueError("GOG registry preparation failed; the patch was not applied")
prepare_setup(folder, command, env)
finally:
os.environ.clear(); os.environ.update(previous)
proc = subprocess.Popen([command, "run", str(path), *installer_arguments(path)], cwd=str(path.parent), env=env)
code = proc.wait()
quiet_at = time.monotonic()
while True:
if active(prefix):
quiet_at = time.monotonic()
elif time.monotonic() - quiet_at >= 2:
break
time.sleep(0.25)
journal["phase"] = "patch-uncertain"
write(root / "operation.json", journal)
if code:
raise ValueError("GOG patch installer exited with code %d; inspect patch.log" % code)
write(root / "patch-status.json", {"state": "done", "exitCode": code})
return 0
except Exception as error:
write(root / "patch-status.json", {"state": "failed", "reason": str(error)})
return 1
def prepare_setup(folder, command, env):
root = control(folder)
record_path = root / "installed.json"
if not record_path.is_file():
return
journal = read(root / "operation.json")
record = journal.get("before") or read(record_path)
manifest = record.get("manifest", {})
if not record.get("build"):
return
info_path = Path(folder) / ("goggame-%s.info" % record["id"])
language = read(info_path).get("language", "") if info_path.is_file() else ""
legacy = manifest.get("product", {})
products = manifest.get("products", []) if not legacy else [
{"productId": str(item["gameID"]), "temp_executable": item["executable"].lstrip("/\\")}
for item in legacy.get("support_commands", [])
if "Neutral" in item.get("languages", []) or record.get("language") in item.get("languages", []) or language in item.get("languages", [])]
for product in products:
if str(product.get("productId")) not in record.get("products", []):
continue
program = None
if manifest.get("scriptInterpreter"):
if not (Path(folder) / ("goggame-%s.script" % product["productId"])).is_file():
continue
program = Path(folder) / "support/__redist/ISI/scriptinterpreter.exe"
elif product.get("temp_executable"):
relative = product["temp_executable"].replace("\\", "/")
for candidate in (Path(folder) / "support" / str(product["productId"]) / relative, Path(folder) / relative):
if candidate.is_file():
program = candidate
break
if program is None:
continue
if not program.resolve(strict=True).is_relative_to(Path(folder).resolve()):
raise ValueError("GOG setup executable leaves the installation")
windows = "Z:" + str(Path(folder).resolve()).replace("/", "\\")
args = ["/VERYSILENT", "/DIR=" + windows, "/ProductId=" + str(product["productId"]),
"/galaxyclient", "/buildId=" + str(legacy.get("timestamp", record["build"])), "/versionName=" + record.get("version", ""),
"/lang-code=" + record.get("language", "en-US"), "/supportDir=" + windows + "\\support", "/nodesktopshortcut"]
if language:
args += ["/Language=" + language, "/LANG=" + language.lower()]
result = subprocess.run([command, "run", str(program), *args], env=env, cwd=folder, timeout=120)
if result.returncode:
raise ValueError("GOG installation setup failed; the patch was not applied")
def main(argv):
if len(argv) == 3 and argv[0] == "lease":
return lease(argv[1], int(argv[2]))
if len(argv) == 4 and argv[0] == "idle":
return idle(*argv[1:])
if len(argv) == 2 and argv[0] == "status":
return status(argv[1])
if len(argv) == 5 and argv[0] == "start":
return start(*argv[1:])
if len(argv) == 5 and argv[0] == "run":
return run_patch(*argv[1:])
raise ValueError("Invalid GOG maintenance command")
if __name__ == "__main__":
try:
sys.exit(main(sys.argv[1:]))
except Exception as error:
print("GOG maintenance: " + str(error), file=sys.stderr)
sys.exit(1)
+140
View File
@@ -0,0 +1,140 @@
#!/usr/bin/env python3
import json
import os
import select
import socket
import struct
import sys
import time
DISPLAY_ID = 1
REGISTRY_ID = 2
METHOD_ID = 3
SETTLE = 0.15
def wl_string(value):
data = value.encode() + b"\0"
return struct.pack("<I", len(data)) + data + b"\0" * (-len(data) % 4)
def read_string(payload, offset):
(length,) = struct.unpack_from("<I", payload, offset)
start = offset + 4
text = payload[start:start + length - 1].decode(errors="replace")
return text, start + length + (-length % 4)
class Connection:
def __init__(self, sock):
self.sock = sock
self.buffer = b""
def send(self, obj, opcode, payload=b""):
self.sock.sendall(struct.pack("<II", obj, ((8 + len(payload)) << 16) | opcode) + payload)
def messages(self, timeout):
ready, _, _ = select.select([self.sock], [], [], timeout)
if not ready:
return []
data, _, _, _ = self.sock.recvmsg(65536, socket.CMSG_SPACE(16 * 4))
if not data:
raise EOFError
self.buffer += data
out = []
while len(self.buffer) >= 8:
obj, word = struct.unpack_from("<II", self.buffer)
size = word >> 16
if size < 8 or len(self.buffer) < size:
break
out.append((obj, word & 0xFFFF, self.buffer[8:size]))
self.buffer = self.buffer[size:]
return out
class Report:
def __init__(self, directory):
self.directory = directory
self.seq = 0
self.sent = None
def write(self, field, hint=0, purpose=0):
state = (field, purpose)
if state == self.sent or not self.directory:
return
self.sent = state
self.seq += 1
os.makedirs(self.directory, exist_ok=True)
target = os.path.join(self.directory, "ime.json")
temp = target + ".tmp"
fd = os.open(temp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
with os.fdopen(fd, "w") as handle:
json.dump({"textField": field, "hint": hint, "purpose": purpose, "seq": self.seq}, handle)
os.replace(temp, target)
print(f"droiddeck-ime: text field {'focused' if field else 'left'}", file=sys.stderr, flush=True)
def connect():
fd = os.environ.pop("WAYLAND_SOCKET", "")
if fd.isdigit():
return socket.socket(socket.AF_UNIX, socket.SOCK_STREAM, fileno=int(fd))
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
sock.connect(os.path.join(os.environ["XDG_RUNTIME_DIR"], os.environ.get("WAYLAND_DISPLAY", "wayland-0")))
return sock
def main():
launch = os.environ.get("BL_LAUNCH_DIR", "")
report = Report(os.path.join(launch, "agent") if launch else "")
conn = Connection(connect())
conn.send(DISPLAY_ID, 1, struct.pack("<I", REGISTRY_ID))
contexts = {}
current = None
pending = None
while True:
timeout = None if pending is None else max(0.0, pending - time.monotonic())
try:
batch = conn.messages(timeout)
except (EOFError, ConnectionError):
report.write(False)
return 0
for obj, opcode, payload in batch:
if obj == DISPLAY_ID and opcode == 0:
_, code = struct.unpack_from("<II", payload)
message, _ = read_string(payload, 8)
print(f"droiddeck-ime: protocol error {code}: {message}", file=sys.stderr, flush=True)
report.write(False)
return 1
if obj == REGISTRY_ID and opcode == 0:
(name,) = struct.unpack_from("<I", payload)
interface, offset = read_string(payload, 4)
(version,) = struct.unpack_from("<I", payload, offset)
if interface == "zwp_input_method_v1":
conn.send(REGISTRY_ID, 0, struct.pack("<I", name) + wl_string(interface)
+ struct.pack("<II", min(version, 1), METHOD_ID))
elif obj == METHOD_ID and opcode == 0:
(context,) = struct.unpack_from("<I", payload)
contexts[context] = [0, 0]
current = context
pending = None
report.write(True)
elif obj == METHOD_ID and opcode == 1:
(context,) = struct.unpack_from("<I", payload)
contexts.pop(context, None)
conn.send(context, 0)
if context == current:
current = None
pending = time.monotonic() + SETTLE
elif obj in contexts and opcode == 2:
hint, purpose = struct.unpack_from("<II", payload)
contexts[obj] = [hint, purpose]
if obj == current:
report.write(True, hint, purpose)
if pending is not None and time.monotonic() >= pending:
pending = None
if current is None:
report.write(False)
if __name__ == "__main__":
sys.exit(main())
@@ -0,0 +1,93 @@
#!/usr/bin/python3
import os
import re
import stat
import sys
HOME = os.environ.get("HOME", "/root")
STEAM = os.path.join(HOME, ".local/share/Steam")
STORES = os.environ.get("DROIDDECK_STORES_ROOT", "/mnt/droiddeck-stores")
TOOLS = re.compile(r"^(Proton |Proton$|SteamLinuxRuntime|Steamworks Shared$)")
def libraries():
paths = [STEAM]
try:
with open(os.path.join(STEAM, "steamapps/libraryfolders.vdf"), encoding="utf-8", errors="replace") as f:
paths += [p.replace("\\\\", "\\") for p in re.findall(r'"path"\s+"([^"]+)"', f.read())]
except OSError:
pass
seen = []
for path in paths:
real = os.path.realpath(path)
if real not in seen:
seen.append(real)
return seen
def roots():
found = []
for library in libraries():
for name in ("common", "compatdata"):
found.append((os.path.join(library, "steamapps", name), name == "common"))
found.append((os.path.join(HOME, "Games"), False))
try:
found += [(entry.path, False) for entry in os.scandir(STORES) if entry.is_dir(follow_symlinks=False)]
except OSError:
pass
return [(path, skip_tools) for path, skip_tools in found if os.path.isdir(path)]
def fix(path, st, wanted):
if st.st_uid != os.geteuid() or st.st_mode & wanted == wanted:
return 0
try:
os.chmod(path, stat.S_IMODE(st.st_mode) | wanted)
return 1
except OSError:
return 0
def walk(top, skip_tools):
fixed = 0
stack = [(top, True)]
while stack:
directory, first = stack.pop()
try:
entries = list(os.scandir(directory))
except OSError:
continue
for entry in entries:
if first and skip_tools and TOOLS.match(entry.name):
continue
try:
st = entry.stat(follow_symlinks=False)
except OSError:
continue
if stat.S_ISDIR(st.st_mode):
fixed += fix(entry.path, st, stat.S_IRWXU)
stack.append((entry.path, False))
elif stat.S_ISREG(st.st_mode):
fixed += fix(entry.path, st, stat.S_IRUSR | stat.S_IWUSR)
return fixed
def main():
try:
os.nice(19)
except OSError:
pass
total = 0
for top, skip_tools in roots():
try:
fixed = fix(top, os.stat(top), stat.S_IRWXU) + walk(top, skip_tools)
except OSError:
continue
if fixed:
print(f"droiddeck-library-perms: {top}: {fixed} made writable")
total += fixed
print(f"droiddeck-library-perms: {total} files and folders made writable")
if __name__ == "__main__":
sys.exit(main())
+94
View File
@@ -0,0 +1,94 @@
#!/usr/bin/python3
import array
import json
import os
import signal
import socket
import struct
import sys
SOCKET_FILE = "/etc/droiddeck/root-socket"
def socket_name():
name = os.environ.get("DROIDDECK_ROOT_SOCKET", "")
if not name:
try:
with open(SOCKET_FILE, encoding="utf-8") as f:
name = f.read().strip()
except OSError:
pass
return "\0" + (name or "com.droiddeck.launcher.root")
def frame(sock, kind, payload):
sock.sendall(kind.encode() + struct.pack(">i", len(payload)) + payload)
def read_exact(sock, n):
data = b""
while len(data) < n:
chunk = sock.recv(n - len(data))
if not chunk:
return None
data += chunk
return data
def main(argv):
if len(argv) < 2 or argv[1] in ("-h", "--help"):
print("usage: droiddeck-root [--check] command [arg ...]", file=sys.stderr)
return 2
try:
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
sock.connect(socket_name())
except OSError as e:
print(f"droiddeck-root: DroidDeck's root service is not reachable: {e}", file=sys.stderr)
return 126
if argv[1] == "--check":
return 0
env = dict(os.environ)
for name in ("LD_PRELOAD", "PROOT_FASTPATH", "DROIDDECK_ROOT_SOCKET"):
env.pop(name, None)
for name in [k for k in env if k.startswith("PROOT_")]:
env.pop(name, None)
try:
cwd = os.getcwd()
except OSError:
cwd = "/root"
body = json.dumps({"argv": argv[1:], "env": env, "cwd": cwd}).encode()
fds = array.array("i", [0, 1, 2])
sock.sendmsg([b"R" + struct.pack(">i", len(body))], [(socket.SOL_SOCKET, socket.SCM_RIGHTS, fds)])
sock.sendall(body)
def forward(signum, _frame):
try:
frame(sock, "S", str(signum).encode())
except OSError:
pass
for signum in (signal.SIGINT, signal.SIGTERM, signal.SIGHUP, signal.SIGQUIT, signal.SIGUSR1, signal.SIGUSR2):
signal.signal(signum, forward)
signal.signal(signal.SIGTSTP, signal.SIG_IGN)
status = 1
while True:
try:
head = read_exact(sock, 5)
except InterruptedError:
continue
except OSError:
break
if head is None:
break
kind = chr(head[0])
payload = read_exact(sock, struct.unpack(">i", head[1:])[0]) or b""
if kind == "E":
print("droiddeck-root: " + payload.decode(errors="replace"), file=sys.stderr)
elif kind == "X":
status = int(payload.decode() or "1")
break
return status
if __name__ == "__main__":
sys.exit(main(sys.argv))
@@ -14,22 +14,59 @@ if [ -n "${BL_LOG:-}" ] && [ -z "${BL_INSIDE:-}" ]; then
if [ "$(stat -c %s "$BL_LOG" 2>/dev/null || echo 0)" -gt 8388608 ]; then
mv -f "$BL_LOG" "$BL_LOG.1"
fi
exec > >({ dd of="$BL_LOG" oflag=append conv=notrunc iflag=count_bytes count="${BL_LOG_CAP:-268435456}" bs=65536 status=none; cat >/dev/null; }) 2>&1
dd=$(command -v gnudd || echo dd)
exec > >({ "$dd" of="$BL_LOG" oflag=append conv=notrunc iflag=count_bytes count="${BL_LOG_CAP:-268435456}" bs=65536 status=none; cat >/dev/null; }) 2>&1
echo "== droiddeck-session $(date) mode=$mode $*"
echo "== uid=$(id -u) size=${BL_WIDTH:-?}x${BL_HEIGHT:-?} icd=${VK_ICD_FILENAMES:-none}"
echo "== gamescope: $(gamescope --version 2>&1 | head -1) at $(command -v gamescope)"
echo "== rootfs: $(cat /.version 2>/dev/null || echo unversioned)"
fi
sync_timezone() {
local zone=${TZ:-}
case "$zone" in ''|/*|*..*) return 0 ;; esac
[ -f "/usr/share/zoneinfo/$zone" ] || return 0
if [ "$(readlink /etc/localtime 2>/dev/null)" != "/usr/share/zoneinfo/$zone" ]; then
ln -sfn "/usr/share/zoneinfo/$zone" /etc/localtime.droiddeck && mv -Tf /etc/localtime.droiddeck /etc/localtime || return 0
fi
[ "$(cat /etc/timezone 2>/dev/null)" = "$zone" ] || printf '%s\n' "$zone" > /etc/timezone
} 2>/dev/null
sync_timezone
write_system_bus_config() {
mkdir -p /run/dbus /usr/local/share/droiddeck
cat > /usr/local/share/droiddeck/system-bus.conf <<'BUSCONF'
<!DOCTYPE busconfig PUBLIC "-//freedesktop//DTD D-Bus Bus Configuration 1.0//EN"
"http://www.freedesktop.org/standards/dbus/1.0/busconfig.dtd">
<busconfig>
<type>system</type>
<listen>unix:path=/run/dbus/system_bus_socket</listen>
<auth>EXTERNAL</auth>
<servicedir>/usr/share/droiddeck/system-services</servicedir>
<policy context="default">
<allow user="*"/>
<allow own="*"/>
<allow send_destination="*"/>
<allow receive_sender="*"/>
</policy>
</busconfig>
BUSCONF
rm -f /run/dbus/system_bus_socket
}
prepare_locale() {
local dir=/usr/lib/locale stamp=/usr/lib/locale/.droiddeck-archive want have= pkg
pkg=(/var/lib/pacman/local/glibc-[0-9]*)
want=${pkg[0]##*/}
if [ -d /var/lib/pacman/local ]; then
pkg=(/var/lib/pacman/local/glibc-[0-9]*)
want=${pkg[0]##*/}
else
want=libc6-$(dpkg-query -W -f='${Version}' libc6 2>/dev/null)
fi
[ -f "$stamp" ] && read -r have < "$stamp"
[ "$have" = "$want" ] && [ -f "$dir/locale-archive" ] && [ ! "$dir/locale-archive" -nt "$stamp" ] && return 0
[ -d "$dir/C.utf8" ] && command -v localedef >/dev/null 2>&1 || return 0
DROIDDECK_LINK_RENAME=1 localedef --add-to-archive --replace "$dir/C.utf8" >/dev/null 2>&1 || return 0
rm -f /usr/lib/gconv/gconv-modules.cache
rm -f /usr/lib/gconv/gconv-modules.cache /usr/lib/aarch64-linux-gnu/gconv/gconv-modules.cache
command -v iconvconfig >/dev/null 2>&1 && iconvconfig >/dev/null 2>&1
printf '%s\n' "$want" > "$stamp"
echo "== locale archive built for $want"
@@ -64,8 +101,33 @@ if [ -z "${BL_INSIDE:-}" ]; then
if [ "${BL_ZRAM:-0}" = 1 ]; then printf 0 > /tmp/.bl-zram; else rm -f /tmp/.bl-zram; fi
fi
steam_devtools() {
_bl_cdp=()
if [ -f "$steam_root/.cef-enable-remote-debugging" ]; then
if timeout 5 python3 -c 'import socket, sys
s = socket.socket()
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(("127.0.0.1", int(sys.argv[1])))' "$1" 2>/dev/null; then
BL_CDP_PORT=$1
return 0
fi
echo "== steam: port $1 is held by another app; Decky cannot load this session and Steam's devtools use another port"
fi
BL_CDP_PORT=$((20000 + RANDOM % 30000))
_bl_cdp=(-cef-enable-debugging -devtools-port "$BL_CDP_PORT")
}
steam_update_stuck() {
[ "$1" -lt 60 ] || steam_updates=0
local stamp
stamp=$(stat -c '%n %Y %s' "${steam_root:-}"/package/*.installed 2>/dev/null)
if [ "$1" -ge 60 ]; then
steam_updates=0
steam_installs=0
elif [ "$stamp" != "${steam_update_stamp-$stamp}" ] && [ "${steam_installs:-0}" -lt 5 ]; then
steam_updates=0
steam_installs=$((${steam_installs:-0} + 1))
fi
steam_update_stamp=$stamp
steam_updates=$((steam_updates + 1))
[ "$steam_updates" -ge 3 ]
}
@@ -210,6 +272,7 @@ 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
/usr/local/bin/droiddeck-downloads || true
fi
export FLATPAK_BWRAP=/usr/local/bin/droiddeck-bwrap
export XDG_DATA_DIRS=$XDG_DATA_HOME/flatpak/exports/share:${XDG_DATA_DIRS:-/usr/local/share:/usr/share}
@@ -277,6 +340,20 @@ if [ -z "${BL_INSIDE:-}" ]; then
step "starting the desktop"
start_agent --no-focus
[ -x /usr/local/bin/droiddeck-desktop ] || { echo "== the desktop package is not installed"; exit 66; }
if command -v dbus-daemon >/dev/null 2>&1 && command -v droiddeck-netmanager >/dev/null 2>&1; then
write_system_bus_config
dbus-daemon --config-file=/usr/local/share/droiddeck/system-bus.conf --nofork --nopidfile &
for _ in $(seq 1 50); do
[ -S /run/dbus/system_bus_socket ] && break
nap 0.1
done
if [ -S /run/dbus/system_bus_socket ]; then
droiddeck-login1 --with-netmanager &
echo "== desktop: system bus up, network and power services running"
else
echo "== desktop: the system bus did not come up"
fi
fi
cores=$(program_cores)
if [ -n "$cores" ]; then
echo "== desktop cores: $cores (the desktop and every program started from it)"
@@ -321,6 +398,8 @@ if [ -z "${BL_INSIDE:-}" ]; then
fi
if [ "${BL_REFRESH:-0}" -gt 0 ]; then
args+=(-r "$BL_REFRESH")
# -r is the starting rate; gamescope follows the panel when it switches modes later.
export GAMESCOPE_NESTED_REFRESH_FOLLOWS_HOST=1
fi
[ "$mode" = steam ] && [ "${BL_STEAM_UI:-}" != desktop ] && args+=(-e)
if [ "$mode" = steam ] && [ "${BL_XWAYLAND_COUNT:-2}" -gt 1 ]; then
@@ -338,6 +417,8 @@ if [ -z "${BL_INSIDE:-}" ]; then
args+=(--mangoapp)
echo "== gamescope: mangoapp on ($(command -v mangoapp), config $MANGOHUD_CONFIGFILE)"
fi
# gamescope writes the frame times the app's HUD shows here (patch 0125).
mkdir -p /run/droiddeck-hud && export DROIDDECK_HUD_FRAMES=/run/droiddeck-hud/frames
export BL_INSIDE=1
# A fixed path: left to itself gamescope creates a new limiter state file on every start.
rm -f "${XDG_RUNTIME_DIR:-/tmp}"/gamescope-limiter-*
@@ -540,7 +621,7 @@ case $mode in
fi
if [ "${BL_ZRAM:-0}" = 1 ]; then
step "zRAM compression: on"
[ "${BL_ZRAM_CLIENT:-1}" = 1 ] || step "zRAM: Steam is not compressed while games run (turned off in Performance)"
[ "${BL_ZRAM_CLIENT:-1}" = 1 ] || step "zRAM: Steam and the hidden Epic Games Launcher are not compressed while games run (turned off in Performance)"
_bl_ram_cap=0
case ${BL_RAM_CAP_MB:-} in
''|0) ;;
@@ -550,16 +631,16 @@ case $mode in
(
bl_zram_scan() {
_bl_game=0 _bl_pids=() _bl_others=() _bl_apps=
local _d _c _args _name _a _id
local _d _c _args _name _a _id _fex
for _d in /proc/[0-9]*; do
[ "${_d##*/}" != "$BASHPID" ] || continue
_args=()
# Under FEX the program is FEX's first argument. AppId= is its own argument.
while IFS= read -r -d '' _c; do _args+=("$_c"); done 2>/dev/null < "$_d/cmdline" || true
[ "${#_args[@]}" -gt 0 ] || continue
_name=${_args[0]}
_name=${_args[0]} _fex=0
if [ "${#_args[@]}" -gt 1 ]; then
case ${_name##*/} in FEX|FEXInterpreter) _name=${_args[1]} ;; esac
case ${_name##*/} in FEX|FEXInterpreter) _name=${_args[1]} _fex=1 ;; esac
fi
case ${_name##*/} in
reaper)
@@ -574,7 +655,13 @@ case $mode in
done
;;
steam|steamwebhelper) _bl_pids+=("${_d##*/}") ;;
*) _bl_others+=("${_d##*/}") ;;
*)
if [ "$_fex" = 1 ] && grep -qz '^DROIDDECK_EPIC_HIDDEN=1$' "$_d/environ" 2>/dev/null; then
_bl_pids+=("${_d##*/}")
else
_bl_others+=("${_d##*/}")
fi
;;
esac
done
}
@@ -921,23 +1008,7 @@ case $mode in
set -- "$@" "$_bl_url"
fi
if command -v dbus-daemon >/dev/null 2>&1 && command -v droiddeck-netmanager >/dev/null 2>&1; then
mkdir -p /run/dbus /usr/local/share/droiddeck
cat > /usr/local/share/droiddeck/system-bus.conf <<'BUSCONF'
<!DOCTYPE busconfig PUBLIC "-//freedesktop//DTD D-Bus Bus Configuration 1.0//EN"
"http://www.freedesktop.org/standards/dbus/1.0/busconfig.dtd">
<busconfig>
<type>system</type>
<listen>unix:path=/run/dbus/system_bus_socket</listen>
<auth>EXTERNAL</auth>
<policy context="default">
<allow user="*"/>
<allow own="*"/>
<allow send_destination="*"/>
<allow receive_sender="*"/>
</policy>
</busconfig>
BUSCONF
rm -f /run/dbus/system_bus_socket
write_system_bus_config
dbus-daemon --config-file=/usr/local/share/droiddeck/system-bus.conf --nofork --nopidfile &
system_bus=$!
for _ in $(seq 1 50); do
@@ -1011,14 +1082,9 @@ BUSCONF
echo "== Decky: installed loader architecture is unsupported by this guest; not starting"
fi
fi
_bl_cdp=()
if [ -f "$steam_root/.cef-enable-remote-debugging" ]; then
export BL_CDP_PORT=8080
else
export BL_CDP_PORT=$((20000 + RANDOM % 30000))
_bl_cdp=(-cef-enable-debugging -devtools-port "$BL_CDP_PORT")
fi
if [ -f "$HOME/.droiddeck-decky-enabled" ] && [ "${decky_arch:-}" = x86_64 ]; then
steam_devtools 8080
export BL_CDP_PORT
if [ -f "$HOME/.droiddeck-decky-enabled" ] && [ "${decky_arch:-}" = x86_64 ] && [ ${#_bl_cdp[@]} = 0 ]; then
echo "== steam: devtools port $BL_CDP_PORT left open for the x86_64 Decky loader"
else
export BL_CDP_GUARD=$BL_CDP_PORT
@@ -1099,6 +1165,8 @@ BUSCONF
fi
echo "== steam args: ${_bl_ui[*]} ${_bl_cdp[*]} ${_bl_lang[*]} -clientbeta $steam_channel -no-cef-sandbox -cef-ozone-platform=x11 ${_bl_cef[*]} $*$([ "$steam_x64" = 1 ] && echo ' (x86-64 client under FEX)')"
steam_updates=0
steam_installs=0
steam_update_stamp=$(stat -c '%n %Y %s' "$steam_root"/package/*.installed 2>/dev/null)
rm -f "$HOME/.bl-stop-requested" "$STEAMOS_STEAM_SHUTDOWN_SENTINEL" "$STEAMOS_STEAM_REBOOT_SENTINEL"
steam_other_game_running() {
local line value n open
+15
View File
@@ -0,0 +1,15 @@
#!/bin/bash
[ "${1:-}" = run ] || exec /usr/bin/snap "$@"
shift
while [ $# -gt 0 ]; do
case $1 in
--) shift; break ;;
-*) shift ;;
*) break ;;
esac
done
target=${1:?usage: snap run <snap>[.<app>] [args...]}
shift
name=${target%%.*}
app=${target#*.}
exec /usr/local/bin/droiddeck-snap-run "$name" "$app" "$@"
+19
View File
@@ -0,0 +1,19 @@
#!/bin/bash
while [ $# -gt 0 ]; do
case $1 in
--classic) shift ;;
--base) shift 2 ;;
--*) shift ;;
*) break ;;
esac
done
tag=${1:?security tag}
shift
[ "${1##*/}" = snap-exec ] && shift
app=${1:-}
shift
name=${tag#snap.}
name=${name%%.*}
app=${app#*.}
[ -n "$app" ] || app=$name
exec /usr/local/bin/droiddeck-snap-run "$name" "$app" "$@"
+139
View File
@@ -0,0 +1,139 @@
#!/usr/bin/python3
import os
import re
import shlex
import sys
import yaml
SNAP_DIR = "/snap"
HOST_DIRS = ("/etc", "/home", "/root", "/tmp", "/run", "/var/snap", "/var/lib/snapd", "/var/tmp", "/var/log",
"/media", "/mnt", "/snap", "/usr/src", "/lib/modules")
def load(name):
with open(f"{SNAP_DIR}/{name}/current/meta/snap.yaml") as f:
return yaml.safe_load(f) or {}
def expand(value, env):
return re.sub(r"\$\{?([A-Za-z_][A-Za-z0-9_]*)\}?", lambda m: env.get(m.group(1), ""), str(value))
def provider_path(path, provider, revision):
snap = f"{SNAP_DIR}/{provider}/{revision}"
for var, value in (("$SNAP_DATA", f"/var/snap/{provider}/{revision}"),
("$SNAP_COMMON", f"/var/snap/{provider}/common"), ("$SNAP", snap)):
if path == var or path.startswith(var + "/"):
return os.path.normpath(value + path[len(var):])
return os.path.normpath(f"{snap}/{path}")
def content_binds(name, meta, env):
out = []
for plug_name, plug in (meta.get("plugs") or {}).items():
if not isinstance(plug, dict) or plug.get("interface") != "content" or not plug.get("target"):
continue
provider = (plug.get("default-provider") or "").split(":")[0]
if not provider or not os.path.isdir(f"{SNAP_DIR}/{provider}/current"):
continue
try:
slots = load(provider).get("slots") or {}
except OSError:
continue
revision = os.path.basename(os.path.realpath(f"{SNAP_DIR}/{provider}/current"))
target = expand(plug["target"], env)
for slot_name, slot in slots.items():
if not isinstance(slot, dict) or slot.get("interface") != "content":
continue
if slot.get("content", slot_name) != plug.get("content", plug_name):
continue
nested = "source" in slot
reads = (slot.get("source") or {}).get("read") if nested else slot.get("read")
for path in reads or []:
source = provider_path(str(path), provider, revision)
out.append((plug_name, source, os.path.join(target, os.path.basename(source)) if nested else target))
if not nested:
break
break
return out
def main(argv):
if len(argv) < 3:
print("usage: droiddeck-snap-run SNAP APP [ARG...]", file=sys.stderr)
return 2
name, app, args = argv[1], argv[2], argv[3:]
meta = load(name)
spec = (meta.get("apps") or {}).get(app)
if spec is None:
print(f"error: snap \"{name}\" has no app \"{app}\"", file=sys.stderr)
return 1
revision = os.path.basename(os.path.realpath(f"{SNAP_DIR}/{name}/current"))
home = os.environ.get("HOME", "/root")
snap = f"{SNAP_DIR}/{name}/{revision}"
env = dict(os.environ)
for k in ("LD_PRELOAD", "LD_LIBRARY_PATH"):
env.pop(k, None)
env.update({
"SNAP": snap, "SNAP_NAME": name, "SNAP_INSTANCE_NAME": name, "SNAP_INSTANCE_KEY": "",
"SNAP_REVISION": revision, "SNAP_VERSION": str(meta.get("version", "")), "SNAP_ARCH": "arm64",
"SNAP_LIBRARY_PATH": "/var/lib/snapd/lib/gl:/var/lib/snapd/lib/gl32:/var/lib/snapd/void",
"SNAP_DATA": f"/var/snap/{name}/{revision}", "SNAP_COMMON": f"/var/snap/{name}/common",
"SNAP_USER_DATA": f"{home}/snap/{name}/{revision}", "SNAP_USER_COMMON": f"{home}/snap/{name}/common",
"SNAP_REAL_HOME": home, "SNAP_UID": str(os.getuid()), "SNAP_EUID": str(os.geteuid()),
"SNAP_COOKIE": "", "SNAP_CONTEXT": "", "SNAP_REEXEC": "0",
})
for d in (env["SNAP_USER_DATA"], env["SNAP_USER_COMMON"], env["SNAP_DATA"], env["SNAP_COMMON"]):
os.makedirs(d, exist_ok=True)
current = f"{home}/snap/{name}/current"
if os.path.realpath(current) != env["SNAP_USER_DATA"]:
try:
os.unlink(current)
except OSError:
pass
os.symlink(revision, current)
confinement = meta.get("confinement", "strict")
if confinement != "classic":
env["HOME"] = env["SNAP_USER_DATA"]
env["PATH"] = ":".join([f"{snap}/usr/sbin", f"{snap}/usr/bin", f"{snap}/sbin", f"{snap}/bin",
"/usr/local/sbin", "/usr/local/bin", "/usr/sbin", "/usr/bin", "/sbin", "/bin", "/usr/games"])
env["LD_LIBRARY_PATH"] = env["SNAP_LIBRARY_PATH"]
for scope in (meta.get("environment") or {}, spec.get("environment") or {}):
for k, v in scope.items():
env[k] = expand(v, env)
command = shlex.split(expand(spec.get("command", ""), env))
if command and not command[0].startswith("/"):
command[0] = f"{snap}/{command[0]}"
chain = [c if c.startswith("/") else f"{snap}/{c}" for c in (meta.get("command-chain") or []) + (spec.get("command-chain") or [])]
program = chain + command + args
if confinement == "classic":
os.execvpe(program[0], program, env)
base = meta.get("base") or "core"
root = f"{SNAP_DIR}/{base}/current"
if not os.path.isdir(root):
print(f"error: the base snap \"{base}\" is not installed; run: snap install {base}", file=sys.stderr)
return 1
bwrap = ["/usr/local/bin/droiddeck-bwrap", "--bind", root, "/", "--dev-bind", "/dev", "/dev", "--proc", "/proc",
"--bind", "/sys", "/sys"]
for d in HOST_DIRS:
if os.path.isdir(d):
bwrap += ["--bind", d, d]
bwrap += ["--bind", "/", "/var/lib/snapd/hostfs"]
bwrap += ["--bind", "/dev/null", "/etc/ld.so.preload"]
binds = content_binds(name, meta, env)
for _, source, target in binds:
if os.path.isdir(source):
bwrap += ["--bind", source, target]
content = {k for k, v in (meta.get("plugs") or {}).items() if isinstance(v, dict) and v.get("interface") == "content"}
plugs = (set(meta.get("plugs") or {}) | set(spec.get("plugs") or [])) - content | {plug for plug, _, _ in binds}
env["DROIDDECK_SNAP_PLUGS"] = " ".join(sorted(plugs))
bwrap += ["--bind", "/usr/local/bin/droiddeck-snapctl", "/usr/lib/snapd/snapctl"]
bwrap += ["--chdir", os.getcwd() if os.path.isdir(os.getcwd()) else env["HOME"], "--clearenv"]
for k, v in env.items():
bwrap += ["--setenv", k, v]
os.execv(bwrap[0], bwrap + ["--"] + program)
if __name__ == "__main__":
sys.exit(main(sys.argv))
+12
View File
@@ -0,0 +1,12 @@
#!/bin/sh
case $1 in
is-connected)
shift
while [ $# -gt 1 ]; do shift; done
case " $DROIDDECK_SNAP_PLUGS " in
*" ${1:-} "*) exit 0 ;;
esac
exit 1
;;
esac
exit 0
+542
View File
@@ -0,0 +1,542 @@
#!/usr/bin/python3
import datetime
import hashlib
import http.server
import json
import os
import re
import shutil
import socketserver
import subprocess
import sys
import threading
import urllib.parse
import urllib.request
STORE = "https://api.snapcraft.io/v2"
ARCH = "arm64"
SNAP_DIR = "/snap"
BIN_DIR = "/snap/bin"
LIB = "/var/lib/snapd"
STATE = LIB + "/droiddeck-state.json"
DESKTOP_DIR = LIB + "/desktop/applications"
SOCKETS = ("/run/snapd.socket", "/run/snapd-snap.socket")
FIND_FIELDS = ("title,summary,description,version,revision,confinement,base,publisher,license,contact,website,"
"media,categories,store-url,download,type,channel,common-ids,links")
INFO_FIELDS = ("title,summary,description,version,revision,confinement,base,publisher,license,contact,website,"
"media,categories,snap-id,store-url,download,type,channel-map,common-ids,links,created-at")
HEADERS = {"Snap-Device-Series": "16", "Snap-Device-Architecture": ARCH, "User-Agent": "snapd/2.70 droiddeck"}
lock = threading.RLock()
install_lock = threading.Lock()
changes = {}
change_seq = [0]
def now():
return datetime.datetime.now(datetime.timezone.utc).isoformat()
def load_state():
try:
with open(STATE) as f:
return json.load(f)
except (OSError, ValueError):
return {"snaps": {}}
def save_state(state):
tmp = STATE + ".tmp"
with open(tmp, "w") as f:
json.dump(state, f, indent=1)
os.replace(tmp, STATE)
def store_get(path, params=None):
url = STORE + path + ("?" + urllib.parse.urlencode(params) if params else "")
req = urllib.request.Request(url, headers=HEADERS)
with urllib.request.urlopen(req, timeout=60) as r:
return json.load(r)
def publisher(p):
p = p or {}
return {"id": p.get("id", ""), "username": p.get("username", ""), "display-name": p.get("display-name", ""),
"validation": p.get("validation", "unproven")}
def media_of(snap):
out = []
for m in snap.get("media") or []:
if m.get("type") in ("icon", "screenshot", "banner") and m.get("url"):
item = {"type": m["type"], "url": m["url"]}
if m.get("width"):
item["width"] = m["width"]
item["height"] = m.get("height", 0)
out.append(item)
return out
def icon_of(media):
return next((m["url"] for m in media if m["type"] == "icon"), "")
def from_store(name, snap, revision=None, channel=None):
media = media_of(snap)
rev = revision or snap.get("revision") or {}
out = {
"id": snap.get("snap-id", ""), "name": name, "title": snap.get("title") or name,
"summary": snap.get("summary", ""), "description": snap.get("description", ""),
"type": rev.get("type") or snap.get("type") or "app", "version": rev.get("version", ""),
"revision": str(rev.get("revision", "")), "channel": channel or "stable",
"confinement": rev.get("confinement") or "strict", "base": rev.get("base") or "",
"publisher": publisher(snap.get("publisher")), "developer": (snap.get("publisher") or {}).get("username", ""),
"license": snap.get("license", ""), "contact": snap.get("contact", ""), "website": snap.get("website", ""),
"media": media, "icon": icon_of(media), "store-url": snap.get("store-url", ""),
"download-size": (rev.get("download") or {}).get("size", 0), "status": "available",
"categories": [{"name": c.get("name", ""), "featured": bool(c.get("featured"))} for c in snap.get("categories") or []],
"common-ids": rev.get("common-ids") or snap.get("common-ids") or [],
"private": False, "devmode": False, "jailmode": False, "trymode": False, "apps": [],
}
return out
def installed_snap(name, entry):
snap = dict(entry["info"])
snap["status"] = "active"
snap["install-date"] = entry.get("installed", now())
snap["installed-size"] = entry.get("size", 0)
snap["revision"] = str(entry["revision"])
snap["version"] = entry.get("version", snap.get("version", ""))
snap["tracking-channel"] = entry.get("channel", "latest/stable")
snap["channel"] = entry.get("channel", "latest/stable")
snap["mounted-from"] = f"{LIB}/snaps/{name}_{entry['revision']}.snap"
snap["apps"] = [{"name": a, "snap": name, "desktop-file": f"{DESKTOP_DIR}/{name}_{a}.desktop"} for a in entry.get("apps", [])]
return snap
def find(query, section=None, name_exact=False):
if name_exact:
try:
info = store_get(f"/snaps/info/{query}", {"architecture": ARCH, "fields": INFO_FIELDS})
except Exception:
return []
rev = next((c for c in info.get("channel-map", []) if c["channel"]["architecture"] == ARCH
and c["channel"]["risk"] == "stable"), None)
if not rev:
return []
return [from_store(info["name"], dict(info["snap"], **{"snap-id": info.get("snap-id", "")}), rev, "stable")]
params = {"architecture": ARCH, "fields": FIND_FIELDS}
if query:
params["q"] = query
if section:
params["category"] = section
if not query and not section:
params["featured"] = "true"
result = store_get("/snaps/find", params)
out = []
state = load_state()
for r in result.get("results", []):
snap = from_store(r["name"], dict(r.get("snap", {}), **{"snap-id": r.get("snap-id", "")}), r.get("revision"))
if r["name"] in state["snaps"]:
snap["status"] = "active"
snap["installed-size"] = state["snaps"][r["name"]].get("size", 0)
out.append(snap)
return out
def new_change(kind, summary, snaps):
with lock:
change_seq[0] += 1
cid = str(change_seq[0])
changes[cid] = {"id": cid, "kind": kind, "summary": summary, "status": "Doing", "ready": False,
"spawn-time": now(), "tasks": [{"id": cid + "-1", "kind": kind, "summary": summary, "status": "Doing",
"progress": {"label": "", "done": 0, "total": 1},
"spawn-time": now()}],
"data": {"snap-names": snaps}}
return cid
def progress(cid, label, done, total):
with lock:
task = changes[cid]["tasks"][0]
task["progress"] = {"label": label, "done": done, "total": max(total, 1)}
task["summary"] = changes[cid]["summary"]
def finish(cid, err=None):
with lock:
c = changes[cid]
c["status"] = "Error" if err else "Done"
c["ready"] = True
c["ready-time"] = now()
c["tasks"][0]["status"] = c["status"]
if err:
c["err"] = err
def root_run(argv):
if os.getuid() == 0:
return subprocess.run(argv, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)
return subprocess.run(["/usr/local/bin/droiddeck-root"] + argv, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
text=True)
def snap_yaml(path):
try:
import yaml
with open(path) as f:
return yaml.safe_load(f) or {}
except Exception:
return {}
def download(cid, name, url, sha3, size, target):
tmp = target + ".partial"
h = hashlib.sha3_384()
req = urllib.request.Request(url, headers=HEADERS)
with urllib.request.urlopen(req, timeout=120) as r, open(tmp, "wb") as out:
done = 0
while True:
chunk = r.read(1 << 20)
if not chunk:
break
out.write(chunk)
h.update(chunk)
done += len(chunk)
progress(cid, f"Download snap \"{name}\"", done, size)
if sha3 and h.hexdigest() != sha3:
os.unlink(tmp)
raise RuntimeError(f"{name}: downloaded snap does not match the store's sha3-384")
os.replace(tmp, target)
def write_desktop(name, rev, meta):
os.makedirs(DESKTOP_DIR, exist_ok=True)
gui = f"{SNAP_DIR}/{name}/{rev}/meta/gui"
apps = (meta.get("apps") or {})
for app, spec in apps.items():
source = os.path.join(gui, f"{app}.desktop")
if (spec or {}).get("daemon") or not os.path.isfile(source):
continue
command = name if app == name else f"{name}.{app}"
out = []
with open(source, encoding="utf-8", errors="replace") as f:
for line in f:
if line.startswith("Exec="):
args = line[5:].strip().split(" ", 1)
rest = (" " + args[1]) if len(args) > 1 else ""
line = f"Exec={BIN_DIR}/{command}{rest}\n"
elif line.startswith("Icon="):
line = "Icon=" + line[5:].replace("${SNAP}", f"{SNAP_DIR}/{name}/current")
out.append(line)
out.append(f"X-SnapInstanceName={name}\n")
target = f"{DESKTOP_DIR}/{name}_{app}.desktop"
with open(target + ".tmp", "w", encoding="utf-8") as f:
f.writelines(out)
os.replace(target + ".tmp", target)
subprocess.run(["update-desktop-database", DESKTOP_DIR], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
def link_bins(name, meta):
os.makedirs(BIN_DIR, exist_ok=True)
apps = []
for app, spec in (meta.get("apps") or {}).items():
if (spec or {}).get("daemon"):
continue
command = name if app == name else f"{name}.{app}"
path = os.path.join(BIN_DIR, command)
with open(path + ".tmp", "w") as f:
f.write(f"#!/bin/sh\nexec /usr/local/bin/droiddeck-snap-run {name} {app} \"$@\"\n")
os.chmod(path + ".tmp", 0o755)
os.replace(path + ".tmp", path)
apps.append(app)
return apps
def remove_tree(top):
if os.path.isdir(top) and not os.path.islink(top):
os.chmod(top, 0o700)
for root, dirs, _ in os.walk(top):
for d in dirs:
path = os.path.join(root, d)
if not os.path.islink(path):
os.chmod(path, 0o700)
shutil.rmtree(top, ignore_errors=True)
def install_one(cid, name, channel, state, parents=()):
if name in state["snaps"] or name in parents:
return
info = store_get(f"/snaps/info/{name}", {"architecture": ARCH, "fields": INFO_FIELDS})
risk = channel.split("/")[-1] if channel else "stable"
track = channel.split("/")[0] if channel and "/" in channel else "latest"
rev = next((c for c in info.get("channel-map", []) if c["channel"]["architecture"] == ARCH
and c["channel"]["risk"] == risk and c["channel"]["track"] == track), None)
if not rev:
raise RuntimeError(f"snap \"{name}\" has no {track}/{risk} release for {ARCH}")
number = rev["revision"]
os.makedirs(f"{LIB}/snaps", exist_ok=True)
blob = f"{LIB}/snaps/{name}_{number}.snap"
d = rev.get("download") or {}
with lock:
changes[cid]["summary"] = f"Install \"{name}\" snap"
download(cid, name, d["url"], d.get("sha3-384"), d.get("size", 0), blob)
progress(cid, f"Unpack snap \"{name}\"", 0, 1)
target = f"{SNAP_DIR}/{name}/{number}"
remove_tree(target)
os.makedirs(os.path.dirname(target), exist_ok=True)
r = root_run(["unsquashfs", "-q", "-n", "-no-xattrs", "-f", "-excludes", "-d", target, blob, "dev"])
if r.returncode != 0:
raise RuntimeError(f"cannot unpack {name}: {r.stdout.strip()[-400:]}")
os.makedirs(f"{target}/dev", exist_ok=True)
current = f"{SNAP_DIR}/{name}/current"
if os.path.islink(current):
os.unlink(current)
os.symlink(str(number), current)
for sub in (f"/var/snap/{name}/{number}", f"/var/snap/{name}/common"):
os.makedirs(sub, exist_ok=True)
cur = f"/var/snap/{name}/current"
if os.path.islink(cur):
os.unlink(cur)
os.symlink(str(number), cur)
meta = snap_yaml(f"{target}/meta/snap.yaml")
entry = {"revision": number, "version": rev.get("version", ""), "channel": f"{track}/{risk}",
"installed": now(), "size": d.get("size", 0), "info": from_store(name, dict(info["snap"], **{"snap-id": info.get("snap-id", "")}), rev, f"{track}/{risk}"),
"base": meta.get("base") or ("core" if (meta.get("type") or "app") == "app" else ""), "apps": []}
base = meta.get("base")
if (meta.get("type") or "app") == "app":
install_one(cid, base or "core", "latest/stable", state, parents + (name,))
for plug in (meta.get("plugs") or {}).values():
if isinstance(plug, dict) and plug.get("interface") == "content" and plug.get("default-provider"):
provider = plug["default-provider"].split(":")[0]
install_one(cid, provider, "latest/stable", state, parents + (name,))
entry["apps"] = link_bins(name, meta)
write_desktop(name, number, meta)
state["snaps"][name] = entry
save_state(state)
def remove_one(name, state):
entry = state["snaps"].pop(name, None)
if not entry:
raise RuntimeError(f"snap \"{name}\" is not installed")
for app in entry.get("apps", []):
command = name if app == name else f"{name}.{app}"
try:
os.unlink(os.path.join(BIN_DIR, command))
except OSError:
pass
if os.path.isdir(DESKTOP_DIR):
for f in os.listdir(DESKTOP_DIR):
if f.startswith(name + "_") and f.endswith(".desktop"):
os.unlink(os.path.join(DESKTOP_DIR, f))
subprocess.run(["update-desktop-database", DESKTOP_DIR], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
remove_tree(f"{SNAP_DIR}/{name}")
for f in os.listdir(f"{LIB}/snaps"):
if f.startswith(name + "_"):
os.unlink(os.path.join(f"{LIB}/snaps", f))
save_state(state)
def run_change(cid, action, names, channel):
with install_lock:
apply_change(cid, action, names, channel)
def apply_change(cid, action, names, channel):
try:
state = load_state()
for name in names:
if action == "install":
install_one(cid, name, channel or "latest/stable", state)
elif action == "remove":
remove_one(name, state)
elif action == "refresh":
old = state["snaps"].get(name)
if old:
remove_one(name, state)
install_one(cid, name, old.get("channel", "latest/stable"), state)
else:
raise RuntimeError(f"unsupported action {action}")
finish(cid)
except Exception as e:
finish(cid, str(e))
SECTIONS = ["featured", "art-and-design", "books-and-reference", "development", "devices-and-iot", "education",
"entertainment", "finance", "games", "health-and-fitness", "music-and-audio", "news-and-weather",
"personalisation", "photo-and-video", "productivity", "science", "security", "server-and-cloud",
"social", "utilities"]
class Handler(http.server.BaseHTTPRequestHandler):
protocol_version = "HTTP/1.1"
def log_message(self, fmt, *args):
pass
def address_string(self):
return "snapd"
def reply(self, body, code=200, kind="sync"):
payload = {"type": kind, "status-code": code, "status": http.client.responses.get(code, "")}
payload.update(body)
data = json.dumps(payload).encode()
self.send_response(code)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(data)))
self.end_headers()
self.wfile.write(data)
def ok(self, result):
self.reply({"result": result})
def error(self, code, message, kind=""):
self.reply({"result": {"message": message, "kind": kind}}, code, "error")
def body(self):
n = int(self.headers.get("Content-Length") or 0)
raw = self.rfile.read(n) if n else b"{}"
try:
return json.loads(raw or b"{}")
except ValueError:
return {}
def do_GET(self):
url = urllib.parse.urlsplit(self.path)
q = urllib.parse.parse_qs(url.query)
path = url.path
try:
if path == "/v2/system-info":
return self.ok({"series": "16", "version": "2.70+droiddeck", "build-id": "droiddeck", "os-release": {"id": "ubuntu", "version-id": "26.04"},
"on-classic": True, "managed": False, "kernel-version": os.uname().release,
"locations": {"snap-mount-dir": SNAP_DIR, "snap-bin-dir": BIN_DIR},
"refresh": {"timer": "00:00~24:00/4"}, "confinement": "partial",
"sandbox-features": {}, "architecture": ARCH})
if path == "/v2/snaps":
state = load_state()
wanted = (q.get("snaps", [""])[0] or "").split(",")
snaps = [installed_snap(n, e) for n, e in state["snaps"].items() if not wanted[0] or n in wanted]
return self.ok(snaps)
m = re.fullmatch(r"/v2/snaps/([^/]+)", path)
if m:
state = load_state()
if m.group(1) in state["snaps"]:
return self.ok(installed_snap(m.group(1), state["snaps"][m.group(1)]))
return self.error(404, f"snap not installed", "snap-not-found")
if path == "/v2/find":
name = q.get("name", [None])[0]
query = name or q.get("q", [""])[0]
section = q.get("section", [None])[0] or q.get("category", [None])[0]
if section == "featured":
section = None
select = q.get("select", [""])[0]
if select == "refresh":
return self.ok([])
if select == "private":
return self.ok([])
return self.ok(find(query, section, bool(name)))
if path in ("/v2/sections",):
return self.ok(SECTIONS)
if path == "/v2/categories":
return self.ok([{"name": s} for s in SECTIONS if s != "featured"])
m = re.fullmatch(r"/v2/changes/([^/]+)", path)
if m:
with lock:
c = changes.get(m.group(1))
c = json.loads(json.dumps(c)) if c else None
return self.ok(c) if c else self.error(404, "cannot find change", "")
if path == "/v2/changes":
with lock:
return self.ok([json.loads(json.dumps(c)) for c in changes.values()])
m = re.fullmatch(r"/v2/icons/([^/]+)/icon", path)
if m:
return self.icon(m.group(1))
if path == "/v2/apps":
state = load_state()
apps = [{"snap": n, "name": a, "desktop-file": f"{DESKTOP_DIR}/{n}_{a}.desktop"}
for n, e in state["snaps"].items() for a in e.get("apps", [])]
return self.ok(apps)
if path in ("/v2/connections", "/v2/interfaces"):
return self.ok({"established": [], "plugs": [], "slots": []})
if path in ("/v2/aliases", "/v2/users", "/v2/notices", "/v2/assertions/model"):
return self.ok({} if path == "/v2/aliases" else [])
return self.error(404, f"not found: {path}")
except Exception as e:
return self.error(500, str(e))
def icon(self, name):
state = load_state()
entry = state["snaps"].get(name)
if not entry:
return self.error(404, "not installed", "snap-not-found")
for candidate in ("meta/gui/icon.png", "meta/gui/icon.svg"):
path = f"{SNAP_DIR}/{name}/current/{candidate}"
if os.path.isfile(path):
with open(path, "rb") as f:
data = f.read()
self.send_response(200)
self.send_header("Content-Type", "image/svg+xml" if path.endswith("svg") else "image/png")
self.send_header("Content-Length", str(len(data)))
self.end_headers()
self.wfile.write(data)
return
return self.error(404, "no icon", "")
def do_POST(self):
path = urllib.parse.urlsplit(self.path).path
body = self.body()
m = re.fullmatch(r"/v2/snaps/([^/]+)", path)
if m or path == "/v2/snaps":
names = [m.group(1)] if m else body.get("snaps") or []
action = body.get("action", "")
channel = body.get("channel") or ""
if channel and "/" not in channel:
channel = "latest/" + channel
if action not in ("install", "remove", "refresh"):
return self.error(400, f"unsupported action \"{action}\"")
cid = new_change(f"{action}-snap", f"{action.capitalize()} {', '.join(names)}", names)
threading.Thread(target=run_change, args=(cid, action, names, channel), daemon=True).start()
return self.reply({"change": cid}, 202, "async")
m = re.fullmatch(r"/v2/changes/([^/]+)", path)
if m:
return self.error(400, "changes cannot be aborted")
if path in ("/v2/login", "/v2/logout", "/v2/snapctl"):
return self.error(400, "not supported by DroidDeck's snap service")
return self.error(404, f"not found: {path}")
def do_PUT(self):
return self.do_POST()
class Server(socketserver.ThreadingMixIn, socketserver.UnixStreamServer):
daemon_threads = True
def get_request(self):
conn, _ = self.socket.accept()
return conn, ("snapd", 0)
def serve(path):
try:
os.unlink(path)
except OSError:
pass
server = Server(path, Handler)
os.chmod(path, 0o666)
server.serve_forever()
def main():
for d in (LIB, SNAP_DIR, BIN_DIR, DESKTOP_DIR, LIB + "/snaps"):
os.makedirs(d, exist_ok=True)
threads = [threading.Thread(target=serve, args=(p,), daemon=True) for p in SOCKETS]
for t in threads:
t.start()
for t in threads:
t.join()
if __name__ == "__main__":
sys.exit(main())
@@ -23,15 +23,20 @@ BRIGHTNESS_JS = r"""
if (window.__droiddeckBrightness) return "present";
const display = SteamClient.System?.Display;
if (!display?.RegisterForBrightnessChanges || !display?.SetBrightness) return "unavailable";
const self = { expected: null, updating: true, revision: 0 };
const self = { expected: null, updating: true, revision: 0, localAt: -Infinity };
// A held stick steps Steam faster than Android's readback returns; those stale readbacks would snap the slider back.
const HOLD_MS = 750;
// Returns "held" while a readback is being ignored, so the caller retries it after the hold.
self.set = value => {
if (typeof value !== "number" || !Number.isFinite(value) || value < 0 || value > 1) return;
if (!self.updating && self.expected !== null && Math.abs(value - self.expected) < 0.0001) return;
if (typeof value !== "number" || !Number.isFinite(value) || value < 0 || value > 1) return true;
if (performance.now() - self.localAt < HOLD_MS) return "held";
if (!self.updating && self.expected !== null && Math.abs(value - self.expected) < 0.0001) return true;
self.expected = value;
self.updating = true;
const revision = ++self.revision;
setTimeout(() => { if (self.revision === revision) self.updating = false; }, 500);
display.SetBrightness(value);
return true;
};
self.subscription = display.RegisterForBrightnessChanges(state => {
const value = state?.flBrightness;
@@ -39,6 +44,7 @@ BRIGHTNESS_JS = r"""
if (Math.abs(value - self.expected) < 0.0001) { self.updating = false; return; }
if (self.updating) { self.updating = false; return; }
self.expected = value;
self.localAt = performance.now();
if (typeof window.__BINDING__ === "function") window.__BINDING__(String(value));
});
window.__droiddeckBrightness = self;
@@ -241,6 +247,74 @@ TOUR_JS = r"""
return "off";
})()
"""
# Steam keeps the Quick Access Frame Limit as the client setting gamescope_app_target_framerate
# (CMsgClientSettings field 21002) and offers the values gamescope's display state lists in
# active_display_info.supported_frame_rates. When the panel's refresh rate changes, a remembered
# limit that is not one of the new values leaves the slider on its first value while the game runs
# at the old limit. The limit is kept when it is still offered and moved to the highest value
# otherwise. Choices are read once they have been unchanged for a moment, since a mode switch can
# report a passing rate first.
FRAME_LIMIT_JS = r"""
(() => {
if (window.__droiddeckFrameLimit) return "present";
const settings = window.settingsStore;
let service = null;
try {
// Steam's webpack does not expose its module cache; the gamescope service client is found by
// the calls its module makes and loaded by id.
let require;
window.webpackChunksteamui.push([[Symbol("droiddeck-frame-limit")], {}, r => { require = r; }]);
for (const id of Object.keys(require.m || {})) {
const source = String(require.m[id]);
if (!source.includes("SetBlurParams") || !source.includes("RegisterForNotifyStateChanged")) continue;
let exports;
try { exports = require(id); } catch (e) { continue; }
if (!exports || typeof exports !== "object") continue;
service = Object.values(exports).find(value => value && typeof value.GetState === "function" &&
typeof value.RegisterForNotifyStateChanged === "function" && typeof value.SetBlurParams === "function");
if (service) break;
}
} catch (e) {
service = null;
}
if (!service || !settings?.clientSettings || typeof SteamClient.Settings?.SetSetting !== "function") return "unavailable";
const self = { timer: null };
const write = value => {
const bytes = [];
for (let n of [21002 * 8, value]) {
while (n > 127) { bytes.push((n & 127) | 128); n = Math.floor(n / 128); }
bytes.push(n);
}
return SteamClient.Settings.SetSetting(btoa(String.fromCharCode(...bytes)));
};
self.check = async () => {
let rates;
try {
const reply = await service.GetState({});
if (!reply.BSuccess()) return;
rates = reply.Body().toObject().state?.active_display_info?.supported_frame_rates;
} catch (e) {
return;
}
if (!Array.isArray(rates) || rates.length === 0) return;
const current = settings.clientSettings;
if (!current.gamescope_enable_app_target_framerate || rates.includes(current.gamescope_app_target_framerate)) return;
try {
await write(Math.max(...rates));
} catch (e) {
}
};
self.schedule = () => {
clearTimeout(self.timer);
self.timer = setTimeout(self.check, 1500);
};
self.subscription = service.RegisterForNotifyStateChanged(self.schedule);
self.interval = setInterval(self.schedule, 5000);
self.schedule();
window.__droiddeckFrameLimit = self;
return "installed";
})()
"""
FILE_BINDING = "droiddeckOpenFileDialog"
FILE_JS = r"""
(() => {
@@ -680,6 +754,8 @@ class Helper:
self.chooser = None
self.controls_state = None
self.controls_installed = False
self.frame_limit_state = None
self.frame_limit_retry = 0
def sync_controls(self):
try:
@@ -694,14 +770,28 @@ class Helper:
if not self.controls_installed:
return
if state != self.controls_state:
if self.page.evaluate("!!window.__droiddeckBrightness && (window.__droiddeckBrightness.set(%s), true)" % json.dumps(value)) is True:
applied = self.page.evaluate("window.__droiddeckBrightness ? window.__droiddeckBrightness.set(%s) : false" % json.dumps(value))
if applied is True:
self.controls_state = state
else:
elif applied != "held":
self.controls_installed = False
self.controls_state = None
except (OSError, ValueError, TypeError):
pass
def sync_frame_limit(self):
# Steam can still be loading its settings and gamescope state when the helper attaches.
if self.frame_limit_state in ("installed", "present") or time.monotonic() < self.frame_limit_retry:
return
try:
state = self.page.evaluate(FRAME_LIMIT_JS)
except RuntimeError as e:
state = "failed (%s)" % e
if state != self.frame_limit_state:
say("frame limit sync: %s" % state)
self.frame_limit_state = state
self.frame_limit_retry = time.monotonic() + 10
def open_chooser(self, payload):
try:
request = json.loads(payload)
@@ -801,6 +891,8 @@ class Helper:
self.page = page
self.controls_state = None
self.controls_installed = False
self.frame_limit_state = None
self.frame_limit_retry = 0
self.sync_controls()
return True
@@ -956,6 +1048,7 @@ class Helper:
self.ensure_tools()
while True:
self.sync_controls()
self.sync_frame_limit()
sources = [self.page.ws] + ([watcher] if watcher.fileno() >= 0 else [])
if self.chooser is not None:
sources.append(self.chooser[1].stdout)
@@ -14,6 +14,7 @@ import urllib.parse
import urllib.request
STATE = ".droiddeck-games.json"
TRIED = ".droiddeck-import-tried.json"
WINNATIVE = ".winnative-steam/steamapps"
LIBRARY = "/mnt/droiddeck-sd"
LEGACY_LIBRARY = "/mnt/bannerlator-sd"
@@ -179,10 +180,44 @@ def request_restart(steam_root):
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=30)
def ask_restart(names, timeout=600, clock=None, sleep=None):
"""The app asks whether to restart the client now; anything but "now" leaves the import to the next start."""
clock, sleep = clock or time.monotonic, sleep or time.sleep
folder = Path(os.environ.get("HOME", "/root"), ".cache/droiddeck")
ask, answer = folder / "steam-import.json", folder / "steam-import.answer"
token = str(time.time_ns())
answer.unlink(missing_ok=True)
save_json(ask, {"token": token, "games": names})
try:
deadline = clock() + timeout
while clock() < deadline:
reply = read_json(answer, None)
if isinstance(reply, dict) and reply.get("token") == token:
return reply.get("choice") == "now"
sleep(1)
return False
finally:
ask.unlink(missing_ok=True)
answer.unlink(missing_ok=True)
def unimported(steam_root, snapshot, candidates):
routes = read_json(Path(steam_root) / "userdata" / snapshot["account"] / "config/.droiddeck-routes.json", {})
config = Path(steam_root) / "userdata" / snapshot["account"] / "config"
routes = read_json(config / ".droiddeck-routes.json", {})
routed = set(routes.values()) if isinstance(routes, dict) else set()
return sorted({appid for appid in candidates.values() if snapshot["owned"].get(str(appid)) is True} - routed)
tried = read_json(config / TRIED, [])
tried = {appid for appid in tried if isinstance(appid, int)} if isinstance(tried, list) else set()
owned = {appid for appid in candidates.values() if snapshot["owned"].get(str(appid)) is True}
if tried - routed != tried:
save_json(config / TRIED, sorted(tried - routed))
return sorted(owned - routed - tried)
def remember_tried(steam_root, account, appids):
config = Path(steam_root) / "userdata" / account / "config"
tried = read_json(config / TRIED, [])
tried = {appid for appid in tried if isinstance(appid, int)} if isinstance(tried, list) else set()
save_json(config / TRIED, sorted(tried | set(appids)))
def watch(steam_root, listing):
@@ -193,7 +228,7 @@ def watch(steam_root, listing):
next_lookup = 0
last_status = None
probed, next_probe, failures = None, 0, 0
pending, requested = [], []
pending, requested, account = [], [], None
while True:
now = time.monotonic()
for game in games:
@@ -233,6 +268,7 @@ def watch(steam_root, listing):
snapshot["sources"] = sources
save_json(Path(steam_root) / "userdata" / snapshot["account"] / "config" / STATE, snapshot)
pending = unimported(steam_root, snapshot, candidates)
account = snapshot["account"]
status = "matched %d/%d games; %d owned" % (len(candidates), len(games), sum(snapshot["owned"].values()))
except (OSError, ValueError, KeyError, StopIteration, subprocess.TimeoutExpired) as error:
status = "ownership check unavailable: " + str(error)
@@ -242,9 +278,14 @@ def watch(steam_root, listing):
status = last_status
if pending and pending != requested and not game_running() and downloads_idle(steam_root):
requested = pending
print("droiddeck-steam-games: restarting the client once to import %s" % pending, flush=True)
names = sorted({game["name"] for game in games if candidates.get(game["folder"]) in pending})
try:
request_restart(steam_root)
remember_tried(steam_root, account, pending)
if ask_restart(names) and not game_running() and downloads_idle(steam_root):
print("droiddeck-steam-games: restarting the client once to import %s" % pending, flush=True)
request_restart(steam_root)
else:
print("droiddeck-steam-games: %s will be imported the next time the client starts" % pending, flush=True)
except (OSError, subprocess.TimeoutExpired) as error:
print("droiddeck-steam-games: restart unavailable: %s" % error, flush=True)
if status != last_status:
@@ -436,6 +477,7 @@ def route(steam_root, acct, games):
if seed_install(steam_root, game, appid):
routes[str(game["appid"])] = appid
continue
print(f"droiddeck-steam-games: {game.get('name', appid)} stays a shortcut this session: it could not be linked as Steam app {appid}")
except OSError as error:
print(f"droiddeck-steam-games: import unavailable ({error})")
elif isinstance(appid, int) and 0 < appid < 0x80000000 and seeded(steamapps, game, appid):
@@ -39,6 +39,7 @@ if [ "$ui" = desktop ] && [ "${BL_DESKTOP:-}" = 1 ]; then
echo "droiddeck-steam-launch: the desktop client did not become ready" >&2
exit 69
fi
[ "$url" = steam://exit ] && exit 0
export BL_INSIDE=1 BL_STEAM_UI=desktop
exec /usr/local/bin/droiddeck-session steam "${url:-steam://open/library}"
fi
@@ -6,6 +6,7 @@ if [ "${BL_DESKTOP:-}" = 1 ]; then
for arg in "$@"; do
case $arg in
steam://*) url=$arg ;;
-shutdown) url=steam://exit ;;
-gamepadui|-bigpicture) ui=bigpicture ;;
esac
done
@@ -799,13 +799,25 @@ x64_gpu_watch() {
x64_gpu_probe
}
x64_arm_webhelper_cpu_supported() {
local status=0
# Valve's native ARM web helper contains LSE atomics; missing CPU data cannot establish incompatibility.
awk -F: '
$1 ~ /^[[:space:]]*Features[[:space:]]*$/ {
if ($2 !~ /(^|[[:space:]])atomics([[:space:]]|$)/) unsupported = 1
}
END { exit unsupported ? 1 : 0 }
' /proc/cpuinfo 2>/dev/null || status=$?
[ "$status" != 1 ]
}
x64_exec() {
x64_env
cd "$STEAM_X64"
# The client checksums its files at start and reinstalls over edited ones, so the session shim (preload/net.c)
# swaps the web helper at exec. The arm64 helper only comes up against a client of the same build.
if [ "${BL_X64_X86_WEBHELPER:-0}" != 1 ] && [ -x /usr/local/bin/droiddeck-x64-arm-webhelper ] &&
[ -x "$ARM_STEAM/steamrtarm64/steamwebhelper" ]; then
[ -x "$ARM_STEAM/steamrtarm64/steamwebhelper" ] && x64_arm_webhelper_cpu_supported; then
local chan x86_build arm_build
chan=$(cat "$STEAM_X64/package/beta" 2>/dev/null || echo "$X64_CHANNEL")
x86_build=$(awk -F'"' '$2 == "version" { print $4; exit }' "$STEAM_X64/package/steam_client_${chan}_steamrt64.manifest" 2>/dev/null || true)
@@ -1049,4 +1061,4 @@ for attempt in 1 2 3 4 5; do
( x64_exec -clientbeta "$X64_CHANNEL" -no-cef-sandbox "${cef[@]}" "$@" ) >>"$LOG" 2>&1 || rc=$?
step "client exited rc=$rc"
[ "$rc" = 42 ] || break
done
done
@@ -40,6 +40,7 @@ import time
import subprocess
import tempfile
import hashlib
import threading
from pathlib import Path
LAUNCHER = ".droiddeck-launch.bat"
@@ -494,8 +495,27 @@ def gog_registry(folder):
return entries, skipped
def apply_gog_registry(folder, compat_data, proton, timeout=90):
def apply_gog_registry(folder, compat_data, proton, timeout=90, installation=None):
entries, skipped = gog_registry(folder)
if installation:
product = str(installation["id"])
if not product.isdigit():
raise ValueError("Invalid GOG product identifier")
values = {"PATH": windows_path(str(folder))}
identity = Path(folder) / ("goggame-%s.id" % product)
if identity.is_file():
actual = json.loads(identity.read_text(encoding="utf-8-sig")).get("buildId")
if actual and installation.get("build") and str(actual) != str(installation["build"]):
raise ValueError("GOG build metadata changed before patch setup")
if installation.get("build"):
values["BUILDID"] = installation["build"]
if installation.get("version"):
values["VER"] = installation["version"]
for key, value in values.items():
entry = gog_entry({"root": "HKLM", "subkey": "Software\\GOG.com\\Games\\" + product,
"valueName": key, "valueData": value, "valueType": "string"}, {})
if entry:
entries.append(entry)
note = " skipped=%d" % skipped if skipped else ""
if not entries:
return "none" + note
@@ -512,7 +532,8 @@ def apply_gog_registry(folder, compat_data, proton, timeout=90):
with tempfile.TemporaryDirectory(prefix="droiddeck-gog-") as tmp:
source = Path(tmp) / "registry.reg"
source.write_bytes(b"\xff\xfe" + text.encode("utf-16-le"))
run = subprocess.run([proton, "run", "reg.exe", "import", windows_path(str(source)), "/reg:32"],
executable = pfx / "drive_c/windows/system32/reg.exe"
run = subprocess.run([proton, "run", str(executable) if executable.is_file() else "reg.exe", "import", windows_path(str(source)), "/reg:32"],
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=timeout)
if run.returncode or not (pfx / "system.reg").is_file():
return "import-failed" + note
@@ -525,6 +546,8 @@ def apply_gog_registry(folder, compat_data, proton, timeout=90):
def main(argv):
if os.environ.get("DROIDDECK_GOG_MAINTENANCE") == "1":
return 0
if argv and argv[0] == "--exited":
rest, code = argv[1:], 0
if rest[:1] == ["--code"] and len(rest) > 1:
@@ -543,6 +566,18 @@ def main(argv):
return 0
folder, sidecar = found
store, game = str(sidecar.get("store")), str(sidecar.get("id"))
if store == "gog":
helper = Path(__file__).resolve().with_name("droiddeck-gog-maintenance")
if helper.is_file():
child = subprocess.Popen([sys.executable, str(helper), "lease", str(folder), str(os.getppid())],
stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, stdin=subprocess.DEVNULL,
start_new_session=True)
ready = child.stdout.readline().decode().strip()
child.stdout.close()
threading.Thread(target=child.wait, daemon=True).start()
if ready != "ready":
log("gog: close or recover the maintenance operation before playing")
return RAN_FAILED
compat_data = os.environ.get("STEAM_COMPAT_DATA_PATH", "").rstrip("/")
prefix_id = os.path.basename(compat_data) if compat_data else ""
launch_dir = os.environ.get("BL_LAUNCH_DIR", "")
+57
View File
@@ -0,0 +1,57 @@
#!/usr/bin/python3
import os
import sys
REAL = "/usr/bin/systemd-run"
VALUED = {"-u", "--unit", "-p", "--property", "--description", "--slice", "-E", "--setenv",
"--working-directory", "--uid", "--gid", "--nice", "-H", "--host", "-M", "--machine",
"--on-active", "--on-boot", "--on-startup", "--on-unit-active", "--on-unit-inactive",
"--on-calendar", "--path-property", "--socket-property", "--timer-property", "--service-type",
"--shell", "--slice-inherit"}
def main(argv):
args = argv[1:]
if "--user" not in args:
os.execv(REAL, [REAL] + args)
env = dict(os.environ)
cwd = None
foreground = False
i = 0
while i < len(args):
a = args[i]
if a == "--":
i += 1
break
if not a.startswith("-"):
break
name, _, inline = a.partition("=")
value = inline if inline else (args[i + 1] if name in VALUED and i + 1 < len(args) else "")
if name in ("-E", "--setenv") and "=" in value:
k, _, v = value.partition("=")
env[k] = v
elif name == "--working-directory":
cwd = value
elif name in ("--scope", "--wait", "-W", "--pipe", "-P", "-t", "--pty"):
foreground = True
i += 1 if inline or name not in VALUED else 2
command = args[i:]
if not command:
os.execv(REAL, [REAL] + args)
if cwd:
os.chdir(cwd)
if foreground:
os.execvpe(command[0], command, env)
if os.fork() == 0:
os.setsid()
null = os.open(os.devnull, os.O_RDWR)
os.dup2(null, 0)
try:
os.execvpe(command[0], command, env)
except OSError:
os._exit(127)
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv))
+7
View File
@@ -0,0 +1,7 @@
#!/bin/bash
key=$1
shift
line=$(grep -m1 "^$key=" /etc/droiddeck/strings 2>/dev/null)
text=${line#*=}
[ -n "$line" ] || text=$key
printf "$text\n" "$@"
@@ -101,16 +101,18 @@ def registry_values(root):
return good
def expand(store, ids):
def expand(store, ids, saved=None):
"""The picks with everything they bundle, each once, a bundle's parts before it."""
out, seen = [], set()
saved = saved if isinstance(saved, dict) else {}
def visit(cid, depth):
if cid in seen or depth > 8:
return
seen.add(cid)
found = component(store, cid)
for dep in (found[2] if found else []):
parts = found[2] if found else [d for d in saved.get(cid, []) if valid_id(d)]
for dep in parts:
visit(dep, depth + 1)
out.append(cid)
@@ -444,7 +446,7 @@ def list_line(name, current, item, separator, add, at_end=True):
return reg_value_line(name, "expand_sz" if expand else "sz", separator.join(items))
def apply_registry(pfx, values, state):
def apply_registry(pfx, values, state, held=()):
"""Writes the picked components' registry values into the prefix and takes out the ones of
components turned off: a value goes back to what it was before, an entry added to a list such
as PATH just leaves the list. Returns (values written, notes)."""
@@ -478,6 +480,9 @@ def apply_registry(pfx, values, state):
for ident, record in old.items():
if ident in keep or not isinstance(record, dict) or not isinstance(record.get("key"), str):
continue
if record.get("cid") in held:
keep[ident] = record
continue
reg = files.get(record.get("hive"))
if reg is None:
keep[ident] = record
@@ -555,14 +560,44 @@ def apply(compat_path, app_id, selection=SELECTION, store=STORE, pending=PENDING
copied = 0
installed = []
values = []
for cid in expand(store, ids):
held = set()
saved_overrides = state.get("overrides") if isinstance(state.get("overrides"), dict) else {}
saved_requires = state.get("requires") if isinstance(state.get("requires"), dict) else {}
recorded = [c for c in state.get("components", []) if isinstance(c, str) and valid_id(c)]
owners = set(state["files"].values())
registry_owners = {r.get("cid") for r in (state.get("registry") or {}).values() if isinstance(r, dict)}
inferred = set()
guessed = set(state.get("guessed") or []) if "requires" in state else set(ids)
loose = [c for c in recorded if c not in ids and (c in owners or c in registry_owners)]
for cid in ids:
if cid in guessed and component(store, cid) is None and cid in recorded:
saved_requires = dict(saved_requires, **{cid: loose})
inferred.add(cid)
kept_overrides, kept_requires = {}, {}
for cid in expand(store, ids, saved_requires):
found = component(store, cid)
if found is None:
notes.append("%s is not installed; skipped" % cid)
if cid in saved_requires or cid in recorded or cid in owners or cid in registry_owners:
held.add(cid)
if cid in saved_overrides:
names = [n for n in saved_overrides.get(cid, []) if isinstance(n, str)]
else:
names = sorted({Path(rel).stem.lower() for rel, owner in state["files"].items()
if owner == cid and rel.lower().endswith(".dll")})
overrides += names
kept_overrides[cid] = names
if isinstance(saved_requires.get(cid), list) and cid not in inferred:
kept_requires[cid] = saved_requires[cid]
notes.append("%s is not in the store; kept the files it placed until it is installed again" % cid)
else:
notes.append("%s is not installed; skipped" % cid)
continue
installed.append(cid)
names, files, _, registry = found
names, files, requires, registry = found
overrides += names
kept_overrides[cid] = list(names)
if requires:
kept_requires[cid] = list(requires)
values += [(cid, value) for value in registry]
for rel, src in files:
if place(src, pfx / rel, None if rel in state["files"] else compat / BACKUP / rel):
@@ -572,6 +607,9 @@ def apply(compat_path, app_id, selection=SELECTION, store=STORE, pending=PENDING
for rel, cid in state["files"].items():
if rel in keep:
continue
if cid in held:
keep[rel] = cid
continue
path = existing(pfx / rel)
saved = compat / BACKUP / rel
if saved.is_file():
@@ -587,10 +625,13 @@ def apply(compat_path, app_id, selection=SELECTION, store=STORE, pending=PENDING
except FileNotFoundError:
pass
compat.mkdir(parents=True, exist_ok=True)
new_state = {"files": keep, "components": installed, "registry": state.get("registry", {})}
new_state = {"files": keep, "components": installed + sorted(held), "overrides": kept_overrides,
"requires": kept_requires, "registry": state.get("registry", {})}
if inferred:
new_state["guessed"] = sorted(inferred)
written = 0
if values or new_state["registry"]:
written, registry_notes = apply_registry(pfx, values, new_state)
written, registry_notes = apply_registry(pfx, values, new_state, held)
notes += registry_notes
save_state(compat, new_state)
if copied or removed or restored or written:
@@ -151,13 +151,13 @@ def view_drive(prefix, exe):
if os.path.lexists(link) and (os.path.exists(link) or not os.readlink(link).startswith(str(view.parent.parent) + '/')):
continue
devices.mkdir(parents=True, exist_ok=True)
staged.symlink_to(view)
staged.symlink_to(view.parent)
os.replace(staged, link)
except OSError:
if os.path.lexists(staged):
staged.unlink()
continue
return letter.upper() + ':\\' + str(path.relative_to(view)).replace('/', '\\'), link
return letter.upper() + ':\\' + str(path.relative_to(view.parent)).replace('/', '\\'), link
return exe, None
@@ -276,6 +276,18 @@ bl_vacdiag() {
}
"""
# Steam's shader pre-caching runs its D3D driver query through every Proton tool at each start, as
# "run <client>/bin/d3ddriverquery64.exe" in compatdata/0. Here it has never succeeded (exit 1 every time), and each
# run started Wine in compatdata/0, where the two Protons upgrade the prefix back and forth for many seconds while the
# game starts. Steam gets the same failure without starting Wine; other verbs and prefixes are left alone.
BL_DRIVER_QUERY_SKIP = """
case "$verb:${1##*/}:${STEAM_COMPAT_DATA_PATH%/}" in
run:d3ddriverquery64.exe:*/compatdata/0 | run:d3ddriverquery.exe:*/compatdata/0)
echo "droiddeck-proton: Steam's D3D driver query is not run (it fails here and would start Wine in compatdata/0)" >&2
exit 1 ;;
esac
"""
BL_DIRECTAUDIO_SETUP = """
bl_is_steam_installscript_target() {
local target=${1:-}
@@ -408,7 +420,7 @@ LAUNCHER_TEMPLATE = LAUNCHER_SH
def launcher_sh(sources=SOURCES):
return (LAUNCHER_TEMPLATE % " ".join('"%s"' % n for n in sources)).replace(
"verb=$1; shift", "verb=$1; shift\n" + BL_DESKTOP_GPU_SETUP + BL_DIRECTAUDIO_SETUP + BL_GAME_CPUS_SETUP + BL_IDTECH3_SETUP
"verb=$1; shift", "verb=$1; shift\n" + BL_DRIVER_QUERY_SKIP + BL_DESKTOP_GPU_SETUP + BL_DIRECTAUDIO_SETUP + BL_GAME_CPUS_SETUP + BL_IDTECH3_SETUP
+ BL_VACDIAG_SETUP + BL_COMPONENTS_SETUP + BL_LIBPATH_SETUP + BL_STORE_SETUP, 1)
@@ -455,6 +467,15 @@ bl_store_launch "$@"
BL_STORE_ARGS=("$@")
bl_run ${BL_TASKSET:-} /usr/local/bin/droiddeck-game-env "$BL_STORE_PROTON" "$verb" "$@" "${BL_EXTRA_ARGS[@]}"
"""
def extra_wrapper_sh(entry_point):
return (EXTRA_WRAPPER_SH % entry_point).replace(
'here=$(dirname "$0")',
'here=$(dirname "$0")\n' + BL_DRIVER_QUERY_SKIP + BL_DESKTOP_GPU_SETUP + BL_DIRECTAUDIO_SETUP + BL_GAME_CPUS_SETUP
+ BL_IDTECH3_SETUP + BL_VACDIAG_SETUP + BL_COMPONENTS_SETUP + BL_LIBPATH_SETUP + BL_STORE_SETUP, 1)
EXTRA_COMPAT_TOOL_VDF = """"compatibilitytools"
{
"compat_tools"
@@ -678,11 +699,7 @@ def adopt_extras(tools):
name = first_key(compat_vdf, ["compatibilitytools", "compat_tools"]) or entry
wrapper = os.path.join(tool_dir, EXTRA_WRAPPER)
try:
body = (EXTRA_WRAPPER_SH % entry_point).replace(
'here=$(dirname "$0")',
'here=$(dirname "$0")\n' + BL_DESKTOP_GPU_SETUP + BL_DIRECTAUDIO_SETUP + BL_GAME_CPUS_SETUP + BL_IDTECH3_SETUP
+ BL_VACDIAG_SETUP + BL_COMPONENTS_SETUP + BL_LIBPATH_SETUP + BL_STORE_SETUP, 1)
write_changed(wrapper, body, 0o755)
write_changed(wrapper, extra_wrapper_sh(entry_point), 0o755)
write_changed(manifest, EXTRA_MANIFEST_VDF)
write_changed(compat_vdf, EXTRA_COMPAT_TOOL_VDF % (name, display_name(entry)))
legacy_wrapper = os.path.join(tool_dir, LEGACY_EXTRA_WRAPPER)
+2
View File
@@ -407,6 +407,7 @@ int bl_kgsl_poll(int (*real)(int, unsigned long, void *), int fd, unsigned long
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_vdec_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")));
int bl_writewatch_ioctl(int (*real)(int, unsigned long, void *), int fd, unsigned long request, void *arg,
@@ -423,6 +424,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_vdec_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;
+2
View File
@@ -1459,10 +1459,12 @@ 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")));
void bl_vdec_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);
bl_vdec_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);
+3
View File
@@ -15,6 +15,7 @@ int bl_status_without_tracer(const char *path, int flags, const void *caller) __
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_vdec_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")));
@@ -55,6 +56,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 ((fd = bl_vdec_open(path, flags)) != -2) return fd;
if (real_open == NULL) real_open = dlsym(RTLD_NEXT, "open");
if (real_open == NULL) {
errno = ENOSYS;
@@ -81,6 +83,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 ((fd = bl_vdec_open(path, flags)) != -2) return fd;
if (real_openat == NULL) real_openat = dlsym(RTLD_NEXT, "openat");
if (real_openat == NULL) {
errno = ENOSYS;
+41
View File
@@ -0,0 +1,41 @@
#define _GNU_SOURCE
#include <errno.h>
#include <limits.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/statfs.h>
#include <unistd.h>
#define FUSE_MAGIC 0x65735546
#define SDCARDFS_MAGIC 0x5dca2df5
static int is_wineserver(void) {
static int cached = -1;
char exe[PATH_MAX];
const char *base;
ssize_t n;
if (cached >= 0) return cached;
n = readlink("/proc/self/exe", exe, sizeof(exe) - 1);
if (n <= 0) {
cached = 0;
return cached;
}
exe[n] = '\0';
base = strrchr(exe, '/');
cached = strcmp(base ? base + 1 : exe, "wineserver") == 0;
return cached;
}
__attribute__((visibility("hidden")))
void bl_storage_owner(int fd, struct stat *st) {
struct statfs fs;
int saved = errno;
uid_t uid;
if (st != NULL && is_wineserver()) {
uid = getuid();
if (st->st_uid != uid && fstatfs(fd, &fs) == 0 && (fs.f_type == FUSE_MAGIC || fs.f_type == SDCARDFS_MAGIC)) st->st_uid = uid;
}
errno = saved;
}
+21 -2
View File
@@ -139,17 +139,31 @@ static int (*next_faccessat(void))(int, const char *, int, int) {
}
__attribute__((visibility("hidden"))) int bl_binfmt_runnable(const char *path, int mode);
__attribute__((visibility("hidden"))) int bl_writable_access(int dirfd, const char *path, int mode, int flags);
static int writable_as_owner(int (*real)(int, const char *, int, int), int dirfd, const char *path, int mode, int flags) {
if (!bl_writable_access(dirfd, path, mode, flags)) return -1;
if ((mode & ~W_OK) == 0 || real(dirfd, path, mode & ~W_OK, flags) == 0) return 0;
return -1;
}
static int check_cwd(const char *path, int mode, int flags) {
int (*real)(int, const char *, int, int) = next_faccessat();
int result;
int err;
if (real == NULL) {
errno = ENOSYS;
return -1;
}
result = real(AT_FDCWD, path, mode, flags);
return result != 0 && errno == EACCES && bl_binfmt_runnable(path, mode) ? 0 : result;
if (result == 0) return 0;
err = errno;
if (err == EACCES && bl_binfmt_runnable(path, mode)) return 0;
errno = err;
if (writable_as_owner(real, AT_FDCWD, path, mode, flags) == 0) return 0;
errno = err;
return result;
}
int access(const char *path, int mode) {
@@ -166,6 +180,7 @@ int eaccess(const char *path, int mode) {
int faccessat(int dirfd, const char *path, int mode, int flags) {
int (*real)(int, const char *, int, int);
int err;
if (dirfd == AT_FDCWD) {
return cached_access(path, mode, flags, check_cwd);
@@ -175,5 +190,9 @@ int faccessat(int dirfd, const char *path, int mode, int flags) {
errno = ENOSYS;
return -1;
}
return real(dirfd, path, mode, flags);
if (real(dirfd, path, mode, flags) == 0) return 0;
err = errno;
if (writable_as_owner(real, dirfd, path, mode, flags) == 0) return 0;
errno = err;
return -1;
}
+42 -1
View File
@@ -3,6 +3,7 @@
#include <fcntl.h>
#include <limits.h>
#include <string.h>
#include <strings.h>
#include <sys/stat.h>
#include <unistd.h>
@@ -23,6 +24,34 @@ static int is_steam_client(void) {
return cached;
}
static int wine_name(const char *path) {
const char *base;
size_t n;
if (path == NULL) return 0;
base = strrchr(path, '/');
base = base ? base + 1 : path;
n = strlen(path);
return strncmp(base, "wine", 4) == 0 || strstr(path, "/lib/wine/") != NULL
|| (n > 4 && strcasecmp(path + n - 4, ".exe") == 0);
}
static int is_wine(void) {
static int cached = -1;
char exe[PATH_MAX];
ssize_t n;
if (cached >= 0) return cached;
n = readlink("/proc/self/exe", exe, sizeof(exe) - 1);
if (n > 0) exe[n] = '\0';
cached = (n > 0 && wine_name(exe)) || wine_name(program_invocation_name);
return cached;
}
static int acts_as_root(void) {
return is_steam_client() || !is_wine();
}
static int grant_owner_write(int dirfd, const char *path) {
struct stat st;
@@ -37,7 +66,7 @@ int bl_writable_retry(int dirfd, const char *path, int flags) {
char parent[PATH_MAX];
const char *slash;
if (saved != EACCES || path == NULL || (flags & O_ACCMODE) == O_RDONLY || !is_steam_client()) return 0;
if (saved != EACCES || path == NULL || (flags & O_ACCMODE) == O_RDONLY || !acts_as_root()) return 0;
if (faccessat(dirfd, path, F_OK, 0) == 0) {
granted = grant_owner_write(dirfd, path);
} else if (flags & O_CREAT) {
@@ -53,3 +82,15 @@ int bl_writable_retry(int dirfd, const char *path, int flags) {
errno = saved;
return granted;
}
__attribute__((visibility("hidden")))
int bl_writable_access(int dirfd, const char *path, int mode, int flags) {
int saved = errno;
struct stat st;
int owned;
if (saved != EACCES || path == NULL || !(mode & W_OK) || !acts_as_root()) return 0;
owned = fstatat(dirfd, path, &st, flags & AT_SYMLINK_NOFOLLOW) == 0 && st.st_uid == geteuid();
errno = saved;
return owned;
}
+39 -8
View File
@@ -49,6 +49,7 @@ 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 (*next_statx)(int, const char *, int, unsigned int, struct statx *);
static int find_fastpath(struct dl_phdr_info *info, size_t size, void *name) {
(void)size;
@@ -68,6 +69,7 @@ __attribute__((constructor)) static void find_fastpath_calls(void) {
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");
next_statx = (int (*)(int, const char *, int, unsigned int, struct statx *))dlsym(fastpath, "statx");
}
}
@@ -92,6 +94,13 @@ static long path_readlink(int dirfd, const char *path, char *buf, size_t size) {
return next_readlinkat(dirfd, path, buf, size);
}
static long path_statx(int dirfd, const char *path, int flags, unsigned int mask, struct statx *out) {
if (!next_statx) {
return real_syscall(SYS_statx, (long)dirfd, (long)path, (long)flags, (long)mask, (long)out);
}
return next_statx(dirfd, path, flags, mask, out);
}
void *dlopen(const char *filename, int flags) {
if (!real_dlopen) {
real_dlopen = (void *(*)(const char *, int))dlsym(RTLD_NEXT, "dlopen");
@@ -329,6 +338,26 @@ static int execveat_is_execve(const long *args) {
return path[0] == '/' || (int)args[0] == AT_FDCWD;
}
static long openat2_call(const long *args) {
if (!real_syscall) {
real_syscall = (long (*)(long, ...)) dlsym(RTLD_NEXT, "syscall");
}
if (!__atomic_load_n(&openat2_missing, __ATOMIC_RELAXED)) {
long fd = real_syscall(SYS_openat2, args[0], args[1], args[2], args[3]);
if (fd != -1 || errno != ENOSYS) {
return fd;
}
__atomic_store_n(&openat2_missing, 1, __ATOMIC_RELAXED);
}
return openat2_via_openat(args);
}
int bl_openat2(int dirfd, const char *path, void *how, size_t size) __asm__("openat2");
int bl_openat2(int dirfd, const char *path, void *how, size_t size) {
long args[6] = {dirfd, (long)path, (long)how, (long)size, 0, 0};
return (int)openat2_call(args);
}
int bl_writewatch_syscall(long number, const long *args, long (*real)(long, ...), long *rc) __attribute__((visibility("hidden")));
long syscall(long number, ...) {
@@ -360,18 +389,20 @@ long syscall(long number, ...) {
return handled;
}
if (number == SYS_openat2) {
if (!__atomic_load_n(&openat2_missing, __ATOMIC_RELAXED)) {
long fd = real_syscall(number, args[0], args[1], args[2], args[3]);
if (fd != -1 || errno != ENOSYS) {
return fd;
}
__atomic_store_n(&openat2_missing, 1, __ATOMIC_RELAXED);
}
return openat2_via_openat(args);
return openat2_call(args);
}
if (number == SYS_openat) {
return path_open((int)args[0], (const char *)args[1], (int)args[2], args[3]);
}
if (number == BL_SYS_FSTATAT) {
return path_stat((int)args[0], (const char *)args[1], (bl_stat *)args[2], (int)args[3]);
}
if (number == SYS_readlinkat) {
return path_readlink((int)args[0], (const char *)args[1], (char *)args[2], (size_t)args[3]);
}
if (number == SYS_statx) {
return path_statx((int)args[0], (const char *)args[1], (int)args[2], (unsigned int)args[3], (struct statx *)args[4]);
}
if (number == SYS_execveat && execveat_is_execve(args)) {
return real_syscall(SYS_execve, args[1], args[2], args[3]);
}
+7 -1
View File
@@ -13,6 +13,7 @@
#include <unistd.h>
static int (*next_fstat)(int, struct stat *);
void bl_storage_owner(int fd, struct stat *st) __attribute__((visibility("hidden")));
static int (*next_fallocate)(int, int, off_t, off_t);
static int (*next_posix_fallocate)(int, off_t, off_t);
static ssize_t (*next_pwrite)(int, const void *, size_t, off_t);
@@ -285,12 +286,17 @@ int fstat(int fd, struct stat *out) {
if (next_fstat == NULL) { errno = ENOSYS; return -1; }
initialize();
errno = entry_errno;
if (!enabled) return next_fstat(fd, out);
if (!enabled) {
int result = next_fstat(fd, out);
if (result == 0) bl_storage_owner(fd, out);
return result;
}
uint64_t start = now_ns();
errno = entry_errno;
int result = next_fstat(fd, out);
int call_errno = errno;
uint64_t elapsed = now_ns() - start;
if (result == 0) bl_storage_owner(fd, out);
if (result == 0 && on_selected_device(fd, out)) {
add(&stats.fstat_calls, 1);
add(&stats.fstat_elapsed_ns, elapsed);
+978
View File
@@ -0,0 +1,978 @@
#define _GNU_SOURCE
#include <dlfcn.h>
#include <errno.h>
#include <poll.h>
#include <stddef.h>
#if defined(__aarch64__) || defined(BL_VDEC_ANY_ARCH)
#include <fcntl.h>
#include <linux/videodev2.h>
#include <pthread.h>
#include <stdarg.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/mman.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <time.h>
#include <unistd.h>
#include "../../../app/src/main/cpp/venc/venc_proto.h"
#define VDEC_DEVICE "/dev/video-dec0"
#define VDEC_INSTANCES 4
#define VDEC_BUFFERS 16
#define VDEC_BITSTREAM_SIZE (4u << 20)
#define VDEC_PADDING 64
#define VDEC_DUMB 64
struct vd_dma_heap_alloc {
uint64_t len;
uint32_t fd;
uint32_t fd_flags;
uint64_t heap_flags;
};
#define VD_DMA_HEAP_IOCTL_ALLOC _IOWR('H', 0x0, struct vd_dma_heap_alloc)
struct vd_dma_buf_sync {
uint64_t flags;
};
#define VD_DMA_BUF_SYNC_WRITE 2u
#define VD_DMA_BUF_SYNC_START 0u
#define VD_DMA_BUF_SYNC_END 4u
#define VD_DMA_BUF_IOCTL_SYNC _IOW('b', 0, struct vd_dma_buf_sync)
struct vd_create_dumb {
uint32_t height, width, bpp, flags, handle, pitch;
uint64_t size;
};
struct vd_destroy_dumb {
uint32_t handle;
};
struct vd_prime_handle {
uint32_t handle, flags;
int32_t fd;
};
#define VD_IOCTL_MODE_CREATE_DUMB _IOWR('d', 0xB2, struct vd_create_dumb)
#define VD_IOCTL_MODE_DESTROY_DUMB _IOWR('d', 0xB4, struct vd_destroy_dumb)
#define VD_IOCTL_PRIME_HANDLE_TO_FD _IOWR('d', 0x2d, struct vd_prime_handle)
struct vd_mode_info {
uint32_t clock;
uint16_t hdisplay, hsync_start, hsync_end, htotal, hskew;
uint16_t vdisplay, vsync_start, vsync_end, vtotal, vscan;
uint32_t vrefresh, flags, type;
char name[32];
};
struct vd_res {
int count_fbs;
uint32_t *fbs;
int count_crtcs;
uint32_t *crtcs;
int count_connectors;
uint32_t *connectors;
int count_encoders;
uint32_t *encoders;
uint32_t min_width, max_width, min_height, max_height;
};
struct vd_connector {
uint32_t connector_id, encoder_id, connector_type, connector_type_id;
int connection;
uint32_t mm_width, mm_height;
int subpixel;
int count_modes;
struct vd_mode_info *modes;
int count_props;
uint32_t *props;
uint64_t *prop_values;
int count_encoders;
uint32_t *encoders;
};
struct vd_encoder {
uint32_t encoder_id, encoder_type, crtc_id, possible_crtcs, possible_clones;
};
struct vd_crtc {
uint32_t crtc_id, buffer_id, x, y, width, height;
int mode_valid;
struct vd_mode_info mode;
int gamma_size;
};
struct vd_device {
char **nodes;
int available_nodes;
int bustype;
void *businfo;
void *deviceinfo;
};
struct vd_capture {
int fd;
ino_t ino;
uint8_t *map;
size_t len;
};
struct vd_done {
uint32_t index;
struct timeval timestamp;
};
struct vdec {
int used, fd;
uint32_t fourcc, width, height;
uint32_t cap_width, cap_height, bpl, cap_size;
uint8_t *bitstream;
uint32_t out_count;
uint32_t out_done[VDEC_BUFFERS], n_out_done;
struct vd_capture cap[VDEC_BUFFERS];
uint32_t cap_count;
uint32_t cap_queue[VDEC_BUFFERS], n_cap_queue;
struct vd_done cap_done[VDEC_BUFFERS];
uint32_t n_cap_done;
int out_on, cap_on;
int sock, hw, hw_failed;
int64_t pts;
void *ctx, *packet, *frame;
uint8_t *packet_data;
size_t packet_capacity;
int last;
uint32_t frames, slow;
double decode_ms;
};
static struct {
void *(*find_decoder_by_name)(const char *);
void *(*alloc_context3)(const void *);
int (*open2)(void *, const void *, void **);
void (*free_context)(void **);
int (*send_packet)(void *, const void *);
int (*receive_frame)(void *, void *);
void (*flush_buffers)(void *);
void *(*packet_alloc)(void);
void (*packet_free)(void **);
void *(*frame_alloc)(void);
void (*frame_free)(void **);
void (*frame_unref)(void *);
int (*dict_set)(void **, const char *, const char *, int);
void (*dict_free)(void **);
const char *(*pix_fmt_name)(int);
} av;
static pthread_mutex_t vd_lock = PTHREAD_MUTEX_INITIALIZER;
static struct vdec vd_all[VDEC_INSTANCES];
static int vd_open_count;
static int vd_state;
static int vd_ffmpeg;
static int vd_heap = -1;
static int vd_dumb_fd[VDEC_DUMB];
static char vd_drm_handle;
static void vd_log(const char *fmt, ...) __attribute__((format(printf, 1, 2)));
static void vd_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-vdec: ", 16) < 0 || write(2, line, n) < 0) return;
}
static int vd_load_ffmpeg(void) {
void *codec = dlopen("libavcodec.so.62", RTLD_LAZY | RTLD_LOCAL);
void *util = codec ? dlopen("libavutil.so.60", RTLD_LAZY | RTLD_LOCAL) : NULL;
if (codec == NULL || util == NULL) {
vd_log("FFmpeg 8 is not available (%s), Remote Play decoding stays off", dlerror());
return 0;
}
#define VD_SYM(lib, field, name) \
if ((*(void **)&av.field = dlsym(lib, name)) == NULL) { \
vd_log("FFmpeg has no %s, Remote Play decoding stays off", name); \
return 0; \
}
VD_SYM(codec, find_decoder_by_name, "avcodec_find_decoder_by_name")
VD_SYM(codec, alloc_context3, "avcodec_alloc_context3")
VD_SYM(codec, open2, "avcodec_open2")
VD_SYM(codec, free_context, "avcodec_free_context")
VD_SYM(codec, send_packet, "avcodec_send_packet")
VD_SYM(codec, receive_frame, "avcodec_receive_frame")
VD_SYM(codec, flush_buffers, "avcodec_flush_buffers")
VD_SYM(codec, packet_alloc, "av_packet_alloc")
VD_SYM(codec, packet_free, "av_packet_free")
VD_SYM(util, frame_alloc, "av_frame_alloc")
VD_SYM(util, frame_free, "av_frame_free")
VD_SYM(util, frame_unref, "av_frame_unref")
VD_SYM(util, dict_set, "av_dict_set")
VD_SYM(util, dict_free, "av_dict_free")
VD_SYM(util, pix_fmt_name, "av_get_pix_fmt_name")
#undef VD_SYM
return 1;
}
static int vd_have_ffmpeg(void) {
if (vd_ffmpeg == 0) vd_ffmpeg = vd_load_ffmpeg() ? 1 : -1;
return vd_ffmpeg > 0;
}
__attribute__((visibility("hidden"))) int bl_venc_connect(void);
static int vd_enabled(void) {
pthread_mutex_lock(&vd_lock);
if (vd_state == 0) {
const char *flag = getenv("BL_REMOTE_PLAY_DECODE"), *socket = getenv("BL_VENC_SOCKET");
vd_state = -1;
if (strcmp(program_invocation_short_name, "streaming_client") == 0 && (flag == NULL || strcmp(flag, "0") != 0)) {
vd_heap = open("/dev/dma_heap/system", O_RDONLY | O_CLOEXEC);
if (vd_heap < 0) vd_log("no /dev/dma_heap/system (%s), Remote Play decoding stays off", strerror(errno));
else if ((socket && *socket) || vd_have_ffmpeg()) vd_state = 1;
for (int i = 0; i < VDEC_DUMB; i++) vd_dumb_fd[i] = -1;
}
}
int on = vd_state > 0;
pthread_mutex_unlock(&vd_lock);
return on;
}
static struct vdec *vd_find(int fd) {
if (fd < 0 || __atomic_load_n(&vd_open_count, __ATOMIC_ACQUIRE) == 0) return NULL;
for (int i = 0; i < VDEC_INSTANCES; i++) if (vd_all[i].used && vd_all[i].fd == fd) return &vd_all[i];
return NULL;
}
__attribute__((visibility("hidden"))) int bl_vdec_open(const char *path, int flags) {
(void)flags;
if (path == NULL || strcmp(path, VDEC_DEVICE) != 0 || !vd_enabled()) return -2;
int fd = memfd_create("droiddeck-vdec", 0);
if (fd < 0) return -1;
pthread_mutex_lock(&vd_lock);
struct vdec *v = NULL;
for (int i = 0; i < VDEC_INSTANCES && v == NULL; i++) if (!vd_all[i].used) v = &vd_all[i];
if (v == NULL) {
pthread_mutex_unlock(&vd_lock);
close(fd);
errno = EBUSY;
return -1;
}
memset(v, 0, sizeof *v);
v->used = 1;
v->fd = fd;
v->fourcc = V4L2_PIX_FMT_H264;
v->last = -1;
v->sock = -1;
for (int i = 0; i < VDEC_BUFFERS; i++) v->cap[i].fd = -1;
__atomic_add_fetch(&vd_open_count, 1, __ATOMIC_RELEASE);
pthread_mutex_unlock(&vd_lock);
return fd;
}
static void vd_close_decoder(struct vdec *v) {
if (v->frames) {
vd_log("%u frames, %.1f ms each on average, %u over 25 ms", v->frames, v->decode_ms / v->frames, v->slow);
}
if (v->sock >= 0) close(v->sock);
v->sock = -1;
v->hw = 0;
if (v->ctx) av.free_context(&v->ctx);
if (v->packet) av.packet_free(&v->packet);
if (v->frame) av.frame_free(&v->frame);
free(v->packet_data);
v->packet_data = NULL;
v->packet_capacity = 0;
v->frames = v->slow = 0;
v->decode_ms = 0;
v->last = -1;
}
static int vd_send(int sock, const void *msg, size_t len, int fd) {
struct iovec iov = { .iov_base = (void *)msg, .iov_len = len };
char control[CMSG_SPACE(sizeof(int))];
struct msghdr m = { .msg_iov = &iov, .msg_iovlen = 1 };
if (fd >= 0) {
memset(control, 0, sizeof control);
m.msg_control = control;
m.msg_controllen = sizeof control;
struct cmsghdr *c = CMSG_FIRSTHDR(&m);
c->cmsg_level = SOL_SOCKET;
c->cmsg_type = SCM_RIGHTS;
c->cmsg_len = CMSG_LEN(sizeof(int));
memcpy(CMSG_DATA(c), &fd, sizeof fd);
}
return sendmsg(sock, &m, MSG_NOSIGNAL) == (ssize_t)len ? 0 : -1;
}
static void vd_send_capture(struct vdec *v, uint32_t index) {
struct vdec_capture c = { .type = VDEC_CAPTURE, .index = index, .size = (uint32_t)v->cap[index].len };
if (v->sock >= 0 && v->cap[index].map && vd_send(v->sock, &c, sizeof c, v->cap[index].fd) != 0)
vd_log("could not hand capture buffer %u to the app: %s", index, strerror(errno));
}
static int vd_open_hardware(struct vdec *v) {
if (v->hw_failed) return -1;
int sock = bl_venc_connect();
if (sock < 0) return -1;
struct vdec_config c = {
.type = VDEC_CONFIG, .codec = v->fourcc == V4L2_PIX_FMT_HEVC ? VENC_HEVC : VENC_H264,
.width = v->width ? v->width : v->cap_width, .height = v->height ? v->height : v->cap_height,
.stride = v->bpl, .rows = v->cap_height, .bitstreams = v->out_count, .bitstream_size = VDEC_BITSTREAM_SIZE,
};
struct vdec_result r;
if (vd_send(sock, &c, sizeof c, v->fd) != 0 || recv(sock, &r, sizeof r, 0) != (ssize_t)sizeof r ||
r.type != VDEC_RESULT || r.status != 0) {
vd_log("the app has no %s decoder for %ux%u", c.codec == VENC_HEVC ? "HEVC" : "H.264", c.width, c.height);
close(sock);
v->hw_failed = 1;
return -1;
}
v->sock = sock;
v->hw = 1;
for (uint32_t i = 0; i < v->cap_count; i++) vd_send_capture(v, i);
vd_log("decoding %s %ux%u with the app's MediaCodec into %ux%u NV12 dma-bufs",
c.codec == VENC_HEVC ? "HEVC" : "H.264", c.width, c.height, v->cap_width, v->cap_height);
return 0;
}
static int vd_open_decoder(struct vdec *v) {
if (vd_open_hardware(v) == 0) return 0;
if (!vd_have_ffmpeg()) return -1;
const char *name = v->fourcc == V4L2_PIX_FMT_HEVC ? "hevc" : "h264";
const void *codec = av.find_decoder_by_name(name);
if (codec == NULL) {
vd_log("FFmpeg has no %s decoder", name);
return -1;
}
v->ctx = av.alloc_context3(codec);
v->packet = av.packet_alloc();
v->frame = av.frame_alloc();
void *options = NULL;
long cores = sysconf(_SC_NPROCESSORS_ONLN);
char threads[8];
snprintf(threads, sizeof threads, "%ld", cores > 4 ? 4L : cores < 1 ? 1L : cores);
av.dict_set(&options, "threads", threads, 0);
av.dict_set(&options, "thread_type", "slice", 0);
av.dict_set(&options, "flags", "+low_delay", 0);
av.dict_set(&options, "flags2", "+fast", 0);
int r = v->ctx && v->packet && v->frame ? av.open2(v->ctx, codec, &options) : -1;
av.dict_free(&options);
if (r < 0) {
vd_log("could not open the %s decoder (%d)", name, r);
vd_close_decoder(v);
return -1;
}
vd_log("decoding %s %ux%u in software into %ux%u NV12 dma-bufs", v->fourcc == V4L2_PIX_FMT_HEVC ? "HEVC" : "H.264",
v->width, v->height, v->cap_width, v->cap_height);
return 0;
}
static void vd_unmap_capture(struct vdec *v) {
for (uint32_t i = 0; i < VDEC_BUFFERS; i++) {
if (v->cap[i].map) munmap(v->cap[i].map, v->cap[i].len);
v->cap[i] = (struct vd_capture){ .fd = -1 };
}
v->cap_count = v->n_cap_queue = v->n_cap_done = 0;
v->last = -1;
}
static void vd_sync(int fd, uint64_t flags) {
struct vd_dma_buf_sync s = { .flags = flags | VD_DMA_BUF_SYNC_WRITE };
ioctl(fd, VD_DMA_BUF_IOCTL_SYNC, &s);
}
static void vd_blank(struct vdec *v, struct vd_capture *c) {
size_t luma = (size_t)v->bpl * v->cap_height;
if (luma + luma / 2 > c->len) return;
vd_sync(c->fd, VD_DMA_BUF_SYNC_START);
memset(c->map, 16, luma);
memset(c->map + luma, 128, luma / 2);
vd_sync(c->fd, VD_DMA_BUF_SYNC_END);
}
static int vd_map_capture(struct vdec *v, uint32_t index, int fd) {
struct stat st;
if (fd < 0 || fstat(fd, &st) != 0) return -EINVAL;
struct vd_capture *c = &v->cap[index];
if (c->map && c->ino == st.st_ino) {
c->fd = fd;
return 0;
}
if (c->map) {
munmap(c->map, c->len);
*c = (struct vd_capture){ .fd = -1 };
if (v->last == (int)index) v->last = -1;
}
off_t len = lseek(fd, 0, SEEK_END);
if (len < (off_t)v->cap_size) return -EINVAL;
void *p = mmap(NULL, (size_t)len, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
if (p == MAP_FAILED) {
vd_log("could not map capture buffer %u: %s", index, strerror(errno));
*c = (struct vd_capture){ .fd = -1 };
return -EINVAL;
}
*c = (struct vd_capture){ .fd = fd, .ino = st.st_ino, .map = p, .len = (size_t)len };
vd_blank(v, c);
if (v->hw) vd_send_capture(v, index);
return 0;
}
static int vd_write_frame(struct vdec *v, struct vd_capture *c) {
uint8_t **data = (uint8_t **)v->frame;
int *linesize = (int *)((uint8_t *)v->frame + 64);
int width = *(int *)((uint8_t *)v->frame + 104), height = *(int *)((uint8_t *)v->frame + 108);
const char *format = av.pix_fmt_name(*(int *)((uint8_t *)v->frame + 116));
if (format == NULL || width <= 0 || height <= 0) return -1;
int nv12 = strcmp(format, "nv12") == 0;
if (!nv12 && strcmp(format, "yuv420p") != 0 && strcmp(format, "yuvj420p") != 0) {
static int warned;
if (!warned++) vd_log("cannot show %s frames", format);
return -1;
}
uint32_t w = (uint32_t)width < v->bpl ? (uint32_t)width : v->bpl;
uint32_t h = (uint32_t)height < v->cap_height ? (uint32_t)height : v->cap_height;
uint8_t *y = c->map, *uv = c->map + (size_t)v->bpl * v->cap_height;
vd_sync(c->fd, VD_DMA_BUF_SYNC_START);
for (uint32_t row = 0; row < h; row++) memcpy(y + (size_t)row * v->bpl, data[0] + (size_t)row * linesize[0], w);
for (uint32_t row = 0; row < (h + 1) / 2; row++) {
uint8_t *dst = uv + (size_t)row * v->bpl;
if (nv12) {
memcpy(dst, data[1] + (size_t)row * linesize[1], w & ~1u);
continue;
}
const uint8_t *u = data[1] + (size_t)row * linesize[1], *vv = data[2] + (size_t)row * linesize[2];
for (uint32_t x = 0; x < w / 2; x++) {
dst[2 * x] = u[x];
dst[2 * x + 1] = vv[x];
}
}
vd_sync(c->fd, VD_DMA_BUF_SYNC_END);
return 0;
}
static void vd_copy_last(struct vdec *v, struct vd_capture *c) {
if (v->last < 0 || v->cap[v->last].map == NULL || &v->cap[v->last] == c) return;
size_t size = v->cap_size < c->len ? v->cap_size : c->len;
vd_sync(c->fd, VD_DMA_BUF_SYNC_START);
memcpy(c->map, v->cap[v->last].map, size);
vd_sync(c->fd, VD_DMA_BUF_SYNC_END);
}
static double vd_now_ms(void) {
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
return ts.tv_sec * 1000.0 + ts.tv_nsec / 1e6;
}
static void vd_deliver(struct vdec *v, int written, double start, struct timeval timestamp) {
uint32_t target = v->cap_queue[0];
if (!written) {
if (v->last < 0) return;
vd_copy_last(v, &v->cap[target]);
}
double ms = vd_now_ms() - start;
v->frames++;
v->decode_ms += ms;
if (ms > 25.0) v->slow++;
memmove(v->cap_queue, v->cap_queue + 1, --v->n_cap_queue * sizeof v->cap_queue[0]);
v->cap_done[v->n_cap_done++] = (struct vd_done){ .index = target, .timestamp = timestamp };
v->last = (int)target;
}
static void vd_decode_hardware(struct vdec *v, uint32_t index, uint32_t bytes, struct timeval timestamp) {
double start = vd_now_ms();
v->pts += 16667;
struct vdec_packet p = { .type = VDEC_PACKET, .input = index, .bytes = bytes, .capture = v->cap_queue[0], .pts_us = v->pts };
struct vdec_result r;
if (vd_send(v->sock, &p, sizeof p, -1) != 0 || recv(v->sock, &r, sizeof r, 0) != (ssize_t)sizeof r ||
r.type != VDEC_RESULT) {
vd_log("lost the app's decoder (%s), switching to software", strerror(errno));
vd_close_decoder(v);
v->hw_failed = 1;
return;
}
vd_deliver(v, r.status == 0 && r.frame, start, timestamp);
}
static void vd_decode(struct vdec *v, uint32_t index, uint32_t bytes, struct timeval timestamp) {
if (!v->cap_on || v->n_cap_queue == 0) return;
if (v->ctx == NULL && !v->hw && vd_open_decoder(v) != 0) return;
if (v->hw) {
vd_decode_hardware(v, index, bytes, timestamp);
return;
}
if (v->packet_capacity < bytes + VDEC_PADDING) {
free(v->packet_data);
v->packet_capacity = bytes + VDEC_PADDING + (64u << 10);
v->packet_data = malloc(v->packet_capacity);
if (v->packet_data == NULL) {
v->packet_capacity = 0;
return;
}
}
memcpy(v->packet_data, v->bitstream + (size_t)index * VDEC_BITSTREAM_SIZE, bytes);
memset(v->packet_data + bytes, 0, VDEC_PADDING);
*(uint8_t **)((uint8_t *)v->packet + 24) = v->packet_data;
*(int *)((uint8_t *)v->packet + 32) = (int)bytes;
double start = vd_now_ms();
uint32_t target = v->cap_queue[0];
struct vd_capture *c = &v->cap[target];
int written = 0;
if (av.send_packet(v->ctx, v->packet) >= 0) {
while (av.receive_frame(v->ctx, v->frame) >= 0) {
if (vd_write_frame(v, c) == 0) written = 1;
av.frame_unref(v->frame);
}
}
*(uint8_t **)((uint8_t *)v->packet + 24) = NULL;
*(int *)((uint8_t *)v->packet + 32) = 0;
vd_deliver(v, written, start, timestamp);
}
static int is_output(uint32_t type) { return type == V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE || type == V4L2_BUF_TYPE_VIDEO_OUTPUT; }
static int is_capture(uint32_t type) { return type == V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE || type == V4L2_BUF_TYPE_VIDEO_CAPTURE; }
static void vd_fill_format(struct vdec *v, struct v4l2_format *f) {
struct v4l2_pix_format_mplane *p = &f->fmt.pix_mp;
memset(p, 0, sizeof *p);
p->field = V4L2_FIELD_NONE;
p->num_planes = 1;
p->colorspace = V4L2_COLORSPACE_REC709;
if (is_output(f->type)) {
p->width = v->width;
p->height = v->height;
p->pixelformat = v->fourcc;
p->plane_fmt[0].sizeimage = VDEC_BITSTREAM_SIZE;
} else {
p->width = v->cap_width;
p->height = v->cap_height;
p->pixelformat = V4L2_PIX_FMT_NV12;
p->plane_fmt[0].bytesperline = v->bpl;
p->plane_fmt[0].sizeimage = v->cap_size;
}
}
static int vd_set_format(struct vdec *v, struct v4l2_format *f, int apply) {
struct v4l2_pix_format_mplane *p = &f->fmt.pix_mp;
if (f->type != V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE && f->type != V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE) return -EINVAL;
struct vdec t = *v;
if (is_output(f->type)) {
if (p->pixelformat != V4L2_PIX_FMT_H264 && p->pixelformat != V4L2_PIX_FMT_HEVC) return -EINVAL;
t.fourcc = p->pixelformat;
t.width = p->width;
t.height = p->height;
} else {
uint32_t w = p->width > t.width ? p->width : t.width, h = p->height > t.height ? p->height : t.height;
if (w < 16 || h < 16 || w > 8192 || h > 8192) return -EINVAL;
t.cap_width = (w + 15) & ~15u;
t.cap_height = (h + 15) & ~15u;
t.bpl = t.cap_width;
t.cap_size = t.bpl * t.cap_height * 3 / 2;
}
if (apply) {
if (t.fourcc != v->fourcc || (t.hw && (t.bpl != v->bpl || t.cap_height != v->cap_height))) vd_close_decoder(&t);
*v = t;
}
vd_fill_format(&t, f);
return 0;
}
static int vd_reqbufs(struct vdec *v, struct v4l2_requestbuffers *r) {
uint32_t n = r->count > VDEC_BUFFERS ? VDEC_BUFFERS : r->count;
if (r->type == V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE && r->memory == V4L2_MEMORY_MMAP) {
if (v->bitstream) munmap(v->bitstream, (size_t)v->out_count * VDEC_BITSTREAM_SIZE);
v->bitstream = NULL;
v->out_count = v->n_out_done = 0;
if (n && ftruncate(v->fd, (off_t)n * VDEC_BITSTREAM_SIZE) != 0) return -ENOMEM;
if (n) {
void *p = mmap(NULL, (size_t)n * VDEC_BITSTREAM_SIZE, PROT_READ, MAP_SHARED, v->fd, 0);
if (p == MAP_FAILED) return -ENOMEM;
v->bitstream = p;
}
v->out_count = n;
} else if (r->type == V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE && r->memory == V4L2_MEMORY_DMABUF) {
if (v->hw) vd_close_decoder(v);
vd_unmap_capture(v);
v->cap_count = n;
} else {
return -EINVAL;
}
r->count = n;
r->capabilities = r->memory == V4L2_MEMORY_MMAP ? V4L2_BUF_CAP_SUPPORTS_MMAP : V4L2_BUF_CAP_SUPPORTS_DMABUF;
return 0;
}
static int vd_querybuf(struct vdec *v, struct v4l2_buffer *b) {
if (b->type != V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE || b->index >= v->out_count || b->m.planes == NULL || b->length < 1)
return -EINVAL;
b->memory = V4L2_MEMORY_MMAP;
b->flags = V4L2_BUF_FLAG_MAPPED;
b->length = 1;
b->m.planes[0].length = VDEC_BITSTREAM_SIZE;
b->m.planes[0].m.mem_offset = b->index * VDEC_BITSTREAM_SIZE;
return 0;
}
static int vd_qbuf(struct vdec *v, struct v4l2_buffer *b) {
if (b->m.planes == NULL || b->length < 1) return -EINVAL;
if (b->type == V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE) {
if (b->index >= v->out_count || v->n_out_done >= VDEC_BUFFERS) return -EINVAL;
uint32_t bytes = b->m.planes[0].bytesused;
if (bytes > VDEC_BITSTREAM_SIZE) bytes = VDEC_BITSTREAM_SIZE;
if (v->out_on && bytes) vd_decode(v, b->index, bytes, b->timestamp);
v->out_done[v->n_out_done++] = b->index;
} else if (b->type == V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE) {
if (b->index >= v->cap_count || v->cap_size == 0) return -EINVAL;
int r = vd_map_capture(v, b->index, b->m.planes[0].m.fd);
if (r < 0) return r;
for (uint32_t i = 0; i < v->n_cap_queue; i++) if (v->cap_queue[i] == b->index) return 0;
if (v->n_cap_queue >= VDEC_BUFFERS) return -EINVAL;
v->cap_queue[v->n_cap_queue++] = b->index;
} else {
return -EINVAL;
}
b->flags |= V4L2_BUF_FLAG_QUEUED;
return 0;
}
static int vd_dqbuf(struct vdec *v, struct v4l2_buffer *b) {
if (b->m.planes == NULL || b->length < 1) return -EINVAL;
if (b->type == V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE) {
if (v->n_out_done == 0) return -EAGAIN;
b->index = v->out_done[0];
memmove(v->out_done, v->out_done + 1, --v->n_out_done * sizeof v->out_done[0]);
b->memory = V4L2_MEMORY_MMAP;
b->flags = V4L2_BUF_FLAG_DONE | V4L2_BUF_FLAG_MAPPED;
b->length = 1;
b->m.planes[0].bytesused = 0;
b->m.planes[0].length = VDEC_BITSTREAM_SIZE;
b->m.planes[0].m.mem_offset = b->index * VDEC_BITSTREAM_SIZE;
return 0;
}
if (b->type != V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE) return -EINVAL;
if (v->n_cap_done == 0) return -EAGAIN;
struct vd_done d = v->cap_done[0];
memmove(v->cap_done, v->cap_done + 1, --v->n_cap_done * sizeof d);
b->index = d.index;
b->memory = V4L2_MEMORY_DMABUF;
b->flags = V4L2_BUF_FLAG_DONE | V4L2_BUF_FLAG_TIMESTAMP_COPY;
b->field = V4L2_FIELD_NONE;
b->timestamp = d.timestamp;
b->length = 1;
b->m.planes[0].bytesused = v->cap_size;
b->m.planes[0].length = v->cap_size;
b->m.planes[0].m.fd = v->cap[d.index].fd;
return 0;
}
static int vd_ioctl(struct vdec *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_vdec");
strcpy((char *)c->card, "DroidDeck video decoder");
strcpy((char *)c->bus_info, "platform:droiddeck-vdec");
c->version = 0x00060000;
c->device_caps = V4L2_CAP_VIDEO_M2M_MPLANE | 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_capture(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_output(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_G_FMT: {
struct v4l2_format *f = arg;
if (!is_output(f->type) && !is_capture(f->type)) return -EINVAL;
vd_fill_format(v, f);
return 0;
}
case VIDIOC_S_FMT: return vd_set_format(v, arg, 1);
case VIDIOC_TRY_FMT: return vd_set_format(v, arg, 0);
case VIDIOC_REQBUFS: return vd_reqbufs(v, arg);
case VIDIOC_QUERYBUF: return vd_querybuf(v, arg);
case VIDIOC_QBUF: return vd_qbuf(v, arg);
case VIDIOC_DQBUF: return vd_dqbuf(v, arg);
case VIDIOC_STREAMON:
case VIDIOC_STREAMOFF: {
uint32_t type = *(uint32_t *)arg;
int on = req == VIDIOC_STREAMON;
if (is_output(type)) {
v->out_on = on;
if (!on) {
v->n_out_done = 0;
if (v->ctx) av.flush_buffers(v->ctx);
}
} else if (is_capture(type)) {
v->cap_on = on;
if (!on) v->n_cap_queue = v->n_cap_done = 0;
} else {
return -EINVAL;
}
if (v->out_on && v->cap_on && v->ctx == NULL && !v->hw && v->out_count && v->cap_size) vd_open_decoder(v);
return 0;
}
case VIDIOC_SUBSCRIBE_EVENT:
case VIDIOC_UNSUBSCRIBE_EVENT:
case VIDIOC_DECODER_CMD:
case VIDIOC_TRY_DECODER_CMD:
return 0;
case VIDIOC_DQEVENT:
return -ENOENT;
default:
vd_log("unhandled ioctl 0x%lx", req);
return -ENOTTY;
}
}
__attribute__((visibility("hidden"))) int bl_vdec_ioctl(int fd, unsigned long req, void *arg, int *rc) {
struct vdec *v = vd_find(fd);
if (v == NULL) return 0;
pthread_mutex_lock(&vd_lock);
int r = arg ? vd_ioctl(v, req, arg) : -EFAULT;
pthread_mutex_unlock(&vd_lock);
if (r < 0) {
errno = -r;
*rc = -1;
} else {
*rc = 0;
}
return 1;
}
__attribute__((visibility("hidden"))) void bl_vdec_closed(int fd) {
struct vdec *v = vd_find(fd);
if (v == NULL) return;
pthread_mutex_lock(&vd_lock);
vd_close_decoder(v);
vd_unmap_capture(v);
if (v->bitstream) munmap(v->bitstream, (size_t)v->out_count * VDEC_BITSTREAM_SIZE);
v->bitstream = NULL;
v->used = 0;
__atomic_sub_fetch(&vd_open_count, 1, __ATOMIC_RELEASE);
pthread_mutex_unlock(&vd_lock);
}
__attribute__((visibility("hidden"))) int bl_vdec_poll(struct pollfd *fds, nfds_t n, int timeout_ms,
int (*real)(struct pollfd *, nfds_t, int), int *ret) {
if (n != 1 || vd_find(fds[0].fd) == NULL) return 0;
struct vdec *v = vd_find(fds[0].fd);
pthread_mutex_lock(&vd_lock);
short ready = (v->n_cap_done ? POLLIN | POLLRDNORM : 0) | (v->n_out_done ? POLLOUT | POLLWRNORM : 0);
pthread_mutex_unlock(&vd_lock);
fds[0].revents = ready & fds[0].events;
if (fds[0].revents == 0 && timeout_ms != 0) real(NULL, 0, timeout_ms < 0 || timeout_ms > 1000 ? 1000 : timeout_ms);
*ret = fds[0].revents ? 1 : 0;
return 1;
}
static int drm_get_devices2(uint32_t flags, struct vd_device **devices, int max) {
(void)flags;
static char *nodes[3] = { "/dev/null", NULL, NULL };
static struct vd_device device = { .nodes = nodes, .available_nodes = 1 };
if (devices == NULL || max < 1) return 1;
devices[0] = &device;
return 1;
}
static void drm_free_devices(struct vd_device **devices, int count) { (void)devices; (void)count; }
static struct vd_mode_info drm_mode = {
.clock = 148500, .hdisplay = 1920, .hsync_start = 2008, .hsync_end = 2052, .htotal = 2200,
.vdisplay = 1080, .vsync_start = 1084, .vsync_end = 1089, .vtotal = 1125, .vrefresh = 60, .name = "1920x1080",
};
static uint32_t drm_crtc_ids[1] = { 1 }, drm_connector_ids[1] = { 2 }, drm_encoder_ids[1] = { 3 };
static struct vd_res *drm_get_resources(int fd) {
(void)fd;
static struct vd_res res = {
.count_crtcs = 1, .crtcs = drm_crtc_ids, .count_connectors = 1, .connectors = drm_connector_ids,
.count_encoders = 1, .encoders = drm_encoder_ids, .max_width = 8192, .max_height = 8192,
};
return &res;
}
static struct vd_connector *drm_get_connector(int fd, uint32_t id) {
(void)fd;
static struct vd_connector connector = {
.connector_id = 2, .encoder_id = 3, .connector_type = 14, .connection = 1, .count_modes = 1,
.modes = &drm_mode, .count_encoders = 1, .encoders = drm_encoder_ids,
};
return id == 2 ? &connector : NULL;
}
static struct vd_encoder *drm_get_encoder(int fd, uint32_t id) {
(void)fd;
static struct vd_encoder encoder = { .encoder_id = 3, .encoder_type = 8, .crtc_id = 1, .possible_crtcs = 1 };
return id == 3 ? &encoder : NULL;
}
static struct vd_crtc *drm_get_crtc(int fd, uint32_t id) {
(void)fd;
static struct vd_crtc crtc;
if (id != 1) return NULL;
crtc = (struct vd_crtc){ .crtc_id = 1, .width = 1920, .height = 1080, .mode_valid = 1, .mode = drm_mode };
return &crtc;
}
static void drm_free(void *p) { (void)p; }
static void *drm_null(void) { return NULL; }
static int drm_fail(void) { return -EINVAL; }
static int drm_dumb_slot(uint32_t handle) { return handle >= 1 && handle <= VDEC_DUMB ? (int)handle - 1 : -1; }
static int drm_ioctl(int fd, unsigned long request, void *arg) {
(void)fd;
int r = -EINVAL;
pthread_mutex_lock(&vd_lock);
if (request == VD_IOCTL_MODE_CREATE_DUMB && arg) {
struct vd_create_dumb *c = arg;
uint64_t pitch = ((uint64_t)c->width * c->bpp + 7) / 8;
uint64_t size = (pitch * c->height + 4095) & ~4095ull;
int slot = -1;
for (int i = 0; i < VDEC_DUMB && slot < 0; i++) if (vd_dumb_fd[i] < 0) slot = i;
struct vd_dma_heap_alloc a = { .len = size, .fd_flags = O_RDWR | O_CLOEXEC };
if (slot < 0 || size == 0 || size > (512ull << 20)) {
r = -ENOMEM;
} else if (ioctl(vd_heap, VD_DMA_HEAP_IOCTL_ALLOC, &a) != 0) {
r = -errno;
vd_log("dma-heap allocation of %llu bytes failed: %s", (unsigned long long)size, strerror(errno));
} else {
vd_dumb_fd[slot] = (int)a.fd;
c->handle = (uint32_t)slot + 1;
c->pitch = (uint32_t)pitch;
c->size = size;
r = 0;
}
} else if (request == VD_IOCTL_PRIME_HANDLE_TO_FD && arg) {
struct vd_prime_handle *h = arg;
int slot = drm_dumb_slot(h->handle);
int dup_fd = slot >= 0 && vd_dumb_fd[slot] >= 0 ? fcntl(vd_dumb_fd[slot], F_DUPFD_CLOEXEC, 0) : -1;
if (dup_fd >= 0) {
h->fd = dup_fd;
r = 0;
} else {
r = slot >= 0 ? -errno : -ENOENT;
}
} else if (request == VD_IOCTL_MODE_DESTROY_DUMB && arg) {
int slot = drm_dumb_slot(((struct vd_destroy_dumb *)arg)->handle);
if (slot >= 0 && vd_dumb_fd[slot] >= 0) {
close(vd_dumb_fd[slot]);
vd_dumb_fd[slot] = -1;
r = 0;
} else {
r = -ENOENT;
}
}
pthread_mutex_unlock(&vd_lock);
if (r < 0) {
errno = -r;
return -1;
}
return 0;
}
static const struct {
const char *name;
void *fn;
} drm_table[] = {
{ "drmGetDevices2", (void *)drm_get_devices2 },
{ "drmFreeDevices", (void *)drm_free_devices },
{ "drmSetMaster", (void *)drm_fail },
{ "drmSetClientCap", (void *)drm_fail },
{ "drmModeGetResources", (void *)drm_get_resources },
{ "drmModeFreeResources", (void *)drm_free },
{ "drmModeGetConnector", (void *)drm_get_connector },
{ "drmModeFreeConnector", (void *)drm_free },
{ "drmModeGetEncoder", (void *)drm_get_encoder },
{ "drmModeFreeEncoder", (void *)drm_free },
{ "drmModeGetCrtc", (void *)drm_get_crtc },
{ "drmModeSetCrtc", (void *)drm_fail },
{ "drmModeFreeCrtc", (void *)drm_free },
{ "drmModeGetPlaneResources", (void *)drm_null },
{ "drmModeFreePlaneResources", (void *)drm_free },
{ "drmModeGetPlane", (void *)drm_null },
{ "drmModeFreePlane", (void *)drm_free },
{ "drmModeObjectGetProperties", (void *)drm_null },
{ "drmModeFreeObjectProperties", (void *)drm_free },
{ "drmModeGetProperty", (void *)drm_null },
{ "drmModeFreeProperty", (void *)drm_free },
{ "drmModeAddFB2", (void *)drm_fail },
{ "drmModeAddFB2WithModifiers", (void *)drm_fail },
{ "drmModeRmFB", (void *)drm_fail },
{ "drmModeAtomicAlloc", (void *)drm_null },
{ "drmModeAtomicFree", (void *)drm_free },
{ "drmModeAtomicAddProperty", (void *)drm_fail },
{ "drmModeAtomicCommit", (void *)drm_fail },
{ "drmIoctl", (void *)drm_ioctl },
};
void *SDL_LoadObject(const char *name) {
static void *(*real)(const char *);
if (name && strcmp(name, "libdrm.so.2") == 0 && vd_enabled()) return &vd_drm_handle;
if (!real) real = (void *(*)(const char *))dlsym(RTLD_NEXT, "SDL_LoadObject");
return real ? real(name) : NULL;
}
void *SDL_LoadFunction(void *handle, const char *name) {
static void *(*real)(void *, const char *);
if (handle == &vd_drm_handle) {
for (size_t i = 0; name && i < sizeof drm_table / sizeof drm_table[0]; i++)
if (strcmp(drm_table[i].name, name) == 0) return drm_table[i].fn;
return NULL;
}
if (!real) real = (void *(*)(void *, const char *))dlsym(RTLD_NEXT, "SDL_LoadFunction");
return real ? real(handle, name) : NULL;
}
void SDL_UnloadObject(void *handle) {
static void (*real)(void *);
if (handle == &vd_drm_handle) return;
if (!real) real = (void (*)(void *))dlsym(RTLD_NEXT, "SDL_UnloadObject");
if (real) real(handle);
}
#else
__attribute__((visibility("hidden"))) int bl_vdec_open(const char *path, int flags) {
(void)path;
(void)flags;
return -2;
}
__attribute__((visibility("hidden"))) int bl_vdec_ioctl(int fd, unsigned long req, void *arg, int *rc) {
(void)fd;
(void)req;
(void)arg;
(void)rc;
return 0;
}
__attribute__((visibility("hidden"))) void bl_vdec_closed(int fd) { (void)fd; }
__attribute__((visibility("hidden"))) int bl_vdec_poll(struct pollfd *fds, nfds_t n, int timeout_ms,
int (*real)(struct pollfd *, nfds_t, int), int *ret) {
(void)fds;
(void)n;
(void)timeout_ms;
(void)real;
(void)ret;
return 0;
}
#endif
+5
View File
@@ -625,9 +625,14 @@ static int vn_poll(struct pollfd *fds, nfds_t n, int timeout_ms, int (*real)(str
return r + ready;
}
__attribute__((weak, visibility("hidden"))) int bl_vdec_poll(struct pollfd *fds, nfds_t n, int timeout_ms,
int (*real)(struct pollfd *, nfds_t, int), int *ret);
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");
int ret;
if (bl_vdec_poll && bl_vdec_poll(fds, n, timeout_ms, real, &ret)) return ret;
if (__atomic_load_n(&vn_open_count, __ATOMIC_ACQUIRE) == 0) return real(fds, n, timeout_ms);
return vn_poll(fds, n, timeout_ms, real);
}
+24 -1
View File
@@ -1,6 +1,7 @@
#define _GNU_SOURCE
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#ifndef WEBHELPER_DEFAULT
#define WEBHELPER_DEFAULT "--no-zygote --in-process-gpu -AudioServiceOutOfProcess"
@@ -25,8 +26,30 @@ static char *join_features(const char *have, const char *add) {
return strcat(out, add);
}
static char *const *chromium_argv(const char *path, char *const argv[]) {
const char *slash = path ? strrchr(path, '/') : NULL;
if (!slash || !argv || !argv[0]) return argv;
int argc = 0;
for (; argv[argc]; argc++)
if (argc && (!strncmp(argv[argc], "--type=", 7) || !strcmp(argv[argc], "--no-sandbox"))) return argv;
size_t dir = (size_t)(slash - path) + 1;
char *sandbox = malloc(dir + sizeof "chrome-sandbox");
if (!sandbox) return argv;
memcpy(sandbox, path, dir);
strcpy(sandbox + dir, "chrome-sandbox");
int chromium = access(sandbox, F_OK) == 0;
free(sandbox);
if (!chromium) return argv;
char **out = calloc((size_t)argc + 2, sizeof *out);
if (!out) return argv;
out[0] = argv[0];
out[1] = (char *)"--no-sandbox";
for (int i = 1; i < argc; i++) out[i + 1] = argv[i];
return out;
}
__attribute__((visibility("hidden"))) char *const *bl_webhelper_argv(const char *path, char *const argv[]) {
if (!is_webhelper_browser(path, argv)) return argv;
if (!is_webhelper_browser(path, argv)) return chromium_argv(path, argv);
const char *spec = getenv("BL_WEBHELPER_ARGS");
if (!spec || !*spec) spec = WEBHELPER_DEFAULT;
if (!strcmp(spec, "stock")) return argv;