From 707b44d56de676290fc23de75a893378a348b51e Mon Sep 17 00:00:00 2001 From: pdev <300827144+pdev-labs@users.noreply.github.com> Date: Sun, 29 Nov 2026 22:51:51 +0530 Subject: [PATCH 01/10] web: share the desktop with a browser on the LAN Add `lfa web start|status|stop|doctor`. The share captures display :1, encodes H.264 with h264_mediacodec when available, and streams Annex-B NAL units over an authenticated WebSocket. The browser decodes them with WebCodecs and sends pointer and keyboard events back over the same socket, which the server injects with XTEST. One 8-character passcode from /dev/urandom protects the page. It stays in memory and is compared with hmac.compare_digest. The server binds to the Wi-Fi address, serves a self-signed HTTPS page by default, and limits failed logins. `--transport webrtc` keeps a go2rtc path for hosts where pion can enumerate interfaces; Android 16 denies the netlink query, so WebCodecs is the default. The share stops from `lfa web stop`, `lfa stop`, stop-linux, and uninstall. Also run the generated pd_login sessions in a subshell so `nohup` no longer fails on a shell function. --- CHANGELOG.md | 12 + README.md | 81 +++- SECURITY.md | 15 +- docs/ARCHITECTURE.md | 61 +++ docs/DECISIONS.md | 27 ++ docs/TROUBLESHOOTING.md | 60 +++ install_linux.sh | 47 +- lib/lfa-web.sh | 945 ++++++++++++++++++++++++++++++++++++++++ tests/test-all.sh | 164 +++++++ web/app.js | 373 ++++++++++++++++ web/login.html | 26 ++ web/login.js | 5 + web/player.html | 40 ++ web/server.py | 752 ++++++++++++++++++++++++++++++++ web/style.css | 154 +++++++ 15 files changed, 2748 insertions(+), 14 deletions(-) create mode 100644 lib/lfa-web.sh create mode 100644 web/app.js create mode 100644 web/login.html create mode 100644 web/login.js create mode 100644 web/player.html create mode 100644 web/server.py create mode 100644 web/style.css diff --git a/CHANGELOG.md b/CHANGELOG.md index 540c3db..4f537d5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,6 +15,18 @@ tag names, define the order. See the table at the bottom. ### Added +- Browser access to the desktop. `lfa web start` shares display `:1` with + another device on the local network, with `status`, `stop`, and `doctor` + alongside it. The command prints one 8-character passcode made of letters + and digits; every viewer who enters it gets mouse and keyboard control until + the share stops. `--view-only`, `--size`, `--fps`, `--encoder`, `--http`, + `--detach`, and `--transport` adjust the share. The default transport sends + H.264 over a WebSocket and decodes it with WebCodecs in the browser, which + works on Android. `--transport webrtc` uses go2rtc v1.9.15, downloaded on + first use after a SHA-256 check. Video uses `h264_mediacodec` when ffmpeg + supports it and falls back to `libx264 -preset ultrafast -tune zerolatency`. + The passcode stays in memory, and the only LAN listener is the Python + server, which serves a self-signed HTTPS page by default. - Separate Android and external storage policies. Guided setup now offers Both, Android only, External only, or None instead of one storage switch. `lfa install` accepts `--android-storage on|off` and diff --git a/README.md b/README.md index f6678b1..51e208d 100644 --- a/README.md +++ b/README.md @@ -133,7 +133,7 @@ hardware, not simulated. Full details, root causes, and evidence are in | Alpine 3.18 (Android 5) | Yes | Yes | legacy VNC desktop, panel works; X11 and Both hidden | v1.7.1 | | Ubuntu GNOME 46 (experimental) | Yes | Yes | shell and apps run; session services missing | v1.7.0 | -> The test suite runs `965` checks with 0 failures. The same suite runs on the +> The test suite runs `1022` checks with 0 failures. The same suite runs on the > devices (`tests/device-matrix.sh`). The table is as of v1.7.1. Ubuntu was > re-verified on v1.7.1, and Alpine 3.18 was re-verified on Android 5 on > 2026-11-04; the other rows were last verified on v1.7.0. A row is @@ -481,14 +481,15 @@ is accepted. | `lfa appimage` (`app`, `ai`) | extract an AppImage once and add a menu entry | | `lfa run` | run an AppImage once without installing it | | `lfa storage` | Android storage status, repair, run, protected data helpers, and separate Android/external access toggles | +| `lfa web` | share the running desktop with a browser on the local network; `start`, `status`, `stop`, `doctor` | | `lfa diagnostics` (`diag`) | write a redacted support bundle | | `lfa notice` | `on`, `off`, or `status` for the `start-linux` change notice | | `lfa version` (`ver`) / `lfa help` | version and command list | | `lfa check-update` | ask GitHub for a newer manager release; prints it and posts an Android notification through Termux:API | Short commands exist only where they cannot be confused with another one: -`status`, `stop`, `usb`, `storage`, and `android` stay spelled out. The long -forms always work. +`status`, `stop`, `usb`, `storage`, `web`, and `android` stay spelled out. The +long forms always work. Examples: @@ -510,6 +511,8 @@ lfa usb exec 001/002 -- lfa-usb desc lfa appimage add ~/Foo.AppImage lfa appimage run Foo lfa storage status +lfa web start -i ubuntu +lfa web status -i ubuntu lfa notice off ``` @@ -677,6 +680,76 @@ only the binds you kept: Android shared storage at `/sdcard` and disabled category is not reachable through `/storage`. Disabling both also hides the other Android and Termux host paths that `--isolated` skips. +### Web desktop in a browser + +`lfa web` shares the running desktop with another device on the same Wi-Fi. +The viewer opens a URL in a browser, types the passcode printed on the phone, +and gets the desktop with mouse and keyboard control. + +```bash +lfa web start -i ubuntu +lfa web status -i ubuntu +lfa web stop -i ubuntu +``` + +`start` prints the URL and one 8-character passcode: + +```text +URL: https://192.168.1.42:8765 +Passcode: K7M2Q9XA +``` + +The code uses uppercase letters and digits, with 0/O and 1/I left out so it is +easier to read from a screen. It is generated per run, kept in memory, and +never written to the log, the state file, or the diagnostics bundle. Every +viewer that enters it gets full control until the share stops. Use +`--view-only` to send video without input. + +The default transport sends H.264 over a WebSocket and the browser decodes it +with WebCodecs. This works on Android, where WebRTC's network discovery is +blocked by the platform. `--transport webrtc` uses go2rtc for a WebRTC stream +on devices where that path is available. + +```bash +lfa web start -i ubuntu --size 1920x1080 --fps 30 +lfa web start -i ubuntu --encoder x264 +lfa web start -i ubuntu --view-only --http +lfa web start -i ubuntu --detach +lfa web start -i ubuntu --transport webrtc +``` + +`--encoder auto` (the default) picks `h264_mediacodec` when ffmpeg reports it +and falls back to `libx264 -preset ultrafast -tune zerolatency`. The default +captures the whole display at 30 fps and about 4 Mbps. `--size WxH` scales the +capture to that output size, which is useful on a large desktop. The phone's +hardware encoder keeps CPU use low, and the browser decodes H.264 with its own +hardware path when it has one. + +WebCodecs needs Chrome 94+, Edge 94+, or Safari 16.4+. Firefox support depends +on the build. The viewer page says so when the browser lacks the API. + +`lfa web doctor` checks ffmpeg's X11 capture input (`x11grab` or `xcbgrab`) +and H.264 encoders, the Python `websockets` and `python-xlib` modules, the +display, and the LAN address. It also reports go2rtc, which only the optional +WebRTC transport uses. + +The server binds to the Wi-Fi IPv4 address, not to cellular or to every +interface. The passcode page runs over HTTPS with a self-signed certificate; +the browser shows a warning once. `--http` skips TLS when the network is +trusted. Five failed passcodes per minute per address are refused, and the +comparison uses `hmac.compare_digest`. The video WebSocket uses the same +session cookie as the page. In the WebRTC transport, go2rtc listens on +`127.0.0.1` only and the Python server proxies the WebRTC handshake. + +`Ctrl-C`, `lfa web stop`, and `lfa stop` stop ffmpeg, go2rtc when it is in use, +and the server. A stale PID is never signalled unless its command line still +matches the server. + +The share is for the local network and does not open a port on the internet. +If the browser connects but video stays black, check that the Wi-Fi access +point allows client-to-client traffic; guest networks often block it. Try +`--encoder x264` if the phone's hardware encoder fails on a large display. + ### Android/data and Android/obb Android 11 and later block `/storage/emulated/0/Android/data` and @@ -1652,7 +1725,7 @@ plus `script` from util-linux for the pty test, which is skipped if absent: ```bash chmod +x tests/test-all.sh -./tests/test-all.sh # expect: PASS=965 FAIL=0 +./tests/test-all.sh # expect: PASS=1022 FAIL=0 ``` The suite is deliberately stubbed. It cannot prove a desktop actually appears. diff --git a/SECURITY.md b/SECURITY.md index 2a737e1..4e557b0 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -45,8 +45,10 @@ In scope: - command injection or path traversal through installer inputs (distro name, instance name, hostname, username, timezone) -- secret leakage: install passwords, the VNC password, or the sudo shim secret - ending up readable outside the intended mode-`0600` file +- secret leakage: install passwords, the VNC password, the `lfa web` + passcode, or the sudo shim secret ending up readable outside the intended + mode-`0600` file +- authentication bypass or passcode brute force against `lfa web` - trusting a downloaded artifact from a host that should not be trusted - anything that runs code as the Termux user without the user asking @@ -66,3 +68,12 @@ Out of scope: Code repository is added. - Scraped download URLs are restricted to the vendor's own hosts. - `:latest` container images can be pinned with `LFA_IMAGE_`. +- The browser share (`lfa web`) generates one 8-character passcode per run + from `/dev/urandom`, keeps it in memory, and passes it to the server on + stdin. It is not written to the log, state file, shell history, or + diagnostics bundle. Failed logins are limited to five per minute per + address and compared with `hmac.compare_digest`. The server binds to the + Wi-Fi IPv4 address, not cellular. The default WebCodecs transport needs no + other listener; when `--transport webrtc` is used, go2rtc listens on + `127.0.0.1` only. The passcode page uses a self-signed HTTPS certificate by + default. diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index b4fd872..c1b91b1 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -253,6 +253,67 @@ allowed in, so `lfa storage data` copies an app's folders into `/storage/emulated/0/Android-backup/`. The copy is a snapshot, not a mount. +## Web desktop + +`lfa web` turns the running display into a browser stream. It does not start a +second X server and it works with either back end because both serve `:1`. + +``` +Termux:X11 or Xvnc :1 + | + | ffmpeg -f x11grab (or xcbgrab) + v + h264_mediacodec or libx264 + | + | Annex-B H.264 on stdout + v + web/server.py ── WebSocket :8766 ──> browser WebCodecs + ^ + | JSON input -> XTEST +``` + +The default transport sends H.264 over the same authenticated WebSocket that +carries input. The browser configures a `VideoDecoder` with the SPS profile +and level, feeds it Annex-B NAL units, and draws each `VideoFrame` to a canvas. +Each viewer gets its own ffmpeg process, so a second viewer does not disturb +the first. `--transport webrtc` keeps the older path: + +``` +ffmpeg -> RTSP 127.0.0.1:8554 -> go2rtc -> WebRTC/UDP :8555 -> browser +``` + +WebRTC is optional because Android's SELinux policy denies the netlink route +query that pion and go2rtc use to enumerate interfaces. The default +`webcodecs` transport avoids that query and works on the phone. On the WebRTC +path, go2rtc's API and RTSP server bind to `127.0.0.1`, so its +unauthenticated web interface is not reachable from the network. The config +uses an absolute ffmpeg path: Android's seccomp filter kills `faccessat2`, +which Go's `os/exec.LookPath` uses, and an absolute path skips `LookPath`. + +The shell starts the server with the passcode on stdin. That keeps the code +out of argv, the environment, the log, and the state file. The server writes +only the URL, encoder, transport, viewer count, and PIDs to +`$PREFIX/var/lib/lfa-web/.json`. + +Input arrives as small JSON messages on the WebSocket and is injected with +XTEST through `python-xlib`. Pointer positions are normalized in the browser +and scaled to the X screen, so a viewer with a different window size still +lands on the right pixel. Modifier keys are sent as ordinary key events, so +Shift and Ctrl behave like the physical keyboard. + +The passcode is 8 characters from uppercase letters and digits, generated +from `/dev/urandom`, with at least one letter and one digit. `0/O` and `1/I` +are excluded to reduce typing mistakes. Sessions last until the server stops; +the cookie is `HttpOnly`, `SameSite=Strict`, and `Secure` when TLS is on. +Failed logins are limited to five per minute per address and compared in +constant time. + +`lfa web stop` and `lfa stop` terminate the server and its ffmpeg child, plus +go2rtc when the WebRTC transport is in use. The state file records the go2rtc +PID so a hard-killed server does not leave an orphan holding ports 1984 and +8554. A recorded PID is only signalled when its command line still matches +`server.py` or `go2rtc`. + ## CI model ## Session wrappers diff --git a/docs/DECISIONS.md b/docs/DECISIONS.md index 7be4e96..eb58e9f 100644 --- a/docs/DECISIONS.md +++ b/docs/DECISIONS.md @@ -273,3 +273,30 @@ Cost: the copy is not live, and it needs the adb client in Termux plus one `adb tcpip 5555` from a PC after each reboot. Wireless debugging removes the PC requirement but needs a one-time pairing. Root or Shizuku would allow live access; neither is present on the test device. + +## D19: the browser share uses WebCodecs, not VNC + +Decision: `lfa web` captures display `:1` with ffmpeg's `x11grab` (or +`xcbgrab`), encodes H.264 with `h264_mediacodec` when available, and streams +Annex-B NAL units over an authenticated WebSocket. The browser decodes them +with WebCodecs and draws each frame to a canvas. The same socket carries XTEST +input. `--transport webrtc` keeps a go2rtc path for devices where WebRTC works. + +Why: noVNC is simpler to ship, but it sends a full framebuffer over a +WebSocket and decodes in software. On a phone that already runs a proot +desktop, that cost is visible. H.264 plus WebCodecs uses the phone's hardware +encoder and the browser's hardware decoder while keeping the protocol small. +The measured target is 100 to 250 ms on a clean Wi-Fi LAN at 720p30. + +WebRTC was the first choice, but Android 16 denies the netlink route query +that pion uses to enumerate interfaces, so go2rtc cannot gather ICE candidates +(`netlinkrib: permission denied`). WebCodecs avoids that query entirely and +works on the phone. WebRTC remains behind `--transport webrtc` for hosts where +pion can enumerate interfaces. + +Cost: the share depends on ffmpeg, the Python `websockets` module, and +`python-xlib` for input. The browser needs Chrome 94+, Edge 94+, or Safari +16.4+ for WebCodecs. A Wi-Fi network that blocks client-to-client traffic +still breaks the connection, and the browser has to accept a self-signed +certificate or use `--http`. VNC remains available as a separate, fully local +back end for users who prefer it. diff --git a/docs/TROUBLESHOOTING.md b/docs/TROUBLESHOOTING.md index 5a1e620..da159db 100644 --- a/docs/TROUBLESHOOTING.md +++ b/docs/TROUBLESHOOTING.md @@ -816,6 +816,66 @@ ssh -N -L 5901:127.0.0.1:5901 -p 8022 u0_aNNN@PHONE_IP Then point the viewer at `localhost:5901`. Do not expose 5901 to the network; VNC's password is not a substitute for SSH. +### 4.5 The browser share does not connect + +Symptom: `lfa web start` prints a URL, but the other device cannot open it, +the passcode is rejected, or the page loads with a black video. + +First run the preflight on the phone: + +```bash +lfa web doctor +``` + +It reports the missing piece: ffmpeg without `x11grab`/`xcbgrab`, a missing +Python `websockets` or `python-xlib` module, a dead display, or no Wi-Fi IPv4 +address. go2rtc is only needed for the optional WebRTC transport, and `lfa web +start --transport webrtc` downloads v1.9.15 into +`$PREFIX/lib/linux-for-android/bin` and verifies its SHA-256. + +If the phone prints `https://...` and the browser refuses the certificate, +accept the warning once. The certificate is self-signed and names the phone's +Wi-Fi address. A browser that still refuses it can use `--http` on a trusted +network. + +If the page says the browser has no WebCodecs support, use Chrome 94+, Edge +94+, or Safari 16.4+. Firefox support depends on the build. The WebRTC +transport works in browsers without WebCodecs, but needs the phone-side go2rtc +path. + +If the page loads but video stays black, check the phone log at +`$PREFIX/var/lib/lfa-web/lfa-web-.log`. An ffmpeg error there means +the capture or encoder failed; try `--encoder x264`. If the log is clean, the +connection may be blocked between the two devices; many guest Wi-Fi networks +block client-to-client traffic. Put both devices on the same normal Wi-Fi +network, or use the phone's hotspot and connect the viewer to it. + +If video works but input does not, `python-xlib` is missing. Install it with +`pkg install python-xlib` and restart the share. Without it the server still +serves video; it just cannot inject XTEST events. + +The WebSocket uses a second port. A browser that accepted the page +certificate may still block the WebSocket certificate on that port. Open +`https://PHONE_IP:8766` once and accept the warning, or start the share with +`--http` on a trusted network. + +If the phone's hardware encoder fails on a large display, choose software +encoding: + +```bash +lfa web start -i ubuntu --encoder x264 --size 1280x720 +``` + +Check the state and the log: + +```bash +lfa web status -i ubuntu +tail -n 40 "$PREFIX/var/lib/lfa-web/lfa-web-ubuntu.log" +``` + +The log never contains the passcode. If it is lost, stop the share and start +it again to print a new one. + ## 5. Applications ### 5.0 `systemctl`, `snap`, Docker, or CUDA still fail diff --git a/install_linux.sh b/install_linux.sh index a2b976a..feea1b7 100755 --- a/install_linux.sh +++ b/install_linux.sh @@ -26,6 +26,12 @@ LFA_CLI_MODE="${LFA_CLI_MODE:-0}" LFA_ASSUME_YES="${LFA_ASSUME_YES:-0}" CLI_INSTANCE="${CLI_INSTANCE:-}" +# Web desktop helpers (`lfa web`). Definitions only; nothing runs here. +if [ -f "$LFA_DIR/lib/lfa-web.sh" ]; then + # shellcheck source=lib/lfa-web.sh + . "$LFA_DIR/lib/lfa-web.sh" +fi + # ------------------------------------------------------------ # Interrupt safety and temporary artifacts. # The guest setup script carries the install passwords (obfuscated) and is @@ -1524,6 +1530,7 @@ Usage: lfa [options] android inspect or enable the Termux:API bridge usb real USB devices: list, scan, attach, tty, flash storage Android shared storage: status, repair, run helpers + web share the desktop with a browser on the LAN appimage (app, ai) extract and run an AppImage run run an AppImage once without installing it diagnostics (diag) write a support bundle @@ -1533,7 +1540,7 @@ Usage: lfa [options] help (-h) show this help Short commands exist only where they cannot be confused with another one: -status, stop, usb, storage and android stay spelled out; `desktop` is a +status, stop, usb, storage, web and android stay spelled out; `desktop` is a synonym for `start`. Global short option: @@ -1582,6 +1589,9 @@ Examples: lfa usb status lfa usb scan lfa usb exec 001/002 -- lfa-usb desc + lfa web start -i ubuntu + lfa web status -i ubuntu + lfa web stop -i ubuntu lfa appimage add ~/Foo.AppImage lfa appimage list lfa appimage run Foo @@ -6280,7 +6290,10 @@ lfa_cli() { local _cmd="${1:-help}" [ $# -gt 0 ] && shift || true if [ "${1:-}" = "-h" ] || [ "${1:-}" = "--help" ]; then - lfa_cli_usage + case "$_cmd" in + web) lfa_cli_web --help ;; + *) lfa_cli_usage ;; + esac return 0 fi # Short commands are resolved here so every handler keeps one name. @@ -6413,6 +6426,7 @@ lfa_cli() { usb) lfa_cli_usb "$@" ;; appimage|app) lfa_cli_appimage "$@" ;; storage) lfa_cli_storage "$@" ;; + web) lfa_cli_web "$@" ;; run) lfa_appimage_run "$@" ;; update) while [ $# -gt 0 ]; do case "$1" in -i|--instance) CLI_INSTANCE="${2:-}"; shift 2 ;; *) echo "Unknown option: $1" >&2; return 2 ;; esac; done @@ -8691,6 +8705,10 @@ lfa_storage_args() { # $1 = instance; prints proot-distro login arguments } EOF chmod +x "$PREFIX/bin/lfa-lib.sh" + if [ -f "$LFA_DIR/lib/lfa-web.sh" ]; then + cp -f "$LFA_DIR/lib/lfa-web.sh" "$PREFIX/bin/lfa-web.sh" 2>/dev/null || true + chmod +x "$PREFIX/bin/lfa-web.sh" 2>/dev/null || true + fi echo "[*] Generating Universal Quick-Launch Scripts..." cat << 'EOF' > $PREFIX/bin/start-linux #!/bin/bash @@ -9069,15 +9087,15 @@ if [ "$SERVER" == "x11" ]; then # visible instead of hidden. echo "Starting $DISTRO desktop as '$X11_USER' (session log: ~/start-linux-session.log)..." if [ "$DE" == "xfce4" ]; then - nohup pd_login $NO_SYSVIPC $DISTRO --user "$X11_USER" --shared-tmp -- bash -c "${USB_WRAP}mkdir -p /tmp/.X11-unix; chmod 1777 /tmp/.X11-unix; export XDG_RUNTIME_DIR=/tmp/xdg-\$USER-$DISTRO; mkdir -p "\$XDG_RUNTIME_DIR"; chmod 700 "\$XDG_RUNTIME_DIR"; export LANG=\${LANG:-C.UTF-8}; export PULSE_SERVER=127.0.0.1; export DISPLAY=:1; export XCURSOR_THEME=Adwaita; export XCURSOR_SIZE=24; $VIRGL_ENV if command -v dbus-run-session >/dev/null 2>&1; then dbus-run-session -- startxfce4 > \$HOME/start-linux-session.log 2>&1; elif command -v dbus-launch >/dev/null 2>&1; then dbus-launch --exit-with-session startxfce4 > \$HOME/start-linux-session.log 2>&1; else startxfce4 > \$HOME/start-linux-session.log 2>&1; fi" & + ( pd_login $NO_SYSVIPC $DISTRO --user "$X11_USER" --shared-tmp -- bash -c "${USB_WRAP}mkdir -p /tmp/.X11-unix; chmod 1777 /tmp/.X11-unix; export XDG_RUNTIME_DIR=/tmp/xdg-\$USER-$DISTRO; mkdir -p "\$XDG_RUNTIME_DIR"; chmod 700 "\$XDG_RUNTIME_DIR"; export LANG=\${LANG:-C.UTF-8}; export PULSE_SERVER=127.0.0.1; export DISPLAY=:1; export XCURSOR_THEME=Adwaita; export XCURSOR_SIZE=24; $VIRGL_ENV if command -v dbus-run-session >/dev/null 2>&1; then dbus-run-session -- startxfce4 > \$HOME/start-linux-session.log 2>&1; elif command -v dbus-launch >/dev/null 2>&1; then dbus-launch --exit-with-session startxfce4 > \$HOME/start-linux-session.log 2>&1; else startxfce4 > \$HOME/start-linux-session.log 2>&1; fi" ) >/dev/null 2>&1 & elif [ "$DE" == "lxde" ]; then - nohup pd_login $NO_SYSVIPC $DISTRO --user "$X11_USER" --shared-tmp -- bash -c "${USB_WRAP}mkdir -p /tmp/.X11-unix; chmod 1777 /tmp/.X11-unix; export XDG_RUNTIME_DIR=/tmp/xdg-\$USER-$DISTRO; mkdir -p "\$XDG_RUNTIME_DIR"; chmod 700 "\$XDG_RUNTIME_DIR"; export LANG=\${LANG:-C.UTF-8}; export PULSE_SERVER=127.0.0.1; export DISPLAY=:1; export XCURSOR_THEME=Adwaita; export XCURSOR_SIZE=24; $VIRGL_ENV if command -v dbus-run-session >/dev/null 2>&1; then dbus-run-session -- startlxde > \$HOME/start-linux-session.log 2>&1; elif command -v dbus-launch >/dev/null 2>&1; then dbus-launch --exit-with-session startlxde > \$HOME/start-linux-session.log 2>&1; else startlxde > \$HOME/start-linux-session.log 2>&1; fi" & + ( pd_login $NO_SYSVIPC $DISTRO --user "$X11_USER" --shared-tmp -- bash -c "${USB_WRAP}mkdir -p /tmp/.X11-unix; chmod 1777 /tmp/.X11-unix; export XDG_RUNTIME_DIR=/tmp/xdg-\$USER-$DISTRO; mkdir -p "\$XDG_RUNTIME_DIR"; chmod 700 "\$XDG_RUNTIME_DIR"; export LANG=\${LANG:-C.UTF-8}; export PULSE_SERVER=127.0.0.1; export DISPLAY=:1; export XCURSOR_THEME=Adwaita; export XCURSOR_SIZE=24; $VIRGL_ENV if command -v dbus-run-session >/dev/null 2>&1; then dbus-run-session -- startlxde > \$HOME/start-linux-session.log 2>&1; elif command -v dbus-launch >/dev/null 2>&1; then dbus-launch --exit-with-session startlxde > \$HOME/start-linux-session.log 2>&1; else startlxde > \$HOME/start-linux-session.log 2>&1; fi" ) >/dev/null 2>&1 & elif [ "$DE" == "mate" ]; then - nohup pd_login $NO_SYSVIPC $DISTRO --user "$X11_USER" --shared-tmp -- bash -c "${USB_WRAP}mkdir -p /tmp/.X11-unix; chmod 1777 /tmp/.X11-unix; export XDG_RUNTIME_DIR=/tmp/xdg-\$USER-$DISTRO; mkdir -p "\$XDG_RUNTIME_DIR"; chmod 700 "\$XDG_RUNTIME_DIR"; export LANG=\${LANG:-C.UTF-8}; export PULSE_SERVER=127.0.0.1; export DISPLAY=:1; export XCURSOR_THEME=Adwaita; export XCURSOR_SIZE=24; $VIRGL_ENV if command -v dbus-run-session >/dev/null 2>&1; then dbus-run-session -- mate-session > \$HOME/start-linux-session.log 2>&1; elif command -v dbus-launch >/dev/null 2>&1; then dbus-launch --exit-with-session mate-session > \$HOME/start-linux-session.log 2>&1; else mate-session > \$HOME/start-linux-session.log 2>&1; fi" & + ( pd_login $NO_SYSVIPC $DISTRO --user "$X11_USER" --shared-tmp -- bash -c "${USB_WRAP}mkdir -p /tmp/.X11-unix; chmod 1777 /tmp/.X11-unix; export XDG_RUNTIME_DIR=/tmp/xdg-\$USER-$DISTRO; mkdir -p "\$XDG_RUNTIME_DIR"; chmod 700 "\$XDG_RUNTIME_DIR"; export LANG=\${LANG:-C.UTF-8}; export PULSE_SERVER=127.0.0.1; export DISPLAY=:1; export XCURSOR_THEME=Adwaita; export XCURSOR_SIZE=24; $VIRGL_ENV if command -v dbus-run-session >/dev/null 2>&1; then dbus-run-session -- mate-session > \$HOME/start-linux-session.log 2>&1; elif command -v dbus-launch >/dev/null 2>&1; then dbus-launch --exit-with-session mate-session > \$HOME/start-linux-session.log 2>&1; else mate-session > \$HOME/start-linux-session.log 2>&1; fi" ) >/dev/null 2>&1 & elif [ "$DE" == "gnome" ]; then # Experimental: gnome-session is skipped (no systemd/logind in proot); # start-gnome-session runs lfa-set-wallpaper then `gnome-shell --x11`. - nohup pd_login $NO_SYSVIPC $DISTRO --user "$X11_USER" --shared-tmp -- bash -c "${USB_WRAP}mkdir -p /tmp/.X11-unix; chmod 1777 /tmp/.X11-unix; export XDG_RUNTIME_DIR=/tmp/xdg-\$USER-$DISTRO; mkdir -p "\$XDG_RUNTIME_DIR"; chmod 700 "\$XDG_RUNTIME_DIR"; export PULSE_SERVER=127.0.0.1; export DISPLAY=:1; export XCURSOR_THEME=Adwaita; export XCURSOR_SIZE=24; $VIRGL_ENV if command -v dbus-run-session >/dev/null 2>&1; then dbus-run-session -- /usr/local/bin/start-gnome-session > \$HOME/start-linux-session.log 2>&1; else /usr/local/bin/start-gnome-session > \$HOME/start-linux-session.log 2>&1; fi" & + ( pd_login $NO_SYSVIPC $DISTRO --user "$X11_USER" --shared-tmp -- bash -c "${USB_WRAP}mkdir -p /tmp/.X11-unix; chmod 1777 /tmp/.X11-unix; export XDG_RUNTIME_DIR=/tmp/xdg-\$USER-$DISTRO; mkdir -p "\$XDG_RUNTIME_DIR"; chmod 700 "\$XDG_RUNTIME_DIR"; export PULSE_SERVER=127.0.0.1; export DISPLAY=:1; export XCURSOR_THEME=Adwaita; export XCURSOR_SIZE=24; $VIRGL_ENV if command -v dbus-run-session >/dev/null 2>&1; then dbus-run-session -- /usr/local/bin/start-gnome-session > \$HOME/start-linux-session.log 2>&1; else /usr/local/bin/start-gnome-session > \$HOME/start-linux-session.log 2>&1; fi" ) >/dev/null 2>&1 & fi echo "If the screen stays on the X cursor, the desktop failed to start:" echo " cat ~/start-linux-session.log (inside the distro) for the reason." @@ -9110,7 +9128,7 @@ elif [ "$SERVER" == "vnc" ]; then [ "$DE" = "lxde" ] && VNC_SES="startlxde" [ "$DE" = "mate" ] && VNC_SES="mate-session" [ "$DE" = "gnome" ] && VNC_SES="/usr/local/bin/start-gnome-session" - nohup pd_login $NO_SYSVIPC $DISTRO --user "$X11_USER" --shared-tmp -- bash -c "${USB_WRAP}export PULSE_SERVER=127.0.0.1; mkdir -p \$HOME/.vnc \$HOME/.config/tigervnc; printf 'geometry=%s\n' '$RESOLUTION' > \$HOME/.vnc/config; printf 'geometry=%s\n' '$RESOLUTION' > \$HOME/.config/tigervnc/config; if command -v vncserver >/dev/null 2>&1; then $VIRGL_ENV vncserver :1; rc=\$?; [ \$rc -eq 0 ] || exit \$rc; else $VIRGL_ENV Xvnc :1 -geometry $RESOLUTION -depth 24 -rfbauth \$HOME/.config/tigervnc/passwd -SecurityTypes VncAuth > \$HOME/.vnc-xvnc.log 2>&1 & sleep 2; export XCURSOR_THEME=Adwaita; export XCURSOR_SIZE=24; DISPLAY=:1 dbus-run-session -- $VNC_SES > \$HOME/start-linux-session.log 2>&1; fi; exec sleep 2147483647" > "$VNC_LOG" 2>&1 & + ( pd_login $NO_SYSVIPC $DISTRO --user "$X11_USER" --shared-tmp -- bash -c "${USB_WRAP}export PULSE_SERVER=127.0.0.1; mkdir -p \$HOME/.vnc \$HOME/.config/tigervnc; printf 'geometry=%s\n' '$RESOLUTION' > \$HOME/.vnc/config; printf 'geometry=%s\n' '$RESOLUTION' > \$HOME/.config/tigervnc/config; if command -v vncserver >/dev/null 2>&1; then $VIRGL_ENV vncserver :1; rc=\$?; [ \$rc -eq 0 ] || exit \$rc; else $VIRGL_ENV Xvnc :1 -geometry $RESOLUTION -depth 24 -rfbauth \$HOME/.config/tigervnc/passwd -SecurityTypes VncAuth > \$HOME/.vnc-xvnc.log 2>&1 & sleep 2; export XCURSOR_THEME=Adwaita; export XCURSOR_SIZE=24; DISPLAY=:1 dbus-run-session -- $VNC_SES > \$HOME/start-linux-session.log 2>&1; fi; exec sleep 2147483647" > "$VNC_LOG" 2>&1 ) >/dev/null 2>&1 & echo $! > "$VNC_PIDFILE" printf 'Waiting for VNC on port 5901' for _i in $(seq 1 20); do @@ -9311,6 +9329,10 @@ fi # Hand display :1 back. A killed X server does not always remove its socket or # lock file, and the next start (either back end) then fails with # "display :1 is taken". +if [ -f "$PREFIX/bin/lfa-web.sh" ]; then + . "$PREFIX/bin/lfa-web.sh" + lfa_web_stop_one "$DISTRO" 1 2>/dev/null || true +fi sleep 2 lfa_clear_stale_x1 EOF @@ -9460,7 +9482,7 @@ EOF if [ "$LFA_DIR" != "$LFA_RUNTIME" ] && [ -f "$LFA_DIR/install_linux.sh" ]; then mkdir -p "$LFA_RUNTIME" cp -f "$LFA_DIR/install_linux.sh" "$LFA_RUNTIME/install_linux.sh" 2>/dev/null || true - for _d in lib plugins assets; do + for _d in lib plugins assets web; do if [ -d "$LFA_DIR/$_d" ]; then rm -rf "${LFA_RUNTIME:?}/$_d" cp -R "$LFA_DIR/$_d" "$LFA_RUNTIME/$_d" 2>/dev/null || true @@ -9531,6 +9553,11 @@ uninstall_linux() { # half-way, leaving a ghost container. Stop sessions first. echo "[*] Stopping any running sessions for $INSTANCE_NAME..." proot-distro kill "$INSTANCE_NAME" >/dev/null 2>&1 || true + if [ -f "$PREFIX/bin/lfa-web.sh" ]; then + # shellcheck source=lib/lfa-web.sh + . "$PREFIX/bin/lfa-web.sh" + lfa_web_stop_one "$INSTANCE_NAME" 1 2>/dev/null || true + fi echo "[*] Removing $INSTANCE_NAME (this can take a moment)..." proot-distro remove "$INSTANCE_NAME" >/dev/null 2>&1 || true @@ -9562,6 +9589,10 @@ uninstall_linux() { for _leftovers in \ "$PREFIX/tmp/lfa-vnc-$INSTANCE_NAME.pid" \ "$PREFIX/tmp/lfa-vnc-$INSTANCE_NAME.log" \ + "$PREFIX/var/lib/lfa-web/$INSTANCE_NAME.json" \ + "$PREFIX/var/lib/lfa-web/$INSTANCE_NAME.pid" \ + "$PREFIX/var/lib/lfa-web/$INSTANCE_NAME.go2rtc.yaml" \ + "$PREFIX/var/lib/lfa-web/lfa-web-$INSTANCE_NAME.log" \ "$PREFIX/tmp/gui_setup_"*.sh; do [ -e "$_leftovers" ] && rm -f "$_leftovers" 2>/dev/null || true done diff --git a/lib/lfa-web.sh b/lib/lfa-web.sh new file mode 100644 index 0000000..95d11f0 --- /dev/null +++ b/lib/lfa-web.sh @@ -0,0 +1,945 @@ +#!/bin/bash +# lfa web: share the running X display (:1) with browsers on the LAN. +# +# This file is sourced by install_linux.sh (CLI) and by stop-linux. It must +# not run anything at load time. The passcode is generated here, printed +# once, and passed to the Python server on stdin so it never appears in +# argv, the environment, the log, or the state file. + +LFA_WEB_GO2RTC_VERSION="v1.9.15" +LFA_WEB_PORT="${LFA_WEB_PORT:-8765}" +LFA_WEB_WS_PORT="${LFA_WEB_WS_PORT:-8766}" + +lfa_web_usage() { + cat <<'EOF' +Linux for Android - web desktop + +Usage: lfa web [options] + + start (up, share) share display :1 with browsers on the LAN + status (st) show the share state for an instance + stop (down) stop the share + doctor (check) check ffmpeg, go2rtc, Python modules, and the LAN IP + +Start options: + -i, --instance NAME instance label (default: last used, or the only one) + --bind ADDR LAN address to listen on (default: detected Wi-Fi IPv4) + --port N HTTPS/HTTP port (default: 8765) + --ws-port N input WebSocket port (default: 8766) + --size WxH output size (default: the display size) + --fps N frame rate (default: 30) + --encoder NAME auto, mediacodec, or x264 (default: auto) + --transport NAME auto, webcodecs, or webrtc (default: auto) + --view-only video only; ignore mouse and keyboard + --http plain HTTP instead of the self-signed HTTPS certificate + --detach leave the share running in the background + --display DISPLAY X display to capture (default: :1) + -h, --help show this help + +The passcode is 8 letters and digits, printed once when the share starts. +It is never written to disk or to the log. Every viewer has full control +unless --view-only is used. + +The default transport sends H.264 over a WebSocket and decodes it with +WebCodecs in the browser. It works on Android, where WebRTC's network +discovery is blocked by the platform. `--transport webrtc` uses go2rtc where +that path is available. +EOF +} + +lfa_web_prefix() { + printf '%s\n' "${PREFIX:-/data/data/com.termux/files/usr}" +} + +lfa_web_state_dir() { + printf '%s/var/lib/lfa-web\n' "$(lfa_web_prefix)" +} + +lfa_web_conf_dir() { + printf '%s/etc/lfa-web\n' "$(lfa_web_prefix)" +} + +lfa_web_bin_dir() { + printf '%s/lib/linux-for-android/bin\n' "$(lfa_web_prefix)" +} + +lfa_web_state_file() { + printf '%s/%s.json\n' "$(lfa_web_state_dir)" "$1" +} + +lfa_web_pid_file() { + printf '%s/%s.pid\n' "$(lfa_web_state_dir)" "$1" +} + +lfa_web_log_file() { + printf '%s/lfa-web-%s.log\n' "$(lfa_web_state_dir)" "$1" +} + +# Instances come from proot-distro's v4 and legacy layouts. install_linux.sh +# already has pd_instances; stop-linux loads lfa-lib.sh; the fallback keeps +# this file usable on its own in tests. +lfa_web_instances() { + if declare -F pd_instances >/dev/null 2>&1; then + pd_instances + return 0 + fi + if declare -F lfa_instances >/dev/null 2>&1; then + lfa_instances + return 0 + fi + local _base _d + _base="$(lfa_web_prefix)/var/lib/proot-distro" + { + if [ -d "$_base/containers" ]; then + for _d in "$_base/containers"/*; do + [ -d "$_d" ] && basename "$_d" + done + fi + for _d in "$_base/installed-rootfs"/*; do + [ -d "$_d" ] || continue + { [ -d "$_d/var" ] || [ -d "$_d/usr" ] || [ -d "$_d/bin" ]; } || continue + basename "$_d" + done + } | awk '!seen[$0]++' +} + +# Pick the instance to label this share. An explicit name must exist; with +# no name, the last used instance wins, then the only instance. +lfa_web_pick_instance() { + local _want="${1:-}" _i _list _n + _list="$(lfa_web_instances)" + if [ -n "$_want" ]; then + for _i in $_list; do + [ "$_i" = "$_want" ] && { printf '%s\n' "$_want"; return 0; } + done + return 1 + fi + if [ -r "$HOME/.config/linux-for-android/last-instance" ]; then + _want="$(cat "$HOME/.config/linux-for-android/last-instance" 2>/dev/null || true)" + for _i in $_list; do + [ "$_i" = "$_want" ] && { printf '%s\n' "$_want"; return 0; } + done + fi + _n="$(printf '%s\n' "$_list" | grep -c . 2>/dev/null || true)" + if [ "$_n" = "1" ]; then + printf '%s\n' "$_list" + return 0 + fi + return 1 +} + +# Wi-Fi IPv4 address. Cellular interfaces are skipped on purpose: sharing a +# desktop over mobile data is not what this feature is for. +lfa_web_lan_ip() { + local _ip="" + if command -v ip >/dev/null 2>&1; then + _ip="$(ip -4 -o addr show 2>/dev/null | awk ' + $2 !~ /^(lo|rmnet|ccmni|dummy|tun|tap|ppp)/ { + split($4, a, "/"); print a[1]; exit + }')" + fi + if [ -z "$_ip" ] && command -v ifconfig >/dev/null 2>&1; then + _ip="$(ifconfig 2>/dev/null | awk ' + /^[A-Za-z0-9_.-]+:/ { iface=$1 } + /inet (addr:)?[0-9]/ { + if (iface !~ /^(lo|rmnet|ccmni|dummy|tun|tap|ppp)/) { + sub(/^addr:/, "", $2); print $2; exit + } + }')" + fi + if [ -z "$_ip" ] && command -v getprop >/dev/null 2>&1; then + _ip="$(getprop dhcp.wlan0.ipaddress 2>/dev/null || true)" + fi + case "$_ip" in + ''|127.*|0.0.0.0|::*|*[!0-9.]*) return 1 ;; + esac + printf '%s\n' "$_ip" +} + +# Eight characters from uppercase letters and digits. 0/O and 1/I are left +# out so a code read from a screen is not mistyped. At least one letter and +# one digit are guaranteed. /dev/urandom keeps it unguessable. +lfa_web_passcode() { + local _alpha="ABCDEFGHJKLMNPQRSTUVWXYZ23456789" + local _code _byte _i _try + for _try in 1 2 3 4 5 6 7 8 9 10; do + _code="" + for _i in 1 2 3 4 5 6 7 8; do + _byte="$(od -An -N1 -tu1 /dev/urandom 2>/dev/null | tr -d ' \n' || true)" + _byte="${_byte:-0}" + _byte=$((10#$_byte)) + _code="${_code}${_alpha:$((_byte % ${#_alpha})):1}" + done + case "$_code" in + *[0-9]*) + case "$_code" in + *[A-Za-z]*) printf '%s\n' "$_code"; return 0 ;; + esac ;; + esac + done + return 1 +} + +lfa_web_arch() { + case "$(uname -m 2>/dev/null)" in + aarch64|arm64) printf 'arm64\n' ;; + armv7l|armv8l|arm) printf 'arm\n' ;; + armv6l) printf 'armv6\n' ;; + x86_64|amd64) printf 'amd64\n' ;; + i386|i486|i586|i686) printf 'i386\n' ;; + *) return 1 ;; + esac +} + +lfa_web_go2rtc_sha() { + case "$1" in + arm64) printf 'af416f22b21a24ab83b8d78642190b4932ae695b4e386853f11d1b0319781763\n' ;; + arm) printf 'cbffe4075a004e2015fd9d7e324800ab7968b52f49e9ce803361879d5e246028\n' ;; + armv6) printf '7dc73f47548fbe472fb6e90b01abe6c1eb50e0073b22bfc4bcf34feaabc6c88d\n' ;; + amd64) printf '20b46c6910734cb05ecefb234066f36868ff19b42ba1418a7a32e13a3e035712\n' ;; + i386) printf '3a4d74b7d6ba2a04c5c7e7c7ee6208f9060fd17dfcce5a0975d44b6621a85c1e\n' ;; + *) return 1 ;; + esac +} + +lfa_web_sha256() { + if command -v sha256sum >/dev/null 2>&1; then + sha256sum "$1" 2>/dev/null | awk '{print $1}' + elif command -v shasum >/dev/null 2>&1; then + shasum -a 256 "$1" 2>/dev/null | awk '{print $1}' + else + return 1 + fi +} + +lfa_web_go2rtc_bin() { + if [ -n "${LFA_WEB_GO2RTC:-}" ]; then + printf '%s\n' "$LFA_WEB_GO2RTC" + else + printf '%s/go2rtc\n' "$(lfa_web_bin_dir)" + fi +} + +lfa_web_go2rtc_ensure() { + local _bin _arch _want _got _tmp _url + _bin="$(lfa_web_go2rtc_bin)" + if [ -x "$_bin" ]; then + return 0 + fi + if [ -n "${LFA_WEB_GO2RTC:-}" ]; then + echo "[!] go2rtc not found at $LFA_WEB_GO2RTC" >&2 + return 1 + fi + _arch="$(lfa_web_arch)" || { + echo "[!] Unsupported CPU for go2rtc." >&2 + return 1 + } + _want="$(lfa_web_go2rtc_sha "$_arch")" || return 1 + if ! command -v curl >/dev/null 2>&1; then + echo "[!] curl is needed to download go2rtc." >&2 + return 1 + fi + mkdir -p "$(dirname "$_bin")" || return 1 + _tmp="$_bin.tmp.$$" + _url="https://github.com/AlexxIT/go2rtc/releases/download/${LFA_WEB_GO2RTC_VERSION}/go2rtc_linux_${_arch}" + echo "[*] Downloading go2rtc ${LFA_WEB_GO2RTC_VERSION} (${_arch})..." >&2 + if ! curl -fL --retry 2 --connect-timeout 15 -o "$_tmp" "$_url"; then + rm -f "$_tmp" 2>/dev/null || true + echo "[!] Could not download go2rtc." >&2 + return 1 + fi + _got="$(lfa_web_sha256 "$_tmp" 2>/dev/null || true)" + if [ "$_got" != "$_want" ]; then + rm -f "$_tmp" 2>/dev/null || true + echo "[!] go2rtc checksum mismatch (got ${_got:-none})." >&2 + return 1 + fi + chmod 755 "$_tmp" || { rm -f "$_tmp" 2>/dev/null || true; return 1; } + mv -f "$_tmp" "$_bin" || { rm -f "$_tmp" 2>/dev/null || true; return 1; } +} + +lfa_web_has_mediacodec() { + local _enc + command -v ffmpeg >/dev/null 2>&1 || return 1 + _enc="$(ffmpeg -hide_banner -encoders 2>/dev/null || true)" + case "$_enc" in + *h264_mediacodec*) return 0 ;; + esac + return 1 +} + +lfa_web_has_x264() { + local _enc + command -v ffmpeg >/dev/null 2>&1 || return 1 + _enc="$(ffmpeg -hide_banner -encoders 2>/dev/null || true)" + case "$_enc" in + *libx264*) return 0 ;; + esac + return 1 +} + +# FFmpeg exposes X11 capture as x11grab on most builds and xcbgrab on some. +# The rest of the code only needs a name; doctor checks that it is present. +lfa_web_grab_device() { + local _devs + if ! command -v ffmpeg >/dev/null 2>&1; then + printf 'xcbgrab\n' + return 0 + fi + _devs="$(ffmpeg -hide_banner -devices 2>/dev/null || true)" + case "$_devs" in + *xcbgrab*) printf 'xcbgrab\n' ;; + *x11grab*) printf 'x11grab\n' ;; + *) printf 'xcbgrab\n' ;; + esac +} + +lfa_web_has_grab_device() { + local _devs + command -v ffmpeg >/dev/null 2>&1 || return 1 + _devs="$(ffmpeg -hide_banner -devices 2>/dev/null || true)" + case "$_devs" in + *xcbgrab*|*x11grab*) return 0 ;; + esac + return 1 +} + +# go2rtc runs on localhost only. The browser talks to it through the Python +# server, and the media goes straight over UDP to the LAN address. +lfa_web_go2rtc_config() { # bind display size fps encoder path [device] + local _bind="$1" _display="$2" _size="$3" _fps="$4" _enc="$5" _path="$6" + local _device="${7:-$(lfa_web_grab_device)}" + local _encflags _cmd _ff + case "$_enc" in + mediacodec) + _encflags="-c:v h264_mediacodec -b:v 4M -g $_fps -bf 0" ;; + x264) + _encflags="-c:v libx264 -preset ultrafast -tune zerolatency -b:v 4M -g $_fps -bf 0 -pix_fmt yuv420p" ;; + *) + return 1 ;; + esac + # An absolute path keeps Go's os/exec from calling LookPath. Android's + # seccomp filter kills faccessat2, which newer Go versions use there, so + # a bare "ffmpeg" makes go2rtc die with SIGSYS on the first viewer. + _ff="$(command -v ffmpeg 2>/dev/null || true)" + [ -n "$_ff" ] || _ff="ffmpeg" + _cmd="$_ff -hide_banner -loglevel warning -fflags nobuffer -flags low_delay -f $_device -framerate $_fps -video_size $_size -i $_display $_encflags -rtsp_transport tcp -f rtsp {output}" + mkdir -p "$(dirname "$_path")" || return 1 + cat > "$_path" </dev/null 2>&1; then + DISPLAY="$_disp" xdpyinfo >/dev/null 2>&1 && return 0 + fi + for _sock in "$(lfa_web_prefix)/tmp/.X11-unix/X$_d" "/tmp/.X11-unix/X$_d"; do + [ -S "$_sock" ] && return 0 + done + if pgrep -f "^termux-x11 .* ${_disp}( |$)" >/dev/null 2>&1; then + return 0 + fi + if pgrep -f "^[^ ]*X(vnc|tigervnc) ${_disp}( |$)" >/dev/null 2>&1; then + return 0 + fi + return 1 +} + +lfa_web_screen_size() { # display -> WxH, empty when it cannot be read + local _disp="${1:-:1}" _out="" + if command -v xdpyinfo >/dev/null 2>&1; then + _out="$(DISPLAY="$_disp" xdpyinfo 2>/dev/null | awk '/dimensions:/ {print $2; exit}')" + fi + if [ -z "$_out" ] && command -v python3 >/dev/null 2>&1; then + _out="$(DISPLAY="$_disp" python3 - <<'PY' 2>/dev/null +try: + from Xlib import display + + screen = display.Display().screen() + print("%dx%d" % (screen.width_in_pixels, screen.height_in_pixels)) +except Exception: + pass +PY +)" + fi + case "$_out" in + [0-9]*x[0-9]*) printf '%s\n' "$_out" ;; + esac +} + +lfa_web_state_get() { # file key + local _file="$1" _key="$2" + [ -f "$_file" ] || return 1 + if command -v python3 >/dev/null 2>&1; then + python3 - "$_file" "$_key" <<'PY' 2>/dev/null +import json +import sys + +try: + with open(sys.argv[1], encoding="utf-8") as fh: + data = json.load(fh) +except Exception: + sys.exit(1) +value = data.get(sys.argv[2]) +if value is None: + sys.exit(1) +if isinstance(value, bool): + print("1" if value else "0") +else: + print(value) +PY + else + sed -n "s/.*\"$_key\": *\"\{0,1\}\([^\",}]*\)\"\{0,1\}.*/\1/p" "$_file" | head -n 1 + fi +} + +lfa_web_pid_alive() { + case "${1:-}" in + ''|0|*[!0-9]*) return 1 ;; + esac + kill -0 "$1" 2>/dev/null +} + +lfa_web_pid_is_server() { # pid + local _cmd + case "${1:-}" in + ''|0|*[!0-9]*) return 1 ;; + esac + _cmd="$( { tr '\0' ' ' < "/proc/$1/cmdline"; } 2>/dev/null || true)" + case "$_cmd" in + *server.py*|*lfa-web-server*) return 0 ;; + esac + return 1 +} + +# A hard-killed server cannot stop its go2rtc child. The state file keeps the +# child pid so stop and the next start can clean it up. +lfa_web_kill_orphan_go2rtc() { # statefile + local _gpid _cmd + [ -f "$1" ] || return 0 + _gpid="$(lfa_web_state_get "$1" go2rtc_pid 2>/dev/null || true)" + lfa_web_pid_alive "$_gpid" || return 0 + _cmd="$( { tr '\0' ' ' < "/proc/$_gpid/cmdline"; } 2>/dev/null || true)" + case "$_cmd" in + *go2rtc*) kill -TERM "$_gpid" 2>/dev/null || true ;; + esac +} + +# The pid is trusted only when it is alive and still looks like our server: +# after a reboot a recycled pid must not be signalled. +lfa_web_running_pid() { # instance + local _state _pid + _state="$(lfa_web_state_file "$1")" + [ -f "$_state" ] || return 1 + _pid="$(lfa_web_state_get "$_state" pid 2>/dev/null || true)" + lfa_web_pid_alive "$_pid" || return 1 + lfa_web_pid_is_server "$_pid" || return 1 + printf '%s\n' "$_pid" +} + +lfa_web_stop_one() { # instance [quiet] + local _inst="$1" _quiet="${2:-0}" _pid _i + _pid="$(lfa_web_running_pid "$_inst" 2>/dev/null || true)" + if [ -n "$_pid" ]; then + kill -TERM "$_pid" 2>/dev/null || true + for _i in 1 2 3 4 5 6 7 8 9 10; do + kill -0 "$_pid" 2>/dev/null || break + sleep 0.2 + done + if kill -0 "$_pid" 2>/dev/null; then + kill -KILL "$_pid" 2>/dev/null || true + fi + [ "$_quiet" = "1" ] || printf '%s: web desktop stopped.\n' "$_inst" + else + [ "$_quiet" = "1" ] || printf '%s: web desktop is not running.\n' "$_inst" + fi + lfa_web_kill_orphan_go2rtc "$(lfa_web_state_file "$_inst")" + rm -f "$(lfa_web_state_file "$_inst")" "$(lfa_web_pid_file "$_inst")" 2>/dev/null || true +} + +lfa_web_make_cert() { # ip -> prints the certificate path + local _ip="$1" _dir _cert _key _stamp + _dir="$(lfa_web_conf_dir)" + _cert="$_dir/cert.pem" + _key="$_dir/key.pem" + _stamp="$_dir/ip" + mkdir -p "$_dir" || return 1 + if [ -s "$_cert" ] && [ -s "$_key" ] && [ "$(cat "$_stamp" 2>/dev/null || true)" = "$_ip" ]; then + printf '%s\n' "$_cert" + return 0 + fi + if ! command -v openssl >/dev/null 2>&1; then + return 1 + fi + if ! openssl req -x509 -newkey rsa:2048 -nodes \ + -keyout "$_key" -out "$_cert" -days 365 \ + -subj "/CN=$_ip" -addext "subjectAltName=IP:$_ip" \ + >/dev/null 2>&1; then + rm -f "$_cert" "$_key" 2>/dev/null || true + return 1 + fi + chmod 600 "$_key" 2>/dev/null || true + printf '%s\n' "$_ip" > "$_stamp" 2>/dev/null || true + printf '%s\n' "$_cert" +} + +lfa_web_doctor() { + local _rc=0 _bind _py _ff _go _arch _x _inst="" _grab + while [ $# -gt 0 ]; do + case "$1" in + -i|--instance) _inst="${2:-}"; shift 2 ;; + -h|--help) lfa_web_usage; return 0 ;; + *) echo "Unknown option: $1" >&2; return 2 ;; + esac + done + echo "Linux for Android - web desktop preflight" + echo "-----------------------------------------" + + if command -v python3 >/dev/null 2>&1; then + echo "[ok] python3: $(python3 --version 2>&1)" + else + echo "[!] python3 is missing. Run: pkg install python" + _rc=1 + fi + + if command -v python3 >/dev/null 2>&1; then + _py="$(python3 -c 'import websockets; print(websockets.__version__)' 2>/dev/null || true)" + if [ -n "$_py" ]; then + echo "[ok] websockets: $_py" + else + echo "[!] Python module websockets is missing. Run: pip install websockets" + _rc=1 + fi + if python3 -c 'import Xlib' >/dev/null 2>&1; then + echo "[ok] python-xlib: input injection available" + else + echo "[!] python-xlib is missing; the share will be view-only. Run: pkg install python-xlib" + fi + fi + + if command -v ffmpeg >/dev/null 2>&1; then + _ff="$(ffmpeg -hide_banner -version 2>/dev/null | head -n 1)" + echo "[ok] ffmpeg: ${_ff:-present}" + _grab="$(lfa_web_grab_device)" + if lfa_web_has_grab_device; then + echo "[ok] ffmpeg $_grab: display capture available" + else + echo "[!] ffmpeg has no X11 capture device (x11grab or xcbgrab)." + echo " Reinstall the Termux ffmpeg package." + _rc=1 + fi + if lfa_web_has_mediacodec; then + echo "[ok] ffmpeg h264_mediacodec: hardware encoding available" + elif lfa_web_has_x264; then + echo "[!] h264_mediacodec is missing; libx264 software encoding will be used" + else + echo "[!] ffmpeg has no H.264 encoder." + _rc=1 + fi + else + echo "[!] ffmpeg is missing. Run: pkg install ffmpeg" + _rc=1 + fi + + _arch="$(lfa_web_arch 2>/dev/null || true)" + if [ -n "$_arch" ]; then + echo "[ok] CPU: $_arch" + else + echo "[i] No pinned go2rtc build for this CPU; WebCodecs still works." + fi + + _go="$(lfa_web_go2rtc_bin)" + if [ -x "$_go" ]; then + echo "[ok] go2rtc (optional WebRTC): $_go" + else + echo "[i] go2rtc is not installed; the default WebCodecs transport does not need it." + fi + echo "[ok] transport: WebCodecs over WebSocket (default)" + + if lfa_web_display_ok "${LFA_WEB_DISPLAY:-:1}"; then + echo "[ok] display ${LFA_WEB_DISPLAY:-:1}: running" + else + echo "[!] display ${LFA_WEB_DISPLAY:-:1} is not running. Start the desktop first." + _rc=1 + fi + + _bind="$(lfa_web_lan_ip 2>/dev/null || true)" + if [ -n "$_bind" ]; then + echo "[ok] LAN address: $_bind" + else + echo "[!] No Wi-Fi IPv4 address found. Use --bind ADDR." + _rc=1 + fi + + if command -v openssl >/dev/null 2>&1; then + echo "[ok] openssl: HTTPS certificate available" + else + echo "[!] openssl is missing; --http will be used." + fi + + _x="$(lfa_web_pick_instance "${_inst:-${LFA_WEB_INSTANCE:-}}" 2>/dev/null || true)" + if [ -n "$_x" ]; then + echo "[ok] instance: $_x" + else + echo "[!] No single instance found. Pass -i NAME." + _rc=1 + fi + + if [ "$_rc" = "0" ]; then + echo "-----------------------------------------" + echo "Ready. Run: lfa web start -i ${_x:-NAME}" + fi + return "$_rc" +} + +lfa_web_start() { + local _inst="" _bind="" _port="$LFA_WEB_PORT" _wsport="$LFA_WEB_WS_PORT" + local _size="auto" _fps="30" _encoder="auto" _view_only=0 _http=0 + local _transport="auto" + local _detach=0 _display=":1" _code _cert _key _scheme _pid _i _ready=0 _rc=0 + local _statefile _pidfile _log _server _webroot _cfg _py _grab _ffmpeg _capture="" + local -a _args=() + + while [ $# -gt 0 ]; do + case "$1" in + -i|--instance) _inst="${2:-}"; shift 2 ;; + --bind) _bind="${2:-}"; shift 2 ;; + --port) _port="${2:-}"; shift 2 ;; + --ws-port) _wsport="${2:-}"; shift 2 ;; + --size) _size="${2:-}"; shift 2 ;; + --fps) _fps="${2:-}"; shift 2 ;; + --encoder) _encoder="${2:-}"; shift 2 ;; + --transport) _transport="${2:-}"; shift 2 ;; + --view-only) _view_only=1; shift ;; + --http) _http=1; shift ;; + --detach) _detach=1; shift ;; + --display) _display="${2:-}"; shift 2 ;; + -h|--help) lfa_web_usage; return 0 ;; + *) echo "Unknown option: $1" >&2; return 2 ;; + esac + done + + case "$_port" in ''|*[!0-9]*) echo "[!] --port must be a number." >&2; return 2 ;; esac + case "$_wsport" in ''|*[!0-9]*) echo "[!] --ws-port must be a number." >&2; return 2 ;; esac + [ "$_port" -ge 1 ] && [ "$_port" -le 65535 ] || { echo "[!] --port is out of range." >&2; return 2; } + [ "$_wsport" -ge 1 ] && [ "$_wsport" -le 65535 ] || { echo "[!] --ws-port is out of range." >&2; return 2; } + [ "$_port" != "$_wsport" ] || { echo "[!] --port and --ws-port must differ." >&2; return 2; } + case "$_port:$_wsport" in + *:1984|*:8554|*:8555|1984:*|8554:*|8555:*) + echo "[!] Ports 1984, 8554, and 8555 are reserved for go2rtc." >&2 + return 2 ;; + esac + case "$_fps" in ''|*[!0-9]*) echo "[!] --fps must be a number." >&2; return 2 ;; esac + [ "$_fps" -ge 1 ] && [ "$_fps" -le 60 ] || { echo "[!] --fps must be 1-60." >&2; return 2; } + case "$_size" in + auto) ;; + *[!0-9x]*|x*|*x) echo "[!] --size must look like 1280x720 or be auto." >&2; return 2 ;; + esac + case "$_encoder" in auto|mediacodec|x264) ;; *) echo "[!] --encoder must be auto, mediacodec, or x264." >&2; return 2 ;; esac + case "$_transport" in auto|webcodecs|webrtc) ;; *) echo "[!] --transport must be auto, webcodecs, or webrtc." >&2; return 2 ;; esac + + if ! _inst="$(lfa_web_pick_instance "$_inst")"; then + echo "[!] Pick an instance with -i NAME (lfa list)." >&2 + return 1 + fi + + if _pid="$(lfa_web_running_pid "$_inst" 2>/dev/null || true)" && [ -n "$_pid" ]; then + echo "[!] $_inst already has a web desktop (pid $_pid)." >&2 + echo " Stop it with: lfa web stop -i $_inst" >&2 + return 1 + fi + lfa_web_kill_orphan_go2rtc "$(lfa_web_state_file "$_inst")" + rm -f "$(lfa_web_state_file "$_inst")" "$(lfa_web_pid_file "$_inst")" 2>/dev/null || true + + command -v python3 >/dev/null 2>&1 || { echo "[!] python3 is missing. Run: pkg install python" >&2; return 1; } + command -v ffmpeg >/dev/null 2>&1 || { echo "[!] ffmpeg is missing. Run: pkg install ffmpeg" >&2; return 1; } + _ffmpeg="$(command -v ffmpeg)" + if ! python3 -c 'import websockets' >/dev/null 2>&1; then + echo "[!] Python module websockets is missing. Run: pip install websockets" >&2 + return 1 + fi + if ! lfa_web_display_ok "$_display"; then + echo "[!] Display $_display is not running. Start the desktop first." >&2 + return 1 + fi + + _capture="$(lfa_web_screen_size "$_display" || true)" + if [ -z "$_capture" ]; then + _capture="$_size" + fi + if [ "$_size" = "auto" ]; then + _size="$_capture" + fi + if [ "$_size" = "auto" ] || [ -z "$_size" ]; then + _size="1280x720" + _capture="1280x720" + fi + + if [ "$_encoder" = "auto" ]; then + if lfa_web_has_mediacodec; then + _encoder="mediacodec" + else + _encoder="x264" + fi + fi + + _grab="$(lfa_web_grab_device)" + if ! lfa_web_has_grab_device; then + echo "[!] ffmpeg has no X11 capture device ($_grab). Reinstall the Termux ffmpeg package." >&2 + return 1 + fi + + [ "$_transport" = "auto" ] && _transport="webcodecs" + + if [ -z "$_bind" ]; then + if ! _bind="$(lfa_web_lan_ip)"; then + echo "[!] No Wi-Fi IPv4 address found. Use --bind ADDR." >&2 + return 1 + fi + fi + case "$_bind" in + ''|*[!0-9.]*) echo "[!] --bind must be an IPv4 address." >&2; return 2 ;; + esac + + if [ "$_http" = "0" ]; then + if _cert="$(lfa_web_make_cert "$_bind")"; then + _key="$(lfa_web_conf_dir)/key.pem" + else + echo "[!] Could not create the HTTPS certificate; falling back to HTTP." >&2 + _http=1 + fi + fi + if [ "$_http" = "1" ]; then + _scheme="http" + _cert="" + _key="" + else + _scheme="https" + fi + + if ! _code="$(lfa_web_passcode)"; then + echo "[!] Could not generate a passcode." >&2 + return 1 + fi + + if [ "$_transport" = "webrtc" ]; then + if ! lfa_web_go2rtc_ensure; then + return 1 + fi + fi + + _server="${LFA_WEB_SERVER:-}" + if [ -z "$_server" ]; then + if [ -n "${LFA_DIR:-}" ] && [ -f "$LFA_DIR/web/server.py" ]; then + _server="$LFA_DIR/web/server.py" + elif [ -f "$(lfa_web_prefix)/lib/linux-for-android/web/server.py" ]; then + _server="$(lfa_web_prefix)/lib/linux-for-android/web/server.py" + else + echo "[!] web/server.py is missing. Re-run install_linux.sh or menu 12." >&2 + return 1 + fi + fi + _webroot="$(dirname "$_server")" + + mkdir -p "$(lfa_web_state_dir)" || return 1 + _statefile="$(lfa_web_state_file "$_inst")" + _pidfile="$(lfa_web_pid_file "$_inst")" + _log="$(lfa_web_log_file "$_inst")" + : > "$_log" 2>/dev/null || true + + if [ "$_transport" = "webrtc" ]; then + _cfg="$(lfa_web_state_dir)/$_inst.go2rtc.yaml" + if ! lfa_web_go2rtc_config "$_bind" "$_display" "$_size" "$_fps" "$_encoder" "$_cfg" "$_grab"; then + echo "[!] Could not write the go2rtc config." >&2 + return 1 + fi + fi + + _args=(--bind "$_bind" --port "$_port" --ws-port "$_wsport" + --display "$_display" --size "$_size" --capture-size "$_capture" + --fps "$_fps" --encoder "$_encoder" --transport "$_transport" + --ffmpeg "$_ffmpeg" --grab "$_grab" --web-root "$_webroot" + --instance "$_inst" --pidfile "$_pidfile" --statefile "$_statefile") + if [ "$_transport" = "webrtc" ]; then + _args+=(--go2rtc "$(lfa_web_go2rtc_bin)" --go2rtc-config "$_cfg") + fi + [ "$_view_only" = "1" ] && _args+=(--view-only) + [ -n "$_cert" ] && _args+=(--cert "$_cert" --key "$_key") + + _py="${LFA_WEB_PYTHON:-python3}" + printf '%s\n' "$_code" | nohup "$_py" "$_server" "${_args[@]}" \ + >"$_log" 2>&1 & + _pid=$! + + for _i in 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 \ + 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 \ + 41 42 43 44 45 46 47 48 49 50; do + kill -0 "$_pid" 2>/dev/null || break + if command -v curl >/dev/null 2>&1; then + if curl -fsSk --max-time 1 "$_scheme://$_bind:$_port/health" >/dev/null 2>&1; then + _ready=1 + break + fi + else + _ready=1 + break + fi + sleep 0.2 + done + + if [ "$_ready" != "1" ]; then + echo "[!] The web desktop did not start." >&2 + sed -n '1,20p' "$_log" 2>/dev/null >&2 || true + kill -TERM "$_pid" 2>/dev/null || true + rm -f "$_pidfile" "$_statefile" 2>/dev/null || true + return 1 + fi + + echo "Linux for Android - web desktop" + echo "Instance: $_inst" + echo "URL: $_scheme://$_bind:$_port" + echo "Passcode: $_code" + if [ "$_encoder" = "mediacodec" ]; then + echo "Encoder: h264_mediacodec (hardware, ${_size}@${_fps})" + else + echo "Encoder: libx264 ultrafast (${_size}@${_fps})" + fi + if [ -n "$_capture" ] && [ "$_capture" != "$_size" ]; then + echo "Capture: ${_capture} scaled to ${_size}" + fi + if [ "$_transport" = "webcodecs" ]; then + echo "Transport: H.264 over WebSocket (WebCodecs)" + else + echo "Transport: WebRTC via go2rtc" + fi + if [ "$_view_only" = "1" ]; then + echo "Control: view only" + else + echo "Control: mouse and keyboard" + fi + if [ "$_http" = "1" ]; then + echo "TLS: off (--http)" + else + echo "TLS: self-signed certificate" + fi + echo "Viewers: 0" + echo "" + + if [ "$_detach" = "1" ]; then + echo "Running in the background. Stop with: lfa web stop -i $_inst" + return 0 + fi + + echo "Press Ctrl-C to stop." + if wait "$_pid"; then + _rc=0 + else + _rc=$? + fi + rm -f "$_pidfile" "$_statefile" 2>/dev/null || true + if [ "$_rc" != "0" ] && [ "$_rc" != "130" ] && [ "$_rc" != "143" ]; then + echo "[!] The web desktop exited with status $_rc." >&2 + tail -n 20 "$_log" 2>/dev/null >&2 || true + else + echo "Web desktop stopped." + fi + return 0 +} + +lfa_web_status() { + local _inst="" _pid _state _url _enc _transport _viewers _started _uptime _now + while [ $# -gt 0 ]; do + case "$1" in + -i|--instance) _inst="${2:-}"; shift 2 ;; + -h|--help) lfa_web_usage; return 0 ;; + *) echo "Unknown option: $1" >&2; return 2 ;; + esac + done + if ! _inst="$(lfa_web_pick_instance "$_inst")"; then + echo "[!] Pick an instance with -i NAME (lfa list)." >&2 + return 1 + fi + _state="$(lfa_web_state_file "$_inst")" + _pid="$(lfa_web_running_pid "$_inst" 2>/dev/null || true)" + if [ -z "$_pid" ]; then + rm -f "$_state" "$(lfa_web_pid_file "$_inst")" 2>/dev/null || true + printf '%s: web desktop is not running.\n' "$_inst" + return 0 + fi + _url="$(lfa_web_state_get "$_state" url 2>/dev/null || true)" + _enc="$(lfa_web_state_get "$_state" encoder 2>/dev/null || true)" + _transport="$(lfa_web_state_get "$_state" transport 2>/dev/null || true)" + _viewers="$(lfa_web_state_get "$_state" viewers 2>/dev/null || true)" + _started="$(lfa_web_state_get "$_state" started 2>/dev/null || true)" + _uptime="" + if [ -n "$_started" ]; then + _now="$(date +%s 2>/dev/null || echo 0)" + case "$_started" in ''|*[!0-9]*) _started="" ;; esac + if [ -n "$_started" ] && [ "$_now" -ge "$_started" ] 2>/dev/null; then + _uptime=$(( _now - _started )) + _uptime="$(printf '%02d:%02d:%02d' $((_uptime/3600)) $(((_uptime%3600)/60)) $((_uptime%60)))" + fi + fi + printf '%s: web desktop running (pid %s)\n' "$_inst" "$_pid" + [ -n "$_url" ] && printf ' URL: %s\n' "$_url" + [ -n "$_enc" ] && printf ' Encoder: %s\n' "$_enc" + [ -n "$_transport" ] && printf ' Transport: %s\n' "$_transport" + printf ' Viewers: %s\n' "${_viewers:-0}" + [ -n "$_uptime" ] && printf ' Uptime: %s\n' "$_uptime" + printf ' Passcode: hidden (printed when started)\n' + return 0 +} + +lfa_web_stop() { + local _inst="" _all=0 _i + while [ $# -gt 0 ]; do + case "$1" in + -i|--instance) _inst="${2:-}"; shift 2 ;; + --all) _all=1; shift ;; + -h|--help) lfa_web_usage; return 0 ;; + *) echo "Unknown option: $1" >&2; return 2 ;; + esac + done + if [ "$_all" = "1" ]; then + [ -z "$_inst" ] || { echo "[!] --all and -i cannot be used together." >&2; return 2; } + for _i in $(lfa_web_instances); do + lfa_web_stop_one "$_i" + done + return 0 + fi + if ! _inst="$(lfa_web_pick_instance "$_inst")"; then + echo "[!] Pick an instance with -i NAME (lfa list)." >&2 + return 1 + fi + lfa_web_stop_one "$_inst" +} + +lfa_cli_web() { + local _sub="${1:-help}" + [ $# -gt 0 ] && shift || true + case "$_sub" in + start|up|share) lfa_web_start "$@" ;; + stop|down) lfa_web_stop "$@" ;; + status|st) lfa_web_status "$@" ;; + doctor|check|preflight) lfa_web_doctor "$@" ;; + help|-h|--help) lfa_web_usage ;; + *) echo "Unknown web command: $_sub" >&2; lfa_web_usage >&2; return 2 ;; + esac +} diff --git a/tests/test-all.sh b/tests/test-all.sh index 8b18b6f..49702f9 100755 --- a/tests/test-all.sh +++ b/tests/test-all.sh @@ -2422,6 +2422,11 @@ check "Y13c CLI external on" 'STORAGE_EXTERNAL="1"' "$CCONF" check "Y13c start launcher uses policy" 'lfa_storage_args' "$T/prefix/bin/start-linux" check "Y13c terminal launcher uses policy" 'lfa_storage_args' "$T/prefix/bin/terminal-linux" check "Y13c lib knows isolation" '--isolated' "$T/prefix/bin/lfa-lib.sh" +check "Y13c web helper installed" 'lfa_cli_web' "$T/prefix/bin/lfa-web.sh" +[ -f "$T/prefix/lib/linux-for-android/web/server.py" ] && pass=$((pass+1)) \ + || { fail=$((fail+1)); echo "FAIL: Y13c web server not copied to runtime"; } +[ -f "$T/prefix/lib/linux-for-android/web/player.html" ] && pass=$((pass+1)) \ + || { fail=$((fail+1)); echo "FAIL: Y13c player page not copied to runtime"; } printf '%s\n' "$(LFA_STORAGE_BIND="/tmp/fake:/media/fake" \ bash -c '. "$1/bin/lfa-lib.sh"; lfa_storage_args "$2"' _ "$T/prefix" stgcli)" \ > "$T/y13args.log" @@ -2479,6 +2484,165 @@ bash "$REPO/install_linux.sh" --cli storage android enable --all -i alpha > "$T/ [ "$rc" = "2" ] && pass=$((pass+1)) || { fail=$((fail+1)); echo "FAIL: Y13d --all with -i exit $rc"; } check "Y13d --all with -i refused" 'Use --all or -i NAME' "$T/y13d4.log" +echo "===== Y14: lfa web (LAN browser desktop) =====" +fresh_env +WEBLIB="$REPO/lib/lfa-web.sh" +[ -f "$WEBLIB" ] && pass=$((pass+1)) || { fail=$((fail+1)); echo "FAIL: Y14 web helper missing"; } + +bash "$REPO/install_linux.sh" --cli web --help > "$T/y14help.log" 2>&1; rc=$? +[ "$rc" = "0" ] && pass=$((pass+1)) || { fail=$((fail+1)); echo "FAIL: Y14 help exit $rc"; } +check "Y14 help passcode" 'passcode' "$T/y14help.log" +check "Y14 help webrtc" 'WebRTC' "$T/y14help.log" +check "Y14 help start" 'lfa web ' "$T/y14help.log" + +bash "$REPO/install_linux.sh" --cli web bogus > "$T/y14bogus.log" 2>&1; rc=$? +[ "$rc" = "2" ] && pass=$((pass+1)) || { fail=$((fail+1)); echo "FAIL: Y14 unknown command exit $rc"; } +check "Y14 unknown command" 'Unknown web command' "$T/y14bogus.log" + +bash -c 'PREFIX="$1"; . "$2"; lfa_web_passcode' _ "$T/prefix" "$WEBLIB" > "$T/y14code.log" +[ "$(tr -d '\n' < "$T/y14code.log" | wc -c)" = "8" ] && pass=$((pass+1)) \ + || { fail=$((fail+1)); echo "FAIL: Y14 passcode is not 8 characters"; } +check_re "Y14 passcode is alphanumeric" '^[A-Za-z0-9]{8}$' "$T/y14code.log" +grep -q '[0-9]' "$T/y14code.log" && pass=$((pass+1)) || { fail=$((fail+1)); echo "FAIL: Y14 passcode has no digit"; } +grep -q '[A-Za-z]' "$T/y14code.log" && pass=$((pass+1)) || { fail=$((fail+1)); echo "FAIL: Y14 passcode has no letter"; } +check_absent "Y14 passcode has no 0" '0' "$T/y14code.log" +check_absent "Y14 passcode has no O" 'O' "$T/y14code.log" +check_absent "Y14 passcode has no 1" '1' "$T/y14code.log" +check_absent "Y14 passcode has no I" 'I' "$T/y14code.log" +check_absent "Y14 passcode has no l" 'l' "$T/y14code.log" + +: > "$T/y14codes.log" +_i=0 +while [ "$_i" -lt 50 ]; do + bash -c 'PREFIX="$1"; . "$2"; lfa_web_passcode' _ "$T/prefix" "$WEBLIB" >> "$T/y14codes.log" + _i=$((_i+1)) +done +[ "$(sort -u "$T/y14codes.log" | grep -c .)" = "50" ] && pass=$((pass+1)) \ + || { fail=$((fail+1)); echo "FAIL: Y14 passcodes are not unique"; } + +mkdir -p "$T/webbin" +cat > "$T/webbin/ip" <<'EOF' +#!/bin/bash +echo "1: lo inet 127.0.0.1/8 scope host lo" +echo "2: rmnet0 inet 10.0.0.5/24 scope global rmnet0" +echo "3: wlan0 inet 192.168.1.42/24 brd 192.168.1.255 scope global wlan0" +EOF +chmod +x "$T/webbin/ip" +_ipout="$(PATH="$T/webbin:$PATH" bash -c 'PREFIX="$1"; . "$2"; lfa_web_lan_ip' _ "$T/prefix" "$WEBLIB")" +[ "$_ipout" = "192.168.1.42" ] && pass=$((pass+1)) \ + || { fail=$((fail+1)); echo "FAIL: Y14 LAN IP picked [$_ipout]"; } + +bash -c 'PREFIX="$1"; . "$2"; lfa_web_go2rtc_config 192.168.1.42 :1 1280x720 30 mediacodec "$3"' \ + _ "$T/prefix" "$WEBLIB" "$T/y14go2rtc.yaml" +check "Y14 config api local" 'listen: "127.0.0.1:1984"' "$T/y14go2rtc.yaml" +check "Y14 config rtsp local" 'listen: "127.0.0.1:8554"' "$T/y14go2rtc.yaml" +check "Y14 config candidate" '192.168.1.42:8555' "$T/y14go2rtc.yaml" +check_re "Y14 config grab" 'x(11|cb)grab' "$T/y14go2rtc.yaml" +check "Y14 config display" '-i :1' "$T/y14go2rtc.yaml" +check "Y14 config output" '{output}' "$T/y14go2rtc.yaml" +check "Y14 config mediacodec" 'h264_mediacodec' "$T/y14go2rtc.yaml" +bash -c 'PREFIX="$1"; . "$2"; lfa_web_go2rtc_config 192.168.1.42 :1 1280x720 30 x264 "$3"' \ + _ "$T/prefix" "$WEBLIB" "$T/y14x264.yaml" +check "Y14 config x264" 'libx264' "$T/y14x264.yaml" +check "Y14 config zerolatency" 'zerolatency' "$T/y14x264.yaml" + +if python3 - "$REPO" <<'PY' +import importlib.util +import sys +import types + +spec = importlib.util.spec_from_file_location("lfasrv", sys.argv[1] + "/web/server.py") +mod = importlib.util.module_from_spec(spec) +spec.loader.exec_module(mod) +sps = b"\x67\x42\xc0\x1f\xaa" +pps = b"\x68\xce\x3c\x80" +idr = b"\x65\x88\x84" +buf = b"\x00\x00\x00\x01" + sps + b"\x00\x00\x00\x01" + pps + b"\x00\x00\x00\x01" + idr +nals, rest = mod.split_annexb(buf) +assert nals == [sps, pps], nals +assert rest.startswith(b"\x00\x00\x01"), rest +assert mod.codec_string(sps) == "avc1.42C01F" +mod.ARGS = types.SimpleNamespace( + ffmpeg="/x/ffmpeg", encoder="mediacodec", fps=30, + grab="x11grab", size="1280x720", display=":1", +) +cmd = mod.ffmpeg_command() +assert cmd[0] == "/x/ffmpeg" +assert "x11grab" in cmd +assert "h264_mediacodec" in cmd +assert cmd[-1] == "pipe:1" +PY +then pass=$((pass+1)); else fail=$((fail+1)); echo "FAIL: Y14 WebCodecs NAL/ffmpeg helpers"; fi + +bash -c 'PREFIX="$1"; . "$2"; lfa_web_display_ok :77' _ "$T/prefix" "$WEBLIB" 2>/dev/null +[ "$?" != "0" ] && pass=$((pass+1)) || { fail=$((fail+1)); echo "FAIL: Y14 dead display accepted"; } +LFA_WEB_SKIP_DISPLAY=1 bash -c 'PREFIX="$1"; . "$2"; lfa_web_display_ok :77' _ "$T/prefix" "$WEBLIB" +[ "$?" = "0" ] && pass=$((pass+1)) || { fail=$((fail+1)); echo "FAIL: Y14 skip-display override"; } + +mkdir -p "$T/prefix/var/lib/proot-distro/installed-rootfs/web1/var" +mkdir -p "$T/home/.config/linux-for-android" +printf 'web1\n' > "$T/home/.config/linux-for-android/last-instance" +_pick="$(bash -c 'PREFIX="$1"; HOME="$2"; . "$3"; lfa_web_pick_instance' _ "$T/prefix" "$T/home" "$WEBLIB")" +[ "$_pick" = "web1" ] && pass=$((pass+1)) || { fail=$((fail+1)); echo "FAIL: Y14 instance pick [$_pick]"; } + +bash "$REPO/install_linux.sh" --cli web status -i web1 > "$T/y14st.log" 2>&1; rc=$? +[ "$rc" = "0" ] && pass=$((pass+1)) || { fail=$((fail+1)); echo "FAIL: Y14 status exit $rc"; } +check "Y14 status stopped" 'web desktop is not running' "$T/y14st.log" + +bash "$REPO/install_linux.sh" --cli web start --port 0 > "$T/y14port.log" 2>&1; rc=$? +[ "$rc" = "2" ] && pass=$((pass+1)) || { fail=$((fail+1)); echo "FAIL: Y14 port 0 exit $rc"; } +check "Y14 port range" '--port is out of range' "$T/y14port.log" +bash "$REPO/install_linux.sh" --cli web start --size bad > "$T/y14size.log" 2>&1; rc=$? +[ "$rc" = "2" ] && pass=$((pass+1)) || { fail=$((fail+1)); echo "FAIL: Y14 bad size exit $rc"; } +check "Y14 size shape" '--size must look like' "$T/y14size.log" +bash "$REPO/install_linux.sh" --cli web start --encoder nope > "$T/y14enc.log" 2>&1; rc=$? +[ "$rc" = "2" ] && pass=$((pass+1)) || { fail=$((fail+1)); echo "FAIL: Y14 bad encoder exit $rc"; } +check "Y14 encoder choice" '--encoder must be' "$T/y14enc.log" + +LFA_WEB_SKIP_DISPLAY=1 bash "$REPO/install_linux.sh" --cli web doctor > "$T/y14doc.log" 2>&1 || true +check "Y14 doctor header" 'web desktop preflight' "$T/y14doc.log" +check "Y14 doctor ffmpeg" 'ffmpeg' "$T/y14doc.log" +check "Y14 doctor display" 'display' "$T/y14doc.log" + +# A live process whose cmdline is not server.py must never be signalled. +mkdir -p "$T/prefix/var/lib/lfa-web" +sleep 60 & _spid=$! +printf '{"pid":%s,"instance":"web1","url":"https://192.168.1.42:8765","started":0,"encoder":"x264","viewers":0,"view_only":false,"ws_port":8766,"go2rtc_pid":0}\n' \ + "$_spid" > "$T/prefix/var/lib/lfa-web/web1.json" +bash "$REPO/install_linux.sh" --cli web stop -i web1 > "$T/y14safe.log" 2>&1 +check "Y14 stop refuses unrelated pid" 'web desktop is not running' "$T/y14safe.log" +kill -0 "$_spid" 2>/dev/null && pass=$((pass+1)) \ + || { fail=$((fail+1)); echo "FAIL: Y14 stop killed an unrelated process"; } +kill "$_spid" 2>/dev/null || true +[ ! -f "$T/prefix/var/lib/lfa-web/web1.json" ] && pass=$((pass+1)) \ + || { fail=$((fail+1)); echo "FAIL: Y14 stop left stale state"; } + +# A process whose cmdline is server.py is the real target. +mkdir -p "$T/webfake" +printf 'import time\ntime.sleep(60)\n' > "$T/webfake/server.py" +python3 "$T/webfake/server.py" & _fpid=$! +printf '{"pid":%s,"instance":"web1","url":"https://192.168.1.42:8765","started":%s,"encoder":"mediacodec","viewers":2,"view_only":false,"ws_port":8766,"go2rtc_pid":0}\n' \ + "$_fpid" "$(date +%s)" > "$T/prefix/var/lib/lfa-web/web1.json" +bash "$REPO/install_linux.sh" --cli web status -i web1 > "$T/y14run.log" 2>&1 +check "Y14 status running" 'web desktop running' "$T/y14run.log" +check "Y14 status url" 'https://192.168.1.42:8765' "$T/y14run.log" +check "Y14 status viewers" 'Viewers: 2' "$T/y14run.log" +check "Y14 status passcode hidden" 'Passcode: hidden' "$T/y14run.log" +bash "$REPO/install_linux.sh" --cli web stop -i web1 > "$T/y14stop.log" 2>&1 +check "Y14 stop running" 'web desktop stopped' "$T/y14stop.log" +wait "$_fpid" 2>/dev/null || true +if kill -0 "$_fpid" 2>/dev/null; then + fail=$((fail+1)); echo "FAIL: Y14 stop left the server alive"; kill "$_fpid" 2>/dev/null || true +else + pass=$((pass+1)) +fi +[ ! -f "$T/prefix/var/lib/lfa-web/web1.json" ] && pass=$((pass+1)) \ + || { fail=$((fail+1)); echo "FAIL: Y14 stop did not remove state"; } + +bash "$REPO/install_linux.sh" --cli web stop --all -i web1 > "$T/y14all.log" 2>&1; rc=$? +[ "$rc" = "2" ] && pass=$((pass+1)) || { fail=$((fail+1)); echo "FAIL: Y14 stop --all with -i exit $rc"; } +check "Y14 stop --all with -i refused" 'cannot be used together' "$T/y14all.log" + echo "" echo "===== Z: documentation links =====" [ -s "$REPO/docs/TROUBLESHOOTING.md" ] && pass=$((pass+1)) || { fail=$((fail+1)); echo "FAIL: Z troubleshooting guide missing"; } diff --git a/web/app.js b/web/app.js new file mode 100644 index 0000000..c60f880 --- /dev/null +++ b/web/app.js @@ -0,0 +1,373 @@ +(() => { + "use strict"; + + const body = document.body; + const cfg = { + wsPort: parseInt(body.dataset.wsPort || "8766", 10), + wsScheme: body.dataset.wsScheme || + (window.location.protocol === "https:" ? "wss" : "ws"), + viewOnly: body.dataset.viewOnly === "true", + transport: body.dataset.transport || "webcodecs", + width: parseInt(body.dataset.width || "1280", 10), + height: parseInt(body.dataset.height || "720", 10) + }; + + const stage = document.getElementById("stage"); + const video = document.getElementById("screen"); + const canvas = document.getElementById("screen-canvas"); + const ctx = canvas.getContext("2d", { alpha: false }); + const overlay = document.getElementById("overlay"); + const statusEl = document.getElementById("status"); + const retry = document.getElementById("retry"); + const hud = document.getElementById("hud"); + const hudFps = document.getElementById("hud-fps"); + const hudRate = document.getElementById("hud-rate"); + const full = document.getElementById("full"); + const control = document.getElementById("control"); + + let pc = null; + let ws = null; + let wsTimer = null; + let retryTimer = null; + let decoder = null; + let lastBytes = 0; + let lastFrames = 0; + let lastStats = 0; + let decodedFrames = 0; + let decodedBytes = 0; + + function setStatus(text, show) { + statusEl.textContent = text; + overlay.hidden = !show; + } + + function reconnect() { + if (cfg.transport === "webcodecs") connectWebCodecs(); + else connectVideo(); + } + + function scheduleRetry(message) { + setStatus(message, true); + retry.hidden = false; + clearTimeout(retryTimer); + retryTimer = setTimeout(reconnect, 2000); + } + + function applyLowLatency() { + if (!pc) return; + for (const receiver of pc.getReceivers()) { + try { receiver.playoutDelayHint = 0; } catch (_) { /* older browser */ } + try { receiver.jitterBufferTarget = 0; } catch (_) { /* older browser */ } + } + } + + async function connectVideo() { + clearTimeout(retryTimer); + retry.hidden = true; + setStatus("Connecting video...", true); + if (pc) { + try { pc.close(); } catch (_) { /* already closed */ } + pc = null; + } + pc = new RTCPeerConnection({ iceServers: [] }); + pc.addTransceiver("video", { direction: "recvonly" }); + pc.ontrack = (event) => { + const stream = event.streams[0] || new MediaStream([event.track]); + video.srcObject = stream; + video.hidden = false; + canvas.hidden = true; + video.play().catch(() => { /* autoplay is allowed because muted */ }); + }; + pc.onconnectionstatechange = () => { + const state = pc ? pc.connectionState : "closed"; + if (state === "connected") { + setStatus("", false); + hud.hidden = false; + applyLowLatency(); + } else if (state === "failed" || state === "disconnected") { + scheduleRetry("Video disconnected. Reconnecting..."); + } + }; + try { + const offer = await pc.createOffer(); + await pc.setLocalDescription(offer); + const res = await fetch("/api/webrtc", { + method: "POST", + headers: { "Content-Type": "application/sdp" }, + body: offer.sdp + }); + if (!res.ok) throw new Error("signaling " + res.status); + const answer = await res.text(); + await pc.setRemoteDescription({ type: "answer", sdp: answer }); + applyLowLatency(); + } catch (err) { + scheduleRetry("Video failed: " + err.message); + } + } + + function drawFrame(frame) { + if (!canvas.width || !canvas.height) { + canvas.width = frame.displayWidth || cfg.width; + canvas.height = frame.displayHeight || cfg.height; + } + ctx.drawImage(frame, 0, 0, canvas.width, canvas.height); + frame.close(); + decodedFrames += 1; + if (!overlay.hidden) { + setStatus("", false); + hud.hidden = false; + } + } + + function configureDecoder(config) { + if (typeof VideoDecoder === "undefined") { + setStatus("This browser has no WebCodecs support. Use Chrome, Edge, or Safari 16.4+.", true); + return; + } + if (decoder) { + try { decoder.close(); } catch (_) { /* already closed */ } + } + decoder = new VideoDecoder({ + output: drawFrame, + error: (err) => scheduleRetry("Decoder: " + err.message) + }); + const base = { + codec: config.codec || "avc1.42E01F", + optimizeForLatency: true + }; + try { + decoder.configure({ ...base, avc: { format: "annexb" } }); + } catch (_) { + decoder.configure(base); + } + canvas.width = config.width || cfg.width; + canvas.height = config.height || cfg.height; + canvas.hidden = false; + video.hidden = true; + } + + function handleVideo(data) { + if (!(data instanceof ArrayBuffer) || data.byteLength < 10 || !decoder) return; + const view = new DataView(data); + const key = view.getUint8(0) === 1; + const timestamp = Number(view.getBigUint64(1)); + const payload = new Uint8Array(data, 9); + decodedBytes += payload.byteLength; + try { + decoder.decode(new EncodedVideoChunk({ + type: key ? "key" : "delta", + timestamp, + data: payload + })); + } catch (err) { + scheduleRetry("Decode failed: " + err.message); + } + } + + function connectWebCodecs() { + clearTimeout(retryTimer); + retry.hidden = true; + if (ws) { + try { ws.close(); } catch (_) { /* already closed */ } + ws = null; + } + if (typeof VideoDecoder === "undefined") { + setStatus("This browser has no WebCodecs support. Use Chrome, Edge, or Safari 16.4+.", true); + return; + } + setStatus("Waiting for video...", true); + const url = cfg.wsScheme + "://" + window.location.hostname + ":" + cfg.wsPort + "/"; + ws = new WebSocket(url); + ws.binaryType = "arraybuffer"; + ws.onopen = () => { control.textContent = "Control on"; }; + ws.onmessage = (event) => { + if (typeof event.data === "string") { + let msg; + try { msg = JSON.parse(event.data); } catch (_) { return; } + if (msg.t === "config") configureDecoder(msg); + else if (msg.t === "error") setStatus(msg.message || "Video error", true); + } else { + handleVideo(event.data); + } + }; + ws.onclose = () => { + control.textContent = "Reconnecting"; + setStatus("Connection lost. Reconnecting...", true); + clearTimeout(wsTimer); + wsTimer = setTimeout(connectWebCodecs, 2000); + }; + ws.onerror = () => { + try { ws.close(); } catch (_) { /* already closed */ } + }; + } + + function connectInput() { + if (cfg.viewOnly) { + control.textContent = "View only"; + return; + } + clearTimeout(wsTimer); + const url = cfg.wsScheme + "://" + window.location.hostname + ":" + cfg.wsPort + "/"; + ws = new WebSocket(url); + ws.onopen = () => { control.textContent = "Control on"; }; + ws.onclose = () => { + control.textContent = "Control reconnecting"; + wsTimer = setTimeout(connectInput, 2000); + }; + ws.onerror = () => { + try { ws.close(); } catch (_) { /* already closed */ } + }; + } + + function send(event) { + if (!ws || ws.readyState !== WebSocket.OPEN) return; + ws.send(JSON.stringify(event)); + } + + function contentRect() { + const rect = stage.getBoundingClientRect(); + const vw = canvas.hidden ? (video.videoWidth || cfg.width) : (canvas.width || cfg.width); + const vh = canvas.hidden ? (video.videoHeight || cfg.height) : (canvas.height || cfg.height); + const scale = Math.min(rect.width / Math.max(1, vw), rect.height / Math.max(1, vh)); + const width = vw * scale; + const height = vh * scale; + return { + left: rect.left + (rect.width - width) / 2, + top: rect.top + (rect.height - height) / 2, + width, + height + }; + } + + function norm(ev) { + const rect = contentRect(); + const x = (ev.clientX - rect.left) / Math.max(1, rect.width); + const y = (ev.clientY - rect.top) / Math.max(1, rect.height); + return [Math.min(1, Math.max(0, x)), Math.min(1, Math.max(0, y))]; + } + + const buttons = { 0: 1, 1: 2, 2: 3 }; + const pressed = new Set(); + const surfaces = [video, canvas]; + + function release(ev) { + if (cfg.viewOnly) return; + const button = buttons[ev.button] || 1; + if (pressed.has(button)) { + pressed.delete(button); + send({ t: "b", button, down: false }); + } + } + + for (const surface of surfaces) { + surface.addEventListener("pointerdown", (ev) => { + if (cfg.viewOnly) return; + ev.preventDefault(); + try { surface.setPointerCapture(ev.pointerId); } catch (_) { /* touch */ } + const [x, y] = norm(ev); + send({ t: "m", x, y }); + const button = buttons[ev.button] || 1; + pressed.add(button); + send({ t: "b", button, down: true }); + }); + + surface.addEventListener("pointermove", (ev) => { + if (cfg.viewOnly) return; + const [x, y] = norm(ev); + send({ t: "m", x, y }); + }); + + surface.addEventListener("pointerup", release); + surface.addEventListener("pointercancel", release); + surface.addEventListener("contextmenu", (ev) => ev.preventDefault()); + surface.addEventListener("wheel", (ev) => { + if (cfg.viewOnly) return; + ev.preventDefault(); + send({ t: "w", dx: ev.deltaX, dy: ev.deltaY }); + }, { passive: false }); + } + + const keys = new Set(); + + window.addEventListener("keydown", (ev) => { + if (cfg.viewOnly) return; + if (document.activeElement && document.activeElement.tagName === "BUTTON") return; + if (ev.key === "Escape" && document.fullscreenElement) return; + if (ev.metaKey) return; + if (ev.ctrlKey && (ev.key === "F11" || ev.key === "F12")) return; + ev.preventDefault(); + if (keys.has(ev.key)) return; + keys.add(ev.key); + send({ t: "kd", key: ev.key }); + }); + + window.addEventListener("keyup", (ev) => { + if (cfg.viewOnly) return; + if (keys.delete(ev.key)) send({ t: "ku", key: ev.key }); + }); + + window.addEventListener("blur", () => { + for (const key of keys) send({ t: "ku", key }); + keys.clear(); + for (const button of pressed) send({ t: "b", button, down: false }); + pressed.clear(); + }); + + full.addEventListener("click", async () => { + try { + if (document.fullscreenElement) await document.exitFullscreen(); + else await stage.requestFullscreen(); + } catch (_) { /* denied */ } + }); + + async function stats() { + if (cfg.transport === "webcodecs") { + const now = performance.now(); + if (lastStats) { + const dt = Math.max(0.001, (now - lastStats) / 1000); + const frames = decodedFrames - lastFrames; + const bytes = decodedBytes - lastBytes; + hudFps.textContent = Math.round(frames / dt) + " fps"; + hudRate.textContent = (bytes * 8 / 1e6 / dt).toFixed(1) + " Mbps"; + } + lastStats = now; + lastFrames = decodedFrames; + lastBytes = decodedBytes; + return; + } + if (!pc || pc.connectionState !== "connected") return; + try { + const report = await pc.getStats(); + report.forEach((s) => { + if (s.type !== "inbound-rtp" || s.kind !== "video") return; + const now = s.timestamp; + if (lastStats) { + const dt = Math.max(0.001, (now - lastStats) / 1000); + const frames = (s.framesDecoded || 0) - lastFrames; + const bytes = (s.bytesReceived || 0) - lastBytes; + hudFps.textContent = Math.round(frames / dt) + " fps"; + hudRate.textContent = (bytes * 8 / 1e6 / dt).toFixed(1) + " Mbps"; + } + lastStats = now; + lastFrames = s.framesDecoded || 0; + lastBytes = s.bytesReceived || 0; + }); + } catch (_) { /* stats are optional */ } + } + + setInterval(stats, 1000); + retry.addEventListener("click", reconnect); + document.addEventListener("visibilitychange", () => { + if (!document.hidden && cfg.transport === "webrtc" && pc && + pc.connectionState === "failed") { + connectVideo(); + } + }); + + if (cfg.transport === "webcodecs") { + connectWebCodecs(); + } else { + connectVideo(); + connectInput(); + } +})(); diff --git a/web/login.html b/web/login.html new file mode 100644 index 0000000..f8d7e88 --- /dev/null +++ b/web/login.html @@ -0,0 +1,26 @@ + + + + + + +LFA web desktop + + + +
+

LFA web desktop

+

Enter the 8-character passcode shown on the phone.

+
+ + + + +
+

Letters and digits only. The code is valid until the share stops.

+
+ + + diff --git a/web/login.js b/web/login.js new file mode 100644 index 0000000..ca04f5a --- /dev/null +++ b/web/login.js @@ -0,0 +1,5 @@ +const params = new URLSearchParams(window.location.search); +if (params.get("error")) { + const box = document.getElementById("err"); + if (box) box.hidden = false; +} diff --git a/web/player.html b/web/player.html new file mode 100644 index 0000000..e7b7c7c --- /dev/null +++ b/web/player.html @@ -0,0 +1,40 @@ + + + + + + +LFA web desktop + + + +
+ + +
+
+

LFA web desktop

+

Connecting to {{INSTANCE}}...

+ +
+
+ +
+ {{INSTANCE}} + + Control on + +
+
+ + + diff --git a/web/server.py b/web/server.py new file mode 100644 index 0000000..5df471c --- /dev/null +++ b/web/server.py @@ -0,0 +1,752 @@ +#!/usr/bin/env python3 +"""LFA web desktop: passcode auth, H.264/WebCodecs stream, and X11 input. + +The default transport runs ffmpeg, streams Annex-B H.264 over an authenticated +WebSocket, and injects XTEST input on the same socket. The optional WebRTC +transport keeps go2rtc on 127.0.0.1 and proxies its WHEP handshake. This +server is the only listener on the LAN. The passcode arrives on stdin once and +stays in memory. +""" + +import argparse +import asyncio +import hmac +import json +import os +import secrets +import shutil +import signal +import ssl +import subprocess +import sys +import tempfile +import threading +import time +import urllib.error +import urllib.request +from http.cookies import SimpleCookie +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from pathlib import Path +from urllib.parse import parse_qs, urlsplit + +try: + import websockets +except ImportError: # reported by `lfa web doctor` + websockets = None + +try: + from Xlib import X, XK, display as xdisplay + from Xlib.ext import xtest +except ImportError: # video still works; input is disabled + X = XK = xdisplay = xtest = None + +ARGS = None +PASSCODE = "" +SESSIONS = {} +ATTEMPTS = {} +VIEWERS = 0 +LOCK = threading.Lock() +STOP = None +HTTPD = None +GO2RTC = None +TMPDIR = None +X11 = None +SCREEN_W = 1280 +SCREEN_H = 720 +PLAYER_HTML = b"" +CSP = ( + "default-src 'self'; " + "connect-src 'self' ws: wss:; " + "media-src 'self' blob:; " + "img-src 'self' data:; " + "style-src 'self'; " + "script-src 'self'; " + "base-uri 'none'; " + "form-action 'self'; " + "frame-ancestors 'none'" +) + + +def log(msg): + print(msg, flush=True) + + +def state_write(): + if not ARGS.statefile: + return + with LOCK: + viewers = VIEWERS + data = { + "pid": os.getpid(), + "instance": ARGS.instance, + "url": "%s://%s:%d" % ("https" if ARGS.cert else "http", ARGS.bind, ARGS.port), + "started": ARGS.started, + "encoder": ARGS.encoder, + "transport": ARGS.transport, + "viewers": viewers, + "view_only": bool(ARGS.view_only), + "ws_port": ARGS.ws_port, + "go2rtc_pid": GO2RTC.pid if GO2RTC is not None else 0, + } + tmp = ARGS.statefile + ".tmp" + try: + with open(tmp, "w", encoding="utf-8") as fh: + json.dump(data, fh) + os.replace(tmp, ARGS.statefile) + except OSError: + pass + + +def cookie_token(header): + if not header: + return "" + jar = SimpleCookie() + try: + jar.load(header) + except Exception: + return "" + morsel = jar.get("lfa_web") + return morsel.value if morsel else "" + + +def session_ok(header): + token = cookie_token(header) + if not token: + return False + now = time.time() + with LOCK: + expiry = SESSIONS.get(token) + if not expiry or expiry < now: + SESSIONS.pop(token, None) + return False + return True + + +def origin_ok(origin, host_header=""): + if not origin: + return True + try: + parts = urlsplit(origin) + except ValueError: + return False + if parts.scheme not in ("http", "https"): + return False + try: + port = parts.port + except ValueError: + return False + if port not in (ARGS.port, ARGS.ws_port): + return False + request_host = (host_header or "").rsplit(":", 1)[0] + return parts.hostname in (ARGS.bind, "localhost", request_host) + + +def rate_ok(ip): + now = time.time() + with LOCK: + recent = [t for t in ATTEMPTS.get(ip, []) if now - t < 60] + if len(recent) >= 5: + ATTEMPTS[ip] = recent + return False + recent.append(now) + ATTEMPTS[ip] = recent + # Drop idle addresses so the dict cannot grow without bound. + if len(ATTEMPTS) > 256: + for key in [k for k, v in ATTEMPTS.items() if not v or now - v[-1] > 600]: + ATTEMPTS.pop(key, None) + return True + + +class Handler(BaseHTTPRequestHandler): + server_version = "LFAWeb/1" + protocol_version = "HTTP/1.1" + + def log_message(self, fmt, *args): + log("%s - %s" % (self.client_address[0], fmt % args)) + + def _send(self, status, body, ctype="text/html; charset=utf-8", headers=None): + if isinstance(body, str): + body = body.encode("utf-8") + self.send_response(status) + self.send_header("Content-Type", ctype) + self.send_header("Content-Length", str(len(body))) + self.send_header("Cache-Control", "no-store") + self.send_header("X-Content-Type-Options", "nosniff") + self.send_header("Referrer-Policy", "no-referrer") + self.send_header("X-Frame-Options", "DENY") + if ctype.startswith("text/html"): + self.send_header("Content-Security-Policy", CSP) + for key, value in (headers or []): + self.send_header(key, value) + self.end_headers() + if self.command != "HEAD": + self.wfile.write(body) + + def _redirect(self, location, headers=None): + self.send_response(303) + self.send_header("Location", location) + self.send_header("Content-Length", "0") + for key, value in (headers or []): + self.send_header(key, value) + self.end_headers() + + def _authed(self): + return session_ok(self.headers.get("Cookie", "")) + + def _static(self, name, ctype): + path = Path(ARGS.web_root) / name + try: + body = path.read_bytes() + except OSError: + self._send(404, "not found", "text/plain") + return + self._send(200, body, ctype) + + def do_GET(self): + path = self.path.split("?", 1)[0] + if path == "/health": + self._send(200, "ok", "text/plain") + return + if path in ("/app.js", "/login.js"): + self._static(path.lstrip("/"), "application/javascript; charset=utf-8") + return + if path == "/style.css": + self._static("style.css", "text/css; charset=utf-8") + return + if path == "/logout": + self._redirect("/", [("Set-Cookie", "lfa_web=; Path=/; Max-Age=0; SameSite=Strict")]) + return + if path not in ("/", "/index.html"): + self._send(404, "not found", "text/plain") + return + if not self._authed(): + self._static("login.html", "text/html; charset=utf-8") + return + self._send(200, PLAYER_HTML, "text/html; charset=utf-8") + + def do_POST(self): + path = self.path.split("?", 1)[0] + try: + length = int(self.headers.get("Content-Length", "0") or "0") + except ValueError: + length = 0 + if length < 0 or length > (1 << 20): + self._send(413, "request too large", "text/plain") + return + body = self.rfile.read(length) if length else b"" + if path == "/login": + ip = self.client_address[0] + if not rate_ok(ip): + self._send(429, "Too many attempts. Wait a minute.", "text/plain") + return + try: + code = parse_qs(body.decode("utf-8", "replace")).get("code", [""])[0].strip() + except Exception: + code = "" + time.sleep(0.2) + if hmac.compare_digest(code, PASSCODE): + token = secrets.token_urlsafe(32) + with LOCK: + SESSIONS[token] = time.time() + 12 * 3600 + cookie = "lfa_web=%s; Path=/; HttpOnly; SameSite=Strict" % token + if ARGS.cert: + cookie += "; Secure" + self._redirect("/", [("Set-Cookie", cookie)]) + else: + self._redirect("/?error=1") + return + if path == "/api/webrtc": + if not self._authed(): + self._send(401, "unauthorized", "text/plain") + return + url = "http://127.0.0.1:1984/api/webrtc?src=screen" + req = urllib.request.Request( + url, + data=body, + method="POST", + headers={"Content-Type": self.headers.get("Content-Type", "application/sdp")}, + ) + try: + with urllib.request.urlopen(req, timeout=20) as resp: + answer = resp.read() + self._send(resp.status, answer, resp.headers.get("Content-Type", "application/sdp")) + except urllib.error.HTTPError as exc: + self._send(exc.code, exc.read(), "text/plain") + except Exception as exc: + self._send(502, "go2rtc: %s" % exc, "text/plain") + return + self._send(404, "not found", "text/plain") + + def do_HEAD(self): + self.do_GET() + + +def split_annexb(buf): + """Split an Annex-B byte buffer into complete NAL units. + + Returns (nals, remainder). The last NAL is held until its next start code + arrives, so a chunk boundary never cuts a NAL in half. + """ + nals = [] + pos = 0 + while True: + start = buf.find(b"\x00\x00\x01", pos) + if start < 0: + break + nxt = buf.find(b"\x00\x00\x01", start + 3) + if nxt < 0: + break + nal = buf[start + 3:nxt] + if nal.endswith(b"\x00"): + nal = nal[:-1] + if nal: + nals.append(nal) + pos = nxt + if pos == 0: + return nals, buf[-2:] if len(buf) > 2 else buf + return nals, buf[pos:] + + +def codec_string(sps): + if sps and len(sps) >= 4: + return "avc1.%02X%02X%02X" % (sps[1], sps[2], sps[3]) + return "avc1.42E01F" + + +def ffmpeg_command(): + if ARGS.encoder == "mediacodec": + enc = ["-c:v", "h264_mediacodec", "-b:v", "4M", + "-g", str(ARGS.fps), "-bf", "0"] + else: + enc = ["-c:v", "libx264", "-preset", "ultrafast", "-tune", "zerolatency", + "-b:v", "4M", "-g", str(ARGS.fps), "-bf", "0", "-pix_fmt", "yuv420p"] + capture = getattr(ARGS, "capture_size", "") or ARGS.size + cmd = [ + ARGS.ffmpeg, "-hide_banner", "-loglevel", "warning", + "-fflags", "nobuffer", "-flags", "low_delay", + "-f", ARGS.grab, "-framerate", str(ARGS.fps), + "-video_size", capture, "-i", ARGS.display, + ] + if capture != ARGS.size: + cmd += ["-vf", "scale=%d:%d:flags=fast_bilinear" % (ARGS.width, ARGS.height)] + cmd += [*enc, "-flush_packets", "1", "-f", "h264", "pipe:1"] + return cmd + + +async def drain_stderr(stream): + while True: + line = await stream.readline() + if not line: + return + log("ffmpeg: %s" % line.decode("utf-8", "replace").rstrip()) + + +async def video_loop(websocket): + proc = None + stderr_task = None + try: + proc = await asyncio.create_subprocess_exec( + *ffmpeg_command(), + stdout=asyncio.subprocess.PIPE, + stderr=asyncio.subprocess.PIPE, + ) + stderr_task = asyncio.create_task(drain_stderr(proc.stderr)) + buf = b"" + sps = b"" + pps = b"" + first = True + last_ts = 0 + while True: + chunk = await proc.stdout.read(65536) + if not chunk: + break + buf += chunk + nals, buf = split_annexb(buf) + for nal in nals: + nal_type = nal[0] & 0x1F + if nal_type == 7: + sps = nal + continue + if nal_type == 8: + pps = nal + continue + if nal_type not in (1, 5): + continue + if first: + await websocket.send(json.dumps({ + "t": "config", + "transport": "webcodecs", + "codec": codec_string(sps), + "width": ARGS.width, + "height": ARGS.height, + })) + first = False + payload = b"" + if nal_type == 5: + if sps: + payload += b"\x00\x00\x00\x01" + sps + if pps: + payload += b"\x00\x00\x00\x01" + pps + payload += b"\x00\x00\x00\x01" + nal + ts = int(time.monotonic() * 1_000_000) + if ts <= last_ts: + ts = last_ts + 1 + last_ts = ts + header = bytes([1 if nal_type == 5 else 0]) + ts.to_bytes(8, "big") + await websocket.send(header + payload) + if not first: + log("video stream ended") + except asyncio.CancelledError: + raise + except Exception as exc: + log("video: %s" % exc) + finally: + if proc is not None: + try: + proc.terminate() + except ProcessLookupError: + pass + try: + await asyncio.wait_for(proc.wait(), 5) + except asyncio.TimeoutError: + try: + proc.kill() + except ProcessLookupError: + pass + if stderr_task is not None: + stderr_task.cancel() + try: + await websocket.close() + except Exception: + pass + + +async def input_loop(websocket): + async for message in websocket: + if ARGS.view_only or isinstance(message, bytes): + continue + try: + event = json.loads(message) + except ValueError: + continue + if isinstance(event, dict): + inject(event) + + +async def ws_handler(websocket, *_): + global VIEWERS + request = getattr(websocket, "request", None) + headers = getattr(request, "headers", None) + if headers is None: + headers = getattr(websocket, "request_headers", {}) + cookie = headers.get("Cookie", "") + origin = headers.get("Origin", "") + if not session_ok(cookie) or not origin_ok(origin, headers.get("Host", "")): + await websocket.close(code=1008) + return + with LOCK: + VIEWERS += 1 + count = VIEWERS + state_write() + log("viewer joined (%d active)" % count) + tasks = [asyncio.create_task(input_loop(websocket))] + if ARGS.transport == "webcodecs": + tasks.append(asyncio.create_task(video_loop(websocket))) + try: + await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED) + finally: + for task in tasks: + task.cancel() + await asyncio.gather(*tasks, return_exceptions=True) + with LOCK: + VIEWERS = max(0, VIEWERS - 1) + count = VIEWERS + state_write() + log("viewer left (%d active)" % count) + + +def keycode(event): + if X11 is None or XK is None: + return 0 + key = event.get("key", "") + special = { + "Enter": "Return", "Backspace": "BackSpace", "Tab": "Tab", + "Escape": "Escape", "Delete": "Delete", "Insert": "Insert", + "Home": "Home", "End": "End", "PageUp": "Prior", "PageDown": "Next", + "ArrowUp": "Up", "ArrowDown": "Down", "ArrowLeft": "Left", + "ArrowRight": "Right", "Control": "Control_L", "Shift": "Shift_L", + "Alt": "Alt_L", "Meta": "Super_L", "CapsLock": "Caps_Lock", + "NumLock": "Num_Lock", "ContextMenu": "Menu", "Pause": "Pause", + "PrintScreen": "Print", "ScrollLock": "Scroll_Lock", + } + sym = 0 + if key in special: + sym = XK.string_to_keysym(special[key]) + elif len(key) == 1: + # ASCII and Latin-1 code points are their own keysyms. Uppercase and + # shifted punctuation map to the same physical key as the base char; + # the browser sends the Shift keydown first, so the result is correct. + point = ord(key) + if 0x20 <= point <= 0x7E or 0xA0 <= point <= 0xFF: + sym = point + elif len(key) <= 4 and key.startswith("F") and key[1:].isdigit(): + sym = XK.string_to_keysym(key) + if not sym: + return 0 + return X11.keysym_to_keycode(sym) + + +def inject(event): + if X11 is None or xtest is None: + return + kind = event.get("t") + try: + if kind == "m": + x = int(float(event.get("x", 0)) * (SCREEN_W - 1)) + y = int(float(event.get("y", 0)) * (SCREEN_H - 1)) + x = max(0, min(SCREEN_W - 1, x)) + y = max(0, min(SCREEN_H - 1, y)) + xtest.fake_input(X11, X.MotionNotify, x=x, y=y) + elif kind == "b": + button = int(event.get("button", 1)) + if 1 <= button <= 9: + xtest.fake_input( + X11, X.ButtonPress if event.get("down") else X.ButtonRelease, button + ) + elif kind == "w": + dy = float(event.get("dy", 0)) + dx = float(event.get("dx", 0)) + if dy: + button = 4 if dy < 0 else 5 + xtest.fake_input(X11, X.ButtonPress, button) + xtest.fake_input(X11, X.ButtonRelease, button) + if dx: + button = 6 if dx < 0 else 7 + xtest.fake_input(X11, X.ButtonPress, button) + xtest.fake_input(X11, X.ButtonRelease, button) + elif kind in ("kd", "ku"): + code = keycode(event) + if code: + xtest.fake_input(X11, X.KeyPress if kind == "kd" else X.KeyRelease, code) + X11.sync() + except Exception: + pass + + +def children(pid): + try: + with open("/proc/%d/task/%d/children" % (pid, pid), encoding="ascii") as fh: + return [int(x) for x in fh.read().split()] + except (OSError, ValueError): + return [] + + +def process_tree(pid): + out = [] + for child in children(pid): + out.append(child) + out.extend(process_tree(child)) + return out + + +def start_go2rtc(): + global GO2RTC + logf = open(os.path.join(TMPDIR, "go2rtc.log"), "ab", buffering=0) + env = dict(os.environ) + env["DISPLAY"] = ARGS.display + GO2RTC = subprocess.Popen( + [ARGS.go2rtc, "-config", ARGS.go2rtc_config], + stdout=logf, + stderr=logf, + env=env, + start_new_session=True, + ) + for _ in range(50): + if GO2RTC.poll() is not None: + break + try: + with urllib.request.urlopen("http://127.0.0.1:1984/api", timeout=1): + log("go2rtc ready") + return True + except Exception: + time.sleep(0.2) + tail = "" + try: + tail = Path(os.path.join(TMPDIR, "go2rtc.log")).read_text(errors="replace")[-800:] + except OSError: + pass + log("go2rtc did not start. %s" % tail) + return False + + +def stop_go2rtc(): + if GO2RTC is None: + return + tree = process_tree(GO2RTC.pid) + try: + GO2RTC.terminate() + GO2RTC.wait(timeout=5) + except Exception: + try: + GO2RTC.kill() + except Exception: + pass + for pid in tree: + try: + os.kill(pid, signal.SIGTERM) + except OSError: + pass + + +def make_ssl(): + if not ARGS.cert: + return None + ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) + ctx.load_cert_chain(ARGS.cert, ARGS.key) + return ctx + + +def render_player(): + global PLAYER_HTML + path = Path(ARGS.web_root) / "player.html" + html = path.read_text(encoding="utf-8") + html = html.replace("{{WS_PORT}}", str(ARGS.ws_port)) + html = html.replace("{{WS_SCHEME}}", "wss" if ARGS.cert else "ws") + html = html.replace("{{VIEW_ONLY}}", "true" if ARGS.view_only else "false") + html = html.replace("{{TRANSPORT}}", ARGS.transport) + html = html.replace("{{INSTANCE}}", ARGS.instance) + html = html.replace("{{WIDTH}}", str(ARGS.width)) + html = html.replace("{{HEIGHT}}", str(ARGS.height)) + PLAYER_HTML = html.encode("utf-8") + + +async def serve(): + global STOP + STOP = asyncio.Event() + loop = asyncio.get_running_loop() + for sig in (signal.SIGINT, signal.SIGTERM): + try: + loop.add_signal_handler(sig, STOP.set) + except NotImplementedError: + pass + ssl_ctx = make_ssl() + async with websockets.serve( + ws_handler, + ARGS.bind, + ARGS.ws_port, + ssl=ssl_ctx, + max_size=1 << 20, + ping_interval=20, + ): + log("websocket channel on %s:%d" % (ARGS.bind, ARGS.ws_port)) + await STOP.wait() + return 0 + + +def main(): + global ARGS, PASSCODE, TMPDIR, X11, SCREEN_W, SCREEN_H, HTTPD + parser = argparse.ArgumentParser() + parser.add_argument("--bind", required=True) + parser.add_argument("--port", type=int, default=8765) + parser.add_argument("--ws-port", type=int, default=8766) + parser.add_argument("--display", default=":1") + parser.add_argument("--size", default="1280x720") + parser.add_argument("--capture-size", default="") + parser.add_argument("--fps", type=int, default=30) + parser.add_argument("--encoder", choices=("mediacodec", "x264"), default="x264") + parser.add_argument("--transport", choices=("webcodecs", "webrtc"), default="webcodecs") + parser.add_argument("--ffmpeg", default="ffmpeg") + parser.add_argument("--grab", default="xcbgrab") + parser.add_argument("--web-root", required=True) + parser.add_argument("--go2rtc", default="") + parser.add_argument("--go2rtc-config", default="") + parser.add_argument("--instance", default="") + parser.add_argument("--cert", default="") + parser.add_argument("--key", default="") + parser.add_argument("--pidfile", default="") + parser.add_argument("--statefile", default="") + parser.add_argument("--view-only", action="store_true") + ARGS = parser.parse_args() + ARGS.started = int(time.time()) + if ARGS.size in ("", "auto"): + ARGS.size = ARGS.capture_size or "1280x720" + if not ARGS.capture_size: + ARGS.capture_size = ARGS.size + ARGS.width, ARGS.height = (ARGS.size.split("x", 1) + ["720"])[:2] + try: + ARGS.width = int(ARGS.width) + ARGS.height = int(ARGS.height) + except ValueError: + ARGS.width, ARGS.height = 1280, 720 + + PASSCODE = sys.stdin.readline().strip() + if not PASSCODE: + log("no passcode on stdin") + return 2 + if websockets is None: + log("python websockets module is missing (pip install websockets)") + return 2 + if ARGS.transport == "webrtc" and (not ARGS.go2rtc or not ARGS.go2rtc_config): + log("webrtc transport needs --go2rtc and --go2rtc-config") + return 2 + + TMPDIR = tempfile.mkdtemp(prefix="lfa-web.") + if ARGS.pidfile: + Path(ARGS.pidfile).parent.mkdir(parents=True, exist_ok=True) + Path(ARGS.pidfile).write_text(str(os.getpid()), encoding="utf-8") + + rc = 1 + try: + render_player() + except OSError as exc: + log("player template: %s" % exc) + shutil.rmtree(TMPDIR, ignore_errors=True) + return 1 + + if xdisplay is not None: + try: + X11 = xdisplay.Display(ARGS.display) + SCREEN_W = X11.screen().width_in_pixels + SCREEN_H = X11.screen().height_in_pixels + except Exception as exc: + log("X11 input unavailable: %s" % exc) + X11 = None + + try: + if ARGS.transport == "webrtc" and not start_go2rtc(): + return 1 + ssl_ctx = make_ssl() + HTTPD = ThreadingHTTPServer((ARGS.bind, ARGS.port), Handler) + HTTPD.daemon_threads = True + if ssl_ctx is not None: + HTTPD.socket = ssl_ctx.wrap_socket(HTTPD.socket, server_side=True) + thread = threading.Thread(target=HTTPD.serve_forever, daemon=True) + thread.start() + state_write() + log("web server on %s:%d" % (ARGS.bind, ARGS.port)) + rc = asyncio.run(serve()) + finally: + try: + if HTTPD is not None: + HTTPD.shutdown() + HTTPD.server_close() + except Exception: + pass + stop_go2rtc() + if ARGS.pidfile: + try: + os.unlink(ARGS.pidfile) + except OSError: + pass + if ARGS.statefile: + try: + os.unlink(ARGS.statefile) + except OSError: + pass + if TMPDIR: + shutil.rmtree(TMPDIR, ignore_errors=True) + return rc + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/web/style.css b/web/style.css new file mode 100644 index 0000000..ff70729 --- /dev/null +++ b/web/style.css @@ -0,0 +1,154 @@ +:root { + --bg: #0b0f14; + --panel: #131a22; + --line: #243040; + --text: #e7edf4; + --muted: #8b9aab; + --accent: #5cc8ff; + --danger: #ff7b72; +} + +* { box-sizing: border-box; } + +[hidden] { display: none !important; } + +html, body { + margin: 0; + min-height: 100%; + background: var(--bg); + color: var(--text); + font: 15px/1.5 system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; +} + +h1 { font-size: 1.35rem; margin: 0 0 .35rem; letter-spacing: -.01em; } +p { margin: .4rem 0; } +.muted { color: var(--muted); } +.error { color: var(--danger); margin-top: .5rem; } +.hint { color: var(--muted); font-size: .85rem; margin-top: 1rem; } + +button { + appearance: none; + border: 1px solid var(--line); + background: #1a2430; + color: var(--text); + border-radius: 9px; + padding: .55rem .9rem; + font: inherit; + cursor: pointer; +} +button:hover { border-color: var(--accent); } +button:active { transform: translateY(1px); } + +input { + width: 100%; + margin-top: .35rem; + padding: .7rem .8rem; + border: 1px solid var(--line); + border-radius: 9px; + background: #0e141b; + color: var(--text); + font: 600 1.4rem/1.2 ui-monospace, "SFMono-Regular", Menlo, monospace; + letter-spacing: .28em; + text-transform: none; +} +input:focus { outline: 2px solid var(--accent); outline-offset: 1px; } + +/* Login */ +body.login { + display: grid; + place-items: center; + padding: 1.25rem; +} +.card { + width: min(26rem, 100%); + padding: 1.5rem; + background: var(--panel); + border: 1px solid var(--line); + border-radius: 16px; + box-shadow: 0 24px 70px rgba(0, 0, 0, .45); +} +.card label { display: block; margin-top: 1rem; color: var(--muted); font-size: .85rem; } +.card button[type="submit"] { + width: 100%; + margin-top: 1rem; + background: var(--accent); + border-color: var(--accent); + color: #04121c; + font-weight: 700; +} + +/* Player */ +body.player { overflow: hidden; } + +.stage { + position: fixed; + inset: 0; + background: #000; + display: grid; + place-items: center; + touch-action: none; + user-select: none; +} + +#screen, .screen { + width: 100%; + height: 100%; + object-fit: contain; + background: #000; + cursor: default; +} + +.overlay { + position: absolute; + inset: 0; + display: grid; + place-items: center; + background: rgba(4, 8, 12, .72); + backdrop-filter: blur(2px); +} +.overlay-card { + text-align: center; + padding: 1.4rem 1.6rem; + background: var(--panel); + border: 1px solid var(--line); + border-radius: 14px; + max-width: 22rem; +} + +.hud { + position: absolute; + top: .6rem; + left: .6rem; + display: flex; + gap: .6rem; + padding: .3rem .55rem; + border-radius: 8px; + background: rgba(4, 8, 12, .6); + color: var(--muted); + font: 12px/1.2 ui-monospace, "SFMono-Regular", Menlo, monospace; + pointer-events: none; +} + +.bar { + position: absolute; + left: 0; + right: 0; + bottom: 0; + display: flex; + align-items: center; + gap: .75rem; + padding: .45rem .7rem; + background: linear-gradient(to top, rgba(4, 8, 12, .78), transparent); + opacity: 0; + transition: opacity .18s ease; +} +.stage:hover .bar, .stage:focus-within .bar { opacity: 1; } +.bar .name { font-weight: 600; } +.bar .spacer { flex: 1; } +.bar .muted { font-size: .8rem; } +.bar button { padding: .35rem .7rem; font-size: .85rem; } + +@media (max-width: 640px) { + .card { padding: 1.15rem; } + input { font-size: 1.25rem; } +} From d90326c9069ddcf0db1751e6e9111f5c64e40349 Mon Sep 17 00:00:00 2001 From: pdev <300827144+pdev-labs@users.noreply.github.com> Date: Mon, 30 Nov 2026 10:54:52 +0530 Subject: [PATCH 02/10] web: probe the display instead of trusting a stale socket A killed X server can leave $PREFIX/tmp/.X11-unix/X1 behind. The old check accepted the socket and started ffmpeg against a dead display. Probe with xdpyinfo or python-xlib first and fall back to the socket only when neither tool is available. --- lib/lfa-web.sh | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/lib/lfa-web.sh b/lib/lfa-web.sh index 95d11f0..bb3d6c4 100644 --- a/lib/lfa-web.sh +++ b/lib/lfa-web.sh @@ -347,8 +347,15 @@ lfa_web_display_ok() { # display, e.g. :1 if [ "${LFA_WEB_SKIP_DISPLAY:-0}" = "1" ]; then return 0 fi + # A socket file can survive a killed server. Probe the display first so a + # stale socket does not send ffmpeg at a dead display. if command -v xdpyinfo >/dev/null 2>&1; then DISPLAY="$_disp" xdpyinfo >/dev/null 2>&1 && return 0 + return 1 + fi + if command -v python3 >/dev/null 2>&1 && python3 -c 'import Xlib' >/dev/null 2>&1; then + DISPLAY="$_disp" python3 -c 'from Xlib import display; display.Display()' >/dev/null 2>&1 && return 0 + return 1 fi for _sock in "$(lfa_web_prefix)/tmp/.X11-unix/X$_d" "/tmp/.X11-unix/X$_d"; do [ -S "$_sock" ] && return 0 From d059ad635c20d51986d3a08afdb26f6335cd8bdb Mon Sep 17 00:00:00 2001 From: pdev <300827144+pdev-labs@users.noreply.github.com> Date: Mon, 30 Nov 2026 13:24:19 +0530 Subject: [PATCH 03/10] web: capture the current screen size for each viewer Termux:X11 resizes its virtual screen when the Android window changes. The share read the size once at startup, so a viewer that connected after a resize made ffmpeg fail with "Capture area ... outside the screen size", which the player showed as a reconnect loop. Run ffmpeg without -video_size so x11grab reads the current screen, and let the canvas take its size from the decoded frames. --size now scales the output instead of cropping the capture. --- docs/ARCHITECTURE.md | 6 +++++- docs/TROUBLESHOOTING.md | 7 +++++++ lib/lfa-web.sh | 29 ++++++++++------------------- web/app.js | 12 +++++++----- web/server.py | 18 +++++++++++------- 5 files changed, 40 insertions(+), 32 deletions(-) diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index c1b91b1..83407b3 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -276,7 +276,11 @@ The default transport sends H.264 over the same authenticated WebSocket that carries input. The browser configures a `VideoDecoder` with the SPS profile and level, feeds it Annex-B NAL units, and draws each `VideoFrame` to a canvas. Each viewer gets its own ffmpeg process, so a second viewer does not disturb -the first. `--transport webrtc` keeps the older path: +the first. ffmpeg omits `-video_size` unless a caller sets one, so x11grab +reads the current screen size. Termux:X11 resizes its virtual screen when the +Android window changes, and a size read at startup can be stale by the time a +viewer connects. `--size WxH` adds a scale filter to the output instead of +cropping the capture. `--transport webrtc` keeps the older path: ``` ffmpeg -> RTSP 127.0.0.1:8554 -> go2rtc -> WebRTC/UDP :8555 -> browser diff --git a/docs/TROUBLESHOOTING.md b/docs/TROUBLESHOOTING.md index da159db..cd2dd7a 100644 --- a/docs/TROUBLESHOOTING.md +++ b/docs/TROUBLESHOOTING.md @@ -850,6 +850,13 @@ connection may be blocked between the two devices; many guest Wi-Fi networks block client-to-client traffic. Put both devices on the same normal Wi-Fi network, or use the phone's hotspot and connect the viewer to it. +If the player alternates between "Waiting for video" and "Connection lost. +Reconnecting.", the WebSocket is connected but ffmpeg is exiting. The log +usually names the reason. A common one is a capture size that no longer +matches the screen: Termux:X11 changes its virtual screen when the Android +window changes, so keep the Termux:X11 app open while viewing, or reconnect +after resizing it. + If video works but input does not, `python-xlib` is missing. Install it with `pkg install python-xlib` and restart the share. Without it the server still serves video; it just cannot inject XTEST events. diff --git a/lib/lfa-web.sh b/lib/lfa-web.sh index bb3d6c4..81898fd 100644 --- a/lib/lfa-web.sh +++ b/lib/lfa-web.sh @@ -621,7 +621,7 @@ lfa_web_start() { local _size="auto" _fps="30" _encoder="auto" _view_only=0 _http=0 local _transport="auto" local _detach=0 _display=":1" _code _cert _key _scheme _pid _i _ready=0 _rc=0 - local _statefile _pidfile _log _server _webroot _cfg _py _grab _ffmpeg _capture="" + local _statefile _pidfile _log _server _webroot _cfg _py _grab _ffmpeg _desc local -a _args=() while [ $# -gt 0 ]; do @@ -687,18 +687,6 @@ lfa_web_start() { return 1 fi - _capture="$(lfa_web_screen_size "$_display" || true)" - if [ -z "$_capture" ]; then - _capture="$_size" - fi - if [ "$_size" = "auto" ]; then - _size="$_capture" - fi - if [ "$_size" = "auto" ] || [ -z "$_size" ]; then - _size="1280x720" - _capture="1280x720" - fi - if [ "$_encoder" = "auto" ]; then if lfa_web_has_mediacodec; then _encoder="mediacodec" @@ -747,6 +735,10 @@ lfa_web_start() { fi if [ "$_transport" = "webrtc" ]; then + if [ "$_size" = "auto" ]; then + _size="$(lfa_web_screen_size "$_display" || true)" + [ -n "$_size" ] || _size="1280x720" + fi if ! lfa_web_go2rtc_ensure; then return 1 fi @@ -780,7 +772,7 @@ lfa_web_start() { fi _args=(--bind "$_bind" --port "$_port" --ws-port "$_wsport" - --display "$_display" --size "$_size" --capture-size "$_capture" + --display "$_display" --size "$_size" --fps "$_fps" --encoder "$_encoder" --transport "$_transport" --ffmpeg "$_ffmpeg" --grab "$_grab" --web-root "$_webroot" --instance "$_inst" --pidfile "$_pidfile" --statefile "$_statefile") @@ -823,13 +815,12 @@ lfa_web_start() { echo "Instance: $_inst" echo "URL: $_scheme://$_bind:$_port" echo "Passcode: $_code" + _desc="$_size" + [ "$_desc" = "auto" ] && _desc="native" if [ "$_encoder" = "mediacodec" ]; then - echo "Encoder: h264_mediacodec (hardware, ${_size}@${_fps})" + echo "Encoder: h264_mediacodec (hardware, ${_desc}@${_fps})" else - echo "Encoder: libx264 ultrafast (${_size}@${_fps})" - fi - if [ -n "$_capture" ] && [ "$_capture" != "$_size" ]; then - echo "Capture: ${_capture} scaled to ${_size}" + echo "Encoder: libx264 ultrafast (${_desc}@${_fps})" fi if [ "$_transport" = "webcodecs" ]; then echo "Transport: H.264 over WebSocket (WebCodecs)" diff --git a/web/app.js b/web/app.js index c60f880..483c076 100644 --- a/web/app.js +++ b/web/app.js @@ -106,9 +106,11 @@ } function drawFrame(frame) { - if (!canvas.width || !canvas.height) { - canvas.width = frame.displayWidth || cfg.width; - canvas.height = frame.displayHeight || cfg.height; + const width = frame.displayWidth || cfg.width; + const height = frame.displayHeight || cfg.height; + if (canvas.width !== width || canvas.height !== height) { + canvas.width = width; + canvas.height = height; } ctx.drawImage(frame, 0, 0, canvas.width, canvas.height); frame.close(); @@ -140,8 +142,8 @@ } catch (_) { decoder.configure(base); } - canvas.width = config.width || cfg.width; - canvas.height = config.height || cfg.height; + canvas.width = 0; + canvas.height = 0; canvas.hidden = false; video.hidden = true; } diff --git a/web/server.py b/web/server.py index 5df471c..ec8fcba 100644 --- a/web/server.py +++ b/web/server.py @@ -320,14 +320,19 @@ def ffmpeg_command(): else: enc = ["-c:v", "libx264", "-preset", "ultrafast", "-tune", "zerolatency", "-b:v", "4M", "-g", str(ARGS.fps), "-bf", "0", "-pix_fmt", "yuv420p"] - capture = getattr(ARGS, "capture_size", "") or ARGS.size + capture = getattr(ARGS, "capture_size", "") cmd = [ ARGS.ffmpeg, "-hide_banner", "-loglevel", "warning", "-fflags", "nobuffer", "-flags", "low_delay", "-f", ARGS.grab, "-framerate", str(ARGS.fps), - "-video_size", capture, "-i", ARGS.display, ] - if capture != ARGS.size: + # Without -video_size, x11grab reads the current screen size. Termux:X11 + # resizes its virtual screen when the Android window changes, so a size + # captured once at startup can be stale by the time ffmpeg runs. + if capture: + cmd += ["-video_size", capture] + cmd += ["-i", ARGS.display] + if getattr(ARGS, "scale", False): cmd += ["-vf", "scale=%d:%d:flags=fast_bilinear" % (ARGS.width, ARGS.height)] cmd += [*enc, "-flush_packets", "1", "-f", "h264", "pipe:1"] return cmd @@ -668,10 +673,9 @@ def main(): parser.add_argument("--view-only", action="store_true") ARGS = parser.parse_args() ARGS.started = int(time.time()) - if ARGS.size in ("", "auto"): - ARGS.size = ARGS.capture_size or "1280x720" - if not ARGS.capture_size: - ARGS.capture_size = ARGS.size + ARGS.scale = ARGS.size not in ("", "auto") + if not ARGS.scale: + ARGS.size = "1280x720" ARGS.width, ARGS.height = (ARGS.size.split("x", 1) + ["720"])[:2] try: ARGS.width = int(ARGS.width) From 7c61a0d90c8e7b15ae5263eb0c914f7c4ec43500 Mon Sep 17 00:00:00 2001 From: pdev <300827144+pdev-labs@users.noreply.github.com> Date: Tue, 1 Dec 2026 08:15:15 +0530 Subject: [PATCH 04/10] web: keep input alive across display restarts Reconnect the XTEST display when the desktop is restarted after the share starts, and read the root geometry for each pointer move so a resized screen still maps to the right pixels. Round the captured size to even dimensions so h264_mediacodec accepts screens with an odd height. Blur the player buttons after a click so they do not keep keyboard focus. --- web/app.js | 7 ++- web/server.py | 130 +++++++++++++++++++++++++++++++++----------------- 2 files changed, 92 insertions(+), 45 deletions(-) diff --git a/web/app.js b/web/app.js index 483c076..b144a64 100644 --- a/web/app.js +++ b/web/app.js @@ -293,7 +293,6 @@ window.addEventListener("keydown", (ev) => { if (cfg.viewOnly) return; - if (document.activeElement && document.activeElement.tagName === "BUTTON") return; if (ev.key === "Escape" && document.fullscreenElement) return; if (ev.metaKey) return; if (ev.ctrlKey && (ev.key === "F11" || ev.key === "F12")) return; @@ -316,6 +315,7 @@ }); full.addEventListener("click", async () => { + full.blur(); try { if (document.fullscreenElement) await document.exitFullscreen(); else await stage.requestFullscreen(); @@ -358,7 +358,10 @@ } setInterval(stats, 1000); - retry.addEventListener("click", reconnect); + retry.addEventListener("click", () => { + retry.blur(); + reconnect(); + }); document.addEventListener("visibilitychange", () => { if (!document.hidden && cfg.transport === "webrtc" && pc && pc.connectionState === "failed") { diff --git a/web/server.py b/web/server.py index ec8fcba..2f12e79 100644 --- a/web/server.py +++ b/web/server.py @@ -51,6 +51,8 @@ GO2RTC = None TMPDIR = None X11 = None +X11_LOCK = threading.Lock() +X11_WARN_AT = 0.0 SCREEN_W = 1280 SCREEN_H = 720 PLAYER_HTML = b"" @@ -334,6 +336,10 @@ def ffmpeg_command(): cmd += ["-i", ARGS.display] if getattr(ARGS, "scale", False): cmd += ["-vf", "scale=%d:%d:flags=fast_bilinear" % (ARGS.width, ARGS.height)] + else: + # h264_mediacodec rejects odd dimensions. Termux:X11 can have an odd + # height (for example 2103), so round down by at most one pixel. + cmd += ["-vf", "scale=trunc(iw/2)*2:trunc(ih/2)*2:flags=fast_bilinear"] cmd += [*enc, "-flush_packets", "1", "-f", "h264", "pipe:1"] return cmd @@ -470,6 +476,26 @@ async def ws_handler(websocket, *_): log("viewer left (%d active)" % count) +def x11_open(): + """Open (or reopen) the X display used for XTEST input.""" + global X11, SCREEN_W, SCREEN_H, X11_WARN_AT + if xdisplay is None: + return False + try: + X11 = xdisplay.Display(ARGS.display) + SCREEN_W = X11.screen().width_in_pixels + SCREEN_H = X11.screen().height_in_pixels + X11_WARN_AT = 0.0 + return True + except Exception as exc: + now = time.time() + if now - X11_WARN_AT > 30: + log("X11 input unavailable: %s" % exc) + X11_WARN_AT = now + X11 = None + return False + + def keycode(event): if X11 is None or XK is None: return 0 @@ -501,41 +527,61 @@ def keycode(event): return X11.keysym_to_keycode(sym) +def _inject(event): + kind = event.get("t") + if kind == "m": + # Read the root geometry for every move. Termux:X11 resizes its + # virtual screen, and stale dimensions put the pointer in the wrong + # place (or outside the screen). + geom = X11.screen().root.get_geometry() + width, height = geom.width, geom.height + x = int(float(event.get("x", 0)) * (width - 1)) + y = int(float(event.get("y", 0)) * (height - 1)) + x = max(0, min(width - 1, x)) + y = max(0, min(height - 1, y)) + xtest.fake_input(X11, X.MotionNotify, x=x, y=y) + elif kind == "b": + button = int(event.get("button", 1)) + if 1 <= button <= 9: + xtest.fake_input( + X11, X.ButtonPress if event.get("down") else X.ButtonRelease, button + ) + elif kind == "w": + dy = float(event.get("dy", 0)) + dx = float(event.get("dx", 0)) + if dy: + button = 4 if dy < 0 else 5 + xtest.fake_input(X11, X.ButtonPress, button) + xtest.fake_input(X11, X.ButtonRelease, button) + if dx: + button = 6 if dx < 0 else 7 + xtest.fake_input(X11, X.ButtonPress, button) + xtest.fake_input(X11, X.ButtonRelease, button) + elif kind in ("kd", "ku"): + code = keycode(event) + if code: + xtest.fake_input(X11, X.KeyPress if kind == "kd" else X.KeyRelease, code) + + def inject(event): - if X11 is None or xtest is None: + global X11 + if xtest is None: return - kind = event.get("t") - try: - if kind == "m": - x = int(float(event.get("x", 0)) * (SCREEN_W - 1)) - y = int(float(event.get("y", 0)) * (SCREEN_H - 1)) - x = max(0, min(SCREEN_W - 1, x)) - y = max(0, min(SCREEN_H - 1, y)) - xtest.fake_input(X11, X.MotionNotify, x=x, y=y) - elif kind == "b": - button = int(event.get("button", 1)) - if 1 <= button <= 9: - xtest.fake_input( - X11, X.ButtonPress if event.get("down") else X.ButtonRelease, button - ) - elif kind == "w": - dy = float(event.get("dy", 0)) - dx = float(event.get("dx", 0)) - if dy: - button = 4 if dy < 0 else 5 - xtest.fake_input(X11, X.ButtonPress, button) - xtest.fake_input(X11, X.ButtonRelease, button) - if dx: - button = 6 if dx < 0 else 7 - xtest.fake_input(X11, X.ButtonPress, button) - xtest.fake_input(X11, X.ButtonRelease, button) - elif kind in ("kd", "ku"): - code = keycode(event) - if code: - xtest.fake_input(X11, X.KeyPress if kind == "kd" else X.KeyRelease, code) - X11.sync() - except Exception: - pass + with X11_LOCK: + if X11 is None and not x11_open(): + return + try: + _inject(event) + X11.sync() + except Exception: + # The desktop may have been restarted after the share started. + X11 = None + if x11_open(): + try: + _inject(event) + X11.sync() + except Exception: + X11 = None def children(pid): @@ -676,12 +722,16 @@ def main(): ARGS.scale = ARGS.size not in ("", "auto") if not ARGS.scale: ARGS.size = "1280x720" - ARGS.width, ARGS.height = (ARGS.size.split("x", 1) + ["720"])[:2] try: - ARGS.width = int(ARGS.width) - ARGS.height = int(ARGS.height) + _w, _h = ARGS.size.split("x", 1) + ARGS.width = max(2, int(_w)) + ARGS.height = max(2, int(_h)) except ValueError: ARGS.width, ARGS.height = 1280, 720 + # h264_mediacodec rejects odd dimensions (crop_bottom must be even). + ARGS.width -= ARGS.width % 2 + ARGS.height -= ARGS.height % 2 + ARGS.size = "%dx%d" % (ARGS.width, ARGS.height) PASSCODE = sys.stdin.readline().strip() if not PASSCODE: @@ -708,13 +758,7 @@ def main(): return 1 if xdisplay is not None: - try: - X11 = xdisplay.Display(ARGS.display) - SCREEN_W = X11.screen().width_in_pixels - SCREEN_H = X11.screen().height_in_pixels - except Exception as exc: - log("X11 input unavailable: %s" % exc) - X11 = None + x11_open() try: if ARGS.transport == "webrtc" and not start_go2rtc(): From 4dfcabc439cf0248711eb1eb898e2a4b7e3f89bc Mon Sep 17 00:00:00 2001 From: pdev <300827144+pdev-labs@users.noreply.github.com> Date: Tue, 1 Dec 2026 13:37:49 +0530 Subject: [PATCH 05/10] web: add an MJPEG fallback for browsers without WebCodecs When VideoDecoder is missing, the player asks for ?mode=mjpeg on the same authenticated WebSocket that carries input. The server runs ffmpeg's mjpeg encoder, splits complete JPEG images, and sends them to the browser. The player draws them through an element, so any browser can view the desktop. It uses more bandwidth than the H.264 path. --- CHANGELOG.md | 7 +-- README.md | 6 ++- docs/ARCHITECTURE.md | 4 ++ docs/TROUBLESHOOTING.md | 7 ++- tests/test-all.sh | 6 +++ web/app.js | 68 +++++++++++++++++++++++++--- web/server.py | 99 +++++++++++++++++++++++++++++++++++++---- 7 files changed, 173 insertions(+), 24 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4f537d5..e8f2e75 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -22,9 +22,10 @@ tag names, define the order. See the table at the bottom. the share stops. `--view-only`, `--size`, `--fps`, `--encoder`, `--http`, `--detach`, and `--transport` adjust the share. The default transport sends H.264 over a WebSocket and decodes it with WebCodecs in the browser, which - works on Android. `--transport webrtc` uses go2rtc v1.9.15, downloaded on - first use after a SHA-256 check. Video uses `h264_mediacodec` when ffmpeg - supports it and falls back to `libx264 -preset ultrafast -tune zerolatency`. + works on Android. A browser without WebCodecs gets an MJPEG fallback. + `--transport webrtc` uses go2rtc v1.9.15, downloaded on first use after a + SHA-256 check. Video uses `h264_mediacodec` when ffmpeg supports it and falls + back to `libx264 -preset ultrafast -tune zerolatency`. The passcode stays in memory, and the only LAN listener is the Python server, which serves a self-signed HTTPS page by default. - Separate Android and external storage policies. Guided setup now offers diff --git a/README.md b/README.md index 51e208d..7153958 100644 --- a/README.md +++ b/README.md @@ -725,8 +725,10 @@ capture to that output size, which is useful on a large desktop. The phone's hardware encoder keeps CPU use low, and the browser decodes H.264 with its own hardware path when it has one. -WebCodecs needs Chrome 94+, Edge 94+, or Safari 16.4+. Firefox support depends -on the build. The viewer page says so when the browser lacks the API. +WebCodecs gives the lowest latency and needs Chrome 94+, Edge 94+, or Safari +16.4+. Firefox support depends on the build. A browser without WebCodecs +automatically gets an MJPEG fallback, which works in every browser but uses +more bandwidth. Use a WebCodecs browser when you can. `lfa web doctor` checks ffmpeg's X11 capture input (`x11grab` or `xcbgrab`) and H.264 encoders, the Python `websockets` and `python-xlib` modules, the diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 83407b3..ab9fdc3 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -275,6 +275,10 @@ Termux:X11 or Xvnc :1 The default transport sends H.264 over the same authenticated WebSocket that carries input. The browser configures a `VideoDecoder` with the SPS profile and level, feeds it Annex-B NAL units, and draws each `VideoFrame` to a canvas. +A browser without WebCodecs asks for `?mode=mjpeg` on the same socket; the +server then runs ffmpeg's `mjpeg` encoder and sends complete JPEG images, +which the player draws through an `` element. The fallback works +everywhere but spends more bandwidth than H.264. Each viewer gets its own ffmpeg process, so a second viewer does not disturb the first. ffmpeg omits `-video_size` unless a caller sets one, so x11grab reads the current screen size. Termux:X11 resizes its virtual screen when the diff --git a/docs/TROUBLESHOOTING.md b/docs/TROUBLESHOOTING.md index cd2dd7a..30846c9 100644 --- a/docs/TROUBLESHOOTING.md +++ b/docs/TROUBLESHOOTING.md @@ -838,10 +838,9 @@ accept the warning once. The certificate is self-signed and names the phone's Wi-Fi address. A browser that still refuses it can use `--http` on a trusted network. -If the page says the browser has no WebCodecs support, use Chrome 94+, Edge -94+, or Safari 16.4+. Firefox support depends on the build. The WebRTC -transport works in browsers without WebCodecs, but needs the phone-side go2rtc -path. +A browser without WebCodecs gets an MJPEG fallback automatically. It works in +every browser, but it sends more data than H.264. If it feels slow, switch to +Chrome 94+, Edge 94+, or Safari 16.4+ for the WebCodecs path. If the page loads but video stays black, check the phone log at `$PREFIX/var/lib/lfa-web/lfa-web-.log`. An ffmpeg error there means diff --git a/tests/test-all.sh b/tests/test-all.sh index 49702f9..4212db9 100755 --- a/tests/test-all.sh +++ b/tests/test-all.sh @@ -2571,6 +2571,12 @@ assert cmd[0] == "/x/ffmpeg" assert "x11grab" in cmd assert "h264_mediacodec" in cmd assert cmd[-1] == "pipe:1" +mj = mod.mjpeg_command() +assert "mjpeg" in mj +assert mj[-1] == "pipe:1" +frames, rest = mod.split_jpeg(b"\xff\xd8abc\xff\xd9\xff\xd8de") +assert frames == [b"\xff\xd8abc\xff\xd9"], frames +assert rest == b"\xff\xd8de", rest PY then pass=$((pass+1)); else fail=$((fail+1)); echo "FAIL: Y14 WebCodecs NAL/ffmpeg helpers"; fi diff --git a/web/app.js b/web/app.js index b144a64..7ac61b2 100644 --- a/web/app.js +++ b/web/app.js @@ -105,15 +105,12 @@ } } - function drawFrame(frame) { - const width = frame.displayWidth || cfg.width; - const height = frame.displayHeight || cfg.height; + function paint(width, height, source) { if (canvas.width !== width || canvas.height !== height) { canvas.width = width; canvas.height = height; } - ctx.drawImage(frame, 0, 0, canvas.width, canvas.height); - frame.close(); + ctx.drawImage(source, 0, 0, canvas.width, canvas.height); decodedFrames += 1; if (!overlay.hidden) { setStatus("", false); @@ -121,6 +118,13 @@ } } + function drawFrame(frame) { + paint(frame.displayWidth || frame.width || cfg.width, + frame.displayHeight || frame.height || cfg.height, + frame); + frame.close(); + } + function configureDecoder(config) { if (typeof VideoDecoder === "undefined") { setStatus("This browser has no WebCodecs support. Use Chrome, Edge, or Safari 16.4+.", true); @@ -174,7 +178,7 @@ ws = null; } if (typeof VideoDecoder === "undefined") { - setStatus("This browser has no WebCodecs support. Use Chrome, Edge, or Safari 16.4+.", true); + connectMjpeg(); return; } setStatus("Waiting for video...", true); @@ -203,6 +207,58 @@ }; } + function connectMjpeg() { + clearTimeout(retryTimer); + retry.hidden = true; + if (ws) { + try { ws.close(); } catch (_) { /* already closed */ } + ws = null; + } + setStatus("Using the MJPEG fallback. Waiting for video...", true); + canvas.width = 0; + canvas.height = 0; + canvas.hidden = false; + video.hidden = true; + const url = cfg.wsScheme + "://" + window.location.hostname + ":" + + cfg.wsPort + "/?mode=mjpeg"; + ws = new WebSocket(url); + ws.binaryType = "arraybuffer"; + const img = new Image(); + let busy = false; + ws.onopen = () => { control.textContent = "Control on"; }; + ws.onmessage = (event) => { + if (typeof event.data === "string") { + let msg; + try { msg = JSON.parse(event.data); } catch (_) { return; } + if (msg.t === "error") setStatus(msg.message || "Video error", true); + return; + } + if (busy) return; + busy = true; + decodedBytes += event.data.byteLength; + const objectUrl = URL.createObjectURL(new Blob([event.data], { type: "image/jpeg" })); + img.onload = () => { + URL.revokeObjectURL(objectUrl); + paint(img.naturalWidth || cfg.width, img.naturalHeight || cfg.height, img); + busy = false; + }; + img.onerror = () => { + URL.revokeObjectURL(objectUrl); + busy = false; + }; + img.src = objectUrl; + }; + ws.onclose = () => { + control.textContent = "Reconnecting"; + setStatus("Connection lost. Reconnecting...", true); + clearTimeout(wsTimer); + wsTimer = setTimeout(connectMjpeg, 2000); + }; + ws.onerror = () => { + try { ws.close(); } catch (_) { /* already closed */ } + }; + } + function connectInput() { if (cfg.viewOnly) { control.textContent = "View only"; diff --git a/web/server.py b/web/server.py index 2f12e79..fdc0bd0 100644 --- a/web/server.py +++ b/web/server.py @@ -315,13 +315,7 @@ def codec_string(sps): return "avc1.42E01F" -def ffmpeg_command(): - if ARGS.encoder == "mediacodec": - enc = ["-c:v", "h264_mediacodec", "-b:v", "4M", - "-g", str(ARGS.fps), "-bf", "0"] - else: - enc = ["-c:v", "libx264", "-preset", "ultrafast", "-tune", "zerolatency", - "-b:v", "4M", "-g", str(ARGS.fps), "-bf", "0", "-pix_fmt", "yuv420p"] +def ffmpeg_input(): capture = getattr(ARGS, "capture_size", "") cmd = [ ARGS.ffmpeg, "-hide_banner", "-loglevel", "warning", @@ -340,10 +334,41 @@ def ffmpeg_command(): # h264_mediacodec rejects odd dimensions. Termux:X11 can have an odd # height (for example 2103), so round down by at most one pixel. cmd += ["-vf", "scale=trunc(iw/2)*2:trunc(ih/2)*2:flags=fast_bilinear"] - cmd += [*enc, "-flush_packets", "1", "-f", "h264", "pipe:1"] return cmd +def ffmpeg_command(): + if ARGS.encoder == "mediacodec": + enc = ["-c:v", "h264_mediacodec", "-b:v", "4M", + "-g", str(ARGS.fps), "-bf", "0"] + else: + enc = ["-c:v", "libx264", "-preset", "ultrafast", "-tune", "zerolatency", + "-b:v", "4M", "-g", str(ARGS.fps), "-bf", "0", "-pix_fmt", "yuv420p"] + return ffmpeg_input() + [*enc, "-flush_packets", "1", "-f", "h264", "pipe:1"] + + +def mjpeg_command(): + return ffmpeg_input() + [ + "-c:v", "mjpeg", "-q:v", "7", "-pix_fmt", "yuvj420p", + "-flush_packets", "1", "-f", "mjpeg", "pipe:1", + ] + + +def split_jpeg(buf): + """Return complete JPEG images and the unfinished tail.""" + frames = [] + while True: + start = buf.find(b"\xff\xd8") + if start < 0: + return frames, b"" + end = buf.find(b"\xff\xd9", start + 2) + if end < 0: + return frames, buf[start:] + frames.append(buf[start:end + 2]) + buf = buf[end + 2:] + + + async def drain_stderr(stream): while True: line = await stream.readline() @@ -432,6 +457,54 @@ async def video_loop(websocket): pass +async def mjpeg_loop(websocket): + proc = None + stderr_task = None + try: + proc = await asyncio.create_subprocess_exec( + *mjpeg_command(), + stdout=asyncio.subprocess.PIPE, + stderr=asyncio.subprocess.PIPE, + ) + stderr_task = asyncio.create_task(drain_stderr(proc.stderr)) + buf = b"" + frames = 0 + while True: + chunk = await proc.stdout.read(65536) + if not chunk: + break + buf += chunk + images, buf = split_jpeg(buf) + for image in images: + await websocket.send(image) + frames += 1 + if frames: + log("mjpeg stream ended") + except asyncio.CancelledError: + raise + except Exception as exc: + log("mjpeg: %s" % exc) + finally: + if proc is not None: + try: + proc.terminate() + except ProcessLookupError: + pass + try: + await asyncio.wait_for(proc.wait(), 5) + except asyncio.TimeoutError: + try: + proc.kill() + except ProcessLookupError: + pass + if stderr_task is not None: + stderr_task.cancel() + try: + await websocket.close() + except Exception: + pass + + async def input_loop(websocket): async for message in websocket: if ARGS.view_only or isinstance(message, bytes): @@ -460,9 +533,17 @@ async def ws_handler(websocket, *_): count = VIEWERS state_write() log("viewer joined (%d active)" % count) + path = "" + if request is not None: + path = getattr(request, "path", "") or "" + else: + path = getattr(websocket, "path", "") or "" + mode = (parse_qs(urlsplit(path).query).get("mode", [""])[0] or ARGS.transport) tasks = [asyncio.create_task(input_loop(websocket))] - if ARGS.transport == "webcodecs": + if mode == "webcodecs": tasks.append(asyncio.create_task(video_loop(websocket))) + elif mode == "mjpeg": + tasks.append(asyncio.create_task(mjpeg_loop(websocket))) try: await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED) finally: From a094f61ef61af057dc5bf02f21a2991465d74959 Mon Sep 17 00:00:00 2001 From: pdev <300827144+pdev-labs@users.noreply.github.com> Date: Wed, 2 Dec 2026 12:37:24 +0530 Subject: [PATCH 06/10] web: allow blob images in the CSP The MJPEG fallback draws each frame from an with a blob: URL. img-src did not include blob:, so the browser blocked every frame and the player stayed on "Waiting for video". Add blob: to img-src. --- web/server.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/web/server.py b/web/server.py index fdc0bd0..1330b8a 100644 --- a/web/server.py +++ b/web/server.py @@ -60,7 +60,7 @@ "default-src 'self'; " "connect-src 'self' ws: wss:; " "media-src 'self' blob:; " - "img-src 'self' data:; " + "img-src 'self' data: blob:; " "style-src 'self'; " "script-src 'self'; " "base-uri 'none'; " From d1324086044430261a5d5cecdc6236b3027c9175 Mon Sep 17 00:00:00 2001 From: pdev <300827144+pdev-labs@users.noreply.github.com> Date: Wed, 2 Dec 2026 12:53:18 +0530 Subject: [PATCH 07/10] web: add a touch control panel to the viewer Touch devices show a floating menu with a relative touchpad, tap-to- position, mouse buttons, hold-drag, scrolling, arrows, and modifier latches. A text field opens the on-screen keyboard and translates its input into key events. Add the relative `mr` pointer event on the server. --- CHANGELOG.md | 8 +- README.md | 5 + docs/ARCHITECTURE.md | 5 +- web/app.js | 299 +++++++++++++++++++++++++++++++++++++++++-- web/player.html | 46 +++++++ web/server.py | 12 ++ web/style.css | 70 ++++++++++ 7 files changed, 430 insertions(+), 15 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e8f2e75..d0bc9e2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -23,9 +23,11 @@ tag names, define the order. See the table at the bottom. `--detach`, and `--transport` adjust the share. The default transport sends H.264 over a WebSocket and decodes it with WebCodecs in the browser, which works on Android. A browser without WebCodecs gets an MJPEG fallback. - `--transport webrtc` uses go2rtc v1.9.15, downloaded on first use after a - SHA-256 check. Video uses `h264_mediacodec` when ffmpeg supports it and falls - back to `libx264 -preset ultrafast -tune zerolatency`. + Phone and tablet viewers get a floating touch panel with a relative + touchpad, tap-to-position, mouse buttons, hold-drag, scrolling, and an + on-screen keyboard. `--transport webrtc` uses go2rtc v1.9.15, downloaded on + first use after a SHA-256 check. Video uses `h264_mediacodec` when ffmpeg + supports it and falls back to `libx264 -preset ultrafast -tune zerolatency`. The passcode stays in memory, and the only LAN listener is the Python server, which serves a self-signed HTTPS page by default. - Separate Android and external storage policies. Guided setup now offers diff --git a/README.md b/README.md index 7153958..9d7a390 100644 --- a/README.md +++ b/README.md @@ -730,6 +730,11 @@ WebCodecs gives the lowest latency and needs Chrome 94+, Edge 94+, or Safari automatically gets an MJPEG fallback, which works in every browser but uses more bandwidth. Use a WebCodecs browser when you can. +A phone or tablet viewer shows a floating menu button. The touch panel +switches between a relative touchpad and tap-to-position pointer mode, and +adds left, right, and middle click, hold-drag, scrolling, arrow and modifier +keys, plus a text field that opens the on-screen keyboard. + `lfa web doctor` checks ffmpeg's X11 capture input (`x11grab` or `xcbgrab`) and H.264 encoders, the Python `websockets` and `python-xlib` modules, the display, and the LAN address. It also reports go2rtc, which only the optional diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index ab9fdc3..7d6feb4 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -307,7 +307,10 @@ Input arrives as small JSON messages on the WebSocket and is injected with XTEST through `python-xlib`. Pointer positions are normalized in the browser and scaled to the X screen, so a viewer with a different window size still lands on the right pixel. Modifier keys are sent as ordinary key events, so -Shift and Ctrl behave like the physical keyboard. +Shift and Ctrl behave like the physical keyboard. Touch viewers get a +relative touchpad mode (`mr` deltas), a tap-to-position mode, mouse buttons, a +hold-drag latch, and an on-screen keyboard whose text is translated into key +presses. The passcode is 8 characters from uppercase letters and digits, generated from `/dev/urandom`, with at least one letter and one digit. `0/O` and `1/I` diff --git a/web/app.js b/web/app.js index 7ac61b2..4a2904a 100644 --- a/web/app.js +++ b/web/app.js @@ -24,6 +24,18 @@ const hudRate = document.getElementById("hud-rate"); const full = document.getElementById("full"); const control = document.getElementById("control"); + const menu = document.getElementById("menu"); + const panel = document.getElementById("touch-panel"); + const touchClose = document.getElementById("touch-close"); + const touchFull = document.getElementById("touch-full"); + const touchDrag = document.getElementById("touch-drag"); + const softInput = document.getElementById("soft-input"); + const touchStatus = document.getElementById("touch-status"); + + const isTouch = navigator.maxTouchPoints > 0 || + (window.matchMedia && window.matchMedia("(pointer: coarse)").matches); + if (isTouch) body.classList.add("touch"); + let pointerMode = isTouch ? "touchpad" : "absolute"; let pc = null; let ws = null; @@ -41,6 +53,11 @@ overlay.hidden = !show; } + function setControl(text) { + control.textContent = text; + if (touchStatus) touchStatus.textContent = text; + } + function reconnect() { if (cfg.transport === "webcodecs") connectWebCodecs(); else connectVideo(); @@ -185,7 +202,7 @@ const url = cfg.wsScheme + "://" + window.location.hostname + ":" + cfg.wsPort + "/"; ws = new WebSocket(url); ws.binaryType = "arraybuffer"; - ws.onopen = () => { control.textContent = "Control on"; }; + ws.onopen = () => { setControl("Control on"); }; ws.onmessage = (event) => { if (typeof event.data === "string") { let msg; @@ -197,7 +214,7 @@ } }; ws.onclose = () => { - control.textContent = "Reconnecting"; + setControl("Reconnecting"); setStatus("Connection lost. Reconnecting...", true); clearTimeout(wsTimer); wsTimer = setTimeout(connectWebCodecs, 2000); @@ -225,7 +242,7 @@ ws.binaryType = "arraybuffer"; const img = new Image(); let busy = false; - ws.onopen = () => { control.textContent = "Control on"; }; + ws.onopen = () => { setControl("Control on"); }; ws.onmessage = (event) => { if (typeof event.data === "string") { let msg; @@ -249,7 +266,7 @@ img.src = objectUrl; }; ws.onclose = () => { - control.textContent = "Reconnecting"; + setControl("Reconnecting"); setStatus("Connection lost. Reconnecting...", true); clearTimeout(wsTimer); wsTimer = setTimeout(connectMjpeg, 2000); @@ -261,15 +278,15 @@ function connectInput() { if (cfg.viewOnly) { - control.textContent = "View only"; + setControl("View only"); return; } clearTimeout(wsTimer); const url = cfg.wsScheme + "://" + window.location.hostname + ":" + cfg.wsPort + "/"; ws = new WebSocket(url); - ws.onopen = () => { control.textContent = "Control on"; }; + ws.onopen = () => { setControl("Control on"); }; ws.onclose = () => { - control.textContent = "Control reconnecting"; + setControl("Control reconnecting"); wsTimer = setTimeout(connectInput, 2000); }; ws.onerror = () => { @@ -307,6 +324,9 @@ const buttons = { 0: 1, 1: 2, 2: 3 }; const pressed = new Set(); const surfaces = [video, canvas]; + const activePointers = new Map(); + let tap = null; + let dragging = false; function release(ev) { if (cfg.viewOnly) return; @@ -317,10 +337,59 @@ } } + function touchpadMode(ev) { + return pointerMode === "touchpad" && ev.pointerType !== "mouse"; + } + + function touchpadDown(surface, ev) { + try { surface.setPointerCapture(ev.pointerId); } catch (_) { /* touch */ } + activePointers.set(ev.pointerId, { x: ev.clientX, y: ev.clientY }); + if (activePointers.size === 1) { + tap = { id: ev.pointerId, time: Date.now(), moved: 0 }; + } else { + tap = null; + } + } + + function touchpadMove(ev) { + const prev = activePointers.get(ev.pointerId); + if (!prev) return; + const dx = ev.clientX - prev.x; + const dy = ev.clientY - prev.y; + activePointers.set(ev.pointerId, { x: ev.clientX, y: ev.clientY }); + if (tap) tap.moved += Math.abs(dx) + Math.abs(dy); + if (activePointers.size >= 2) { + send({ t: "w", dy: dy * 4, dx: 0 }); + return; + } + if (!dx && !dy) return; + const rect = contentRect(); + const scale = 1.7; + send({ + t: "mr", + dx: (dx * scale) / Math.max(1, rect.width), + dy: (dy * scale) / Math.max(1, rect.height) + }); + } + + function touchpadUp(ev) { + activePointers.delete(ev.pointerId); + if (tap && tap.id === ev.pointerId && tap.moved < 8 && + Date.now() - tap.time < 350) { + send({ t: "b", button: 1, down: true }); + send({ t: "b", button: 1, down: false }); + } + if (activePointers.size === 0) tap = null; + } + for (const surface of surfaces) { surface.addEventListener("pointerdown", (ev) => { if (cfg.viewOnly) return; ev.preventDefault(); + if (touchpadMode(ev)) { + touchpadDown(surface, ev); + return; + } try { surface.setPointerCapture(ev.pointerId); } catch (_) { /* touch */ } const [x, y] = norm(ev); send({ t: "m", x, y }); @@ -331,12 +400,30 @@ surface.addEventListener("pointermove", (ev) => { if (cfg.viewOnly) return; + if (touchpadMode(ev)) { + ev.preventDefault(); + touchpadMove(ev); + return; + } const [x, y] = norm(ev); send({ t: "m", x, y }); }); - surface.addEventListener("pointerup", release); - surface.addEventListener("pointercancel", release); + surface.addEventListener("pointerup", (ev) => { + if (touchpadMode(ev)) { + touchpadUp(ev); + } else { + release(ev); + } + }); + surface.addEventListener("pointercancel", (ev) => { + if (touchpadMode(ev)) { + activePointers.delete(ev.pointerId); + tap = null; + } else { + release(ev); + } + }); surface.addEventListener("contextmenu", (ev) => ev.preventDefault()); surface.addEventListener("wheel", (ev) => { if (cfg.viewOnly) return; @@ -345,10 +432,182 @@ }, { passive: false }); } + const latched = new Set(); + + function setPanel(open) { + panel.hidden = !open; + menu.setAttribute("aria-expanded", open ? "true" : "false"); + if (!open && dragging) { + dragging = false; + send({ t: "b", button: 1, down: false }); + touchDrag.textContent = "Hold drag"; + touchDrag.classList.remove("active"); + } + } + + menu.addEventListener("click", () => { + setPanel(panel.hidden); + menu.blur(); + }); + touchClose.addEventListener("click", () => { + setPanel(false); + touchClose.blur(); + }); + + panel.querySelectorAll("[data-mode]").forEach((button) => { + button.addEventListener("click", () => { + pointerMode = button.dataset.mode; + panel.querySelectorAll("[data-mode]").forEach((other) => { + other.classList.toggle("active", other === button); + }); + button.blur(); + }); + }); + + panel.querySelectorAll("[data-button]").forEach((button) => { + button.addEventListener("click", () => { + const number = Number(button.dataset.button); + send({ t: "b", button: number, down: true }); + send({ t: "b", button: number, down: false }); + button.blur(); + }); + }); + + panel.querySelectorAll("[data-wheel]").forEach((button) => { + button.addEventListener("click", () => { + send({ t: "w", dy: Number(button.dataset.wheel), dx: 0 }); + button.blur(); + }); + }); + + function sendKeyTap(key) { + send({ t: "kd", key }); + send({ t: "ku", key }); + } + + let keepKeyboard = false; + + function rememberKeyboard(button) { + button.addEventListener("pointerdown", () => { + keepKeyboard = document.activeElement === softInput; + }); + } + + function restoreKeyboard() { + if (!keepKeyboard) return; + keepKeyboard = false; + try { softInput.focus({ preventScroll: true }); } catch (_) { softInput.focus(); } + } + + panel.querySelectorAll("[data-key]").forEach((button) => { + rememberKeyboard(button); + button.addEventListener("click", () => { + sendKeyTap(button.dataset.key); + button.blur(); + restoreKeyboard(); + }); + }); + + function updateMods() { + panel.querySelectorAll("[data-mod]").forEach((button) => { + button.classList.toggle("on", latched.has(button.dataset.mod)); + }); + } + + panel.querySelectorAll("[data-mod]").forEach((button) => { + rememberKeyboard(button); + button.addEventListener("click", () => { + const mod = button.dataset.mod; + if (latched.has(mod)) latched.delete(mod); + else latched.add(mod); + updateMods(); + button.blur(); + restoreKeyboard(); + }); + }); + + touchDrag.addEventListener("click", () => { + dragging = !dragging; + send({ t: "b", button: 1, down: dragging }); + touchDrag.textContent = dragging ? "Release drag" : "Hold drag"; + touchDrag.classList.toggle("active", dragging); + touchDrag.blur(); + }); + + function needsShift(ch) { + return /[A-Z]/.test(ch) || "~!@#$%^&*()_+{}|:\"<>?".includes(ch); + } + + function sendChar(ch) { + if (ch === "\n" || ch === "\r") { + sendKeyTap("Enter"); + return; + } + const mods = []; + if (latched.has("Control")) mods.push("Control"); + if (latched.has("Alt")) mods.push("Alt"); + if (latched.has("Shift") || needsShift(ch)) mods.push("Shift"); + for (const mod of mods) send({ t: "kd", key: mod }); + send({ t: "kd", key: ch }); + send({ t: "ku", key: ch }); + for (const mod of mods.slice().reverse()) send({ t: "ku", key: mod }); + latched.clear(); + updateMods(); + } + + const SENTINEL = "\u200b"; + let composing = false; + + function resetSoftInput() { + softInput.value = SENTINEL; + } + + softInput.value = ""; + softInput.addEventListener("focus", () => { + resetSoftInput(); + setTimeout(() => softInput.scrollIntoView({ block: "center" }), 250); + }); + softInput.addEventListener("blur", () => { softInput.value = ""; }); + softInput.addEventListener("compositionstart", () => { composing = true; }); + softInput.addEventListener("compositionend", (ev) => { + composing = false; + const text = ev.data || softInput.value.split(SENTINEL).join(""); + for (const ch of text) sendChar(ch); + resetSoftInput(); + }); + softInput.addEventListener("beforeinput", (ev) => { + if (composing) return; + if (ev.inputType === "insertText") { + for (const ch of (ev.data || "")) sendChar(ch); + ev.preventDefault(); + resetSoftInput(); + } else if (ev.inputType === "deleteContentBackward") { + sendKeyTap("BackSpace"); + ev.preventDefault(); + resetSoftInput(); + } else if (ev.inputType === "insertLineBreak" || + ev.inputType === "insertParagraph") { + sendKeyTap("Enter"); + ev.preventDefault(); + resetSoftInput(); + } + }); + softInput.addEventListener("keydown", (ev) => { + if (ev.key === "Enter") { + sendKeyTap("Enter"); + ev.preventDefault(); + } else if (ev.key === "Backspace" && softInput.value === SENTINEL) { + sendKeyTap("BackSpace"); + ev.preventDefault(); + } + }); + const keys = new Set(); window.addEventListener("keydown", (ev) => { if (cfg.viewOnly) return; + if (ev.target === softInput) return; + if (ev.target instanceof Element && ev.target.closest("#touch-panel")) return; if (ev.key === "Escape" && document.fullscreenElement) return; if (ev.metaKey) return; if (ev.ctrlKey && (ev.key === "F11" || ev.key === "F12")) return; @@ -360,6 +619,8 @@ window.addEventListener("keyup", (ev) => { if (cfg.viewOnly) return; + if (ev.target === softInput) return; + if (ev.target instanceof Element && ev.target.closest("#touch-panel")) return; if (keys.delete(ev.key)) send({ t: "ku", key: ev.key }); }); @@ -368,14 +629,30 @@ keys.clear(); for (const button of pressed) send({ t: "b", button, down: false }); pressed.clear(); + if (dragging) { + dragging = false; + send({ t: "b", button: 1, down: false }); + touchDrag.textContent = "Hold drag"; + touchDrag.classList.remove("active"); + } + latched.clear(); + updateMods(); }); - full.addEventListener("click", async () => { - full.blur(); + async function toggleFullscreen() { try { if (document.fullscreenElement) await document.exitFullscreen(); else await stage.requestFullscreen(); } catch (_) { /* denied */ } + } + + full.addEventListener("click", () => { + full.blur(); + toggleFullscreen(); + }); + touchFull.addEventListener("click", () => { + touchFull.blur(); + toggleFullscreen(); }); async function stats() { diff --git a/web/player.html b/web/player.html index e7b7c7c..813fce8 100644 --- a/web/player.html +++ b/web/player.html @@ -34,6 +34,52 @@

LFA web desktop

Control on + + diff --git a/web/server.py b/web/server.py index 1330b8a..f601230 100644 --- a/web/server.py +++ b/web/server.py @@ -621,6 +621,18 @@ def _inject(event): x = max(0, min(width - 1, x)) y = max(0, min(height - 1, y)) xtest.fake_input(X11, X.MotionNotify, x=x, y=y) + elif kind == "mr": + # Relative motion for the touchpad mode. The browser sends a + # fraction of the screen; add it to the current pointer position. + dx = float(event.get("dx", 0)) + dy = float(event.get("dy", 0)) + root = X11.screen().root + geom = root.get_geometry() + width, height = geom.width, geom.height + pointer = root.query_pointer() + x = max(0, min(width - 1, pointer.root_x + int(dx * width))) + y = max(0, min(height - 1, pointer.root_y + int(dy * height))) + xtest.fake_input(X11, X.MotionNotify, x=x, y=y) elif kind == "b": button = int(event.get("button", 1)) if 1 <= button <= 9: diff --git a/web/style.css b/web/style.css index ff70729..c9af8c8 100644 --- a/web/style.css +++ b/web/style.css @@ -152,3 +152,73 @@ body.player { overflow: hidden; } .card { padding: 1.15rem; } input { font-size: 1.25rem; } } + +/* Touch controls */ +.menu-toggle { + position: absolute; + right: 1rem; + bottom: calc(1rem + env(safe-area-inset-bottom)); + z-index: 40; + width: 3rem; + height: 3rem; + padding: 0; + border-radius: 50%; + display: none; + flex-direction: column; + align-items: center; + justify-content: center; + gap: 4px; + background: var(--accent); + border-color: var(--accent); + color: #04121c; + box-shadow: 0 8px 24px rgba(0, 0, 0, .45); +} +body.touch .menu-toggle { display: flex; } +.menu-toggle span { + display: block; + width: 1.15rem; + height: 2px; + background: #04121c; + border-radius: 2px; +} +.touch-panel { + position: absolute; + left: .5rem; + right: .5rem; + bottom: calc(.5rem + env(safe-area-inset-bottom)); + z-index: 50; + max-height: 70vh; + overflow-y: auto; + touch-action: auto; + padding: .9rem; + background: rgba(19, 26, 34, .97); + border: 1px solid var(--line); + border-radius: 14px; + box-shadow: 0 18px 60px rgba(0, 0, 0, .6); + display: grid; + gap: .55rem; +} +.touch-head { display: flex; align-items: center; justify-content: space-between; } +.touch-head strong { font-size: .95rem; } +.touch-head .spacer { flex: 1; } +body.touch .bar { display: none; } +.touch-row { display: flex; flex-wrap: wrap; align-items: center; gap: .4rem; } +.touch-row button { padding: .5rem .7rem; font-size: .85rem; min-height: 2.75rem; } +.touch-row button.active, .touch-row button.mod.on { + background: var(--accent); + border-color: var(--accent); + color: #04121c; +} +.touch-label { color: var(--muted); font-size: .8rem; min-width: 4.5rem; } +.soft-input { + width: 100%; + margin: 0; + padding: .7rem .8rem; + border: 1px solid var(--line); + border-radius: 9px; + background: #0e141b; + color: var(--text); + font: 16px/1.3 system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; + letter-spacing: normal; + text-transform: none; +} From 1f0606fb8e0438d3b556368199bb90e5f444a63e Mon Sep 17 00:00:00 2001 From: pdev <300827144+pdev-labs@users.noreply.github.com> Date: Wed, 2 Dec 2026 21:58:38 +0530 Subject: [PATCH 08/10] web: decode MJPEG frames with createImageBitmap when available Avoid a blob URL and an load per frame. createImageBitmap decodes off the main thread, which helps the fallback keep up at 60 fps. --- README.md | 15 +++++++++++---- web/app.js | 33 ++++++++++++++++++++++----------- 2 files changed, 33 insertions(+), 15 deletions(-) diff --git a/README.md b/README.md index 9d7a390..1f982e6 100644 --- a/README.md +++ b/README.md @@ -720,10 +720,17 @@ lfa web start -i ubuntu --transport webrtc `--encoder auto` (the default) picks `h264_mediacodec` when ffmpeg reports it and falls back to `libx264 -preset ultrafast -tune zerolatency`. The default -captures the whole display at 30 fps and about 4 Mbps. `--size WxH` scales the -capture to that output size, which is useful on a large desktop. The phone's -hardware encoder keeps CPU use low, and the browser decodes H.264 with its own -hardware path when it has one. +captures the whole display at 30 fps. `--size WxH` scales the capture to that +output size, which is useful on a large desktop. The phone's hardware encoder +keeps CPU use low, and the browser decodes H.264 with its own hardware path +when it has one. + +The MJPEG fallback keeps up at 60 fps when you ask for it. On the test phone's +hotspot, `--size 1280x720 --fps 60` used about 8 Mbps and +`--size 960x540 --fps 60` about 6 Mbps. The H.264 path uses much less +bandwidth for the same picture. The viewer HUD shows the actual frame rate and +bitrate, so you can tune `--size` and `--fps` against what the viewer can +decode. WebCodecs gives the lowest latency and needs Chrome 94+, Edge 94+, or Safari 16.4+. Firefox support depends on the build. A browser without WebCodecs diff --git a/web/app.js b/web/app.js index 4a2904a..683b679 100644 --- a/web/app.js +++ b/web/app.js @@ -240,20 +240,18 @@ cfg.wsPort + "/?mode=mjpeg"; ws = new WebSocket(url); ws.binaryType = "arraybuffer"; - const img = new Image(); let busy = false; - ws.onopen = () => { setControl("Control on"); }; - ws.onmessage = (event) => { - if (typeof event.data === "string") { - let msg; - try { msg = JSON.parse(event.data); } catch (_) { return; } - if (msg.t === "error") setStatus(msg.message || "Video error", true); + const showJpeg = (data) => { + if (typeof createImageBitmap === "function") { + createImageBitmap(new Blob([data], { type: "image/jpeg" })).then((bitmap) => { + paint(bitmap.width, bitmap.height, bitmap); + bitmap.close(); + busy = false; + }).catch(() => { busy = false; }); return; } - if (busy) return; - busy = true; - decodedBytes += event.data.byteLength; - const objectUrl = URL.createObjectURL(new Blob([event.data], { type: "image/jpeg" })); + const objectUrl = URL.createObjectURL(new Blob([data], { type: "image/jpeg" })); + const img = new Image(); img.onload = () => { URL.revokeObjectURL(objectUrl); paint(img.naturalWidth || cfg.width, img.naturalHeight || cfg.height, img); @@ -265,6 +263,19 @@ }; img.src = objectUrl; }; + ws.onopen = () => { setControl("Control on"); }; + ws.onmessage = (event) => { + if (typeof event.data === "string") { + let msg; + try { msg = JSON.parse(event.data); } catch (_) { return; } + if (msg.t === "error") setStatus(msg.message || "Video error", true); + return; + } + if (busy) return; + busy = true; + decodedBytes += event.data.byteLength; + showJpeg(event.data); + }; ws.onclose = () => { setControl("Reconnecting"); setStatus("Connection lost. Reconnecting...", true); From 52171b7110fee9db23932a874d8c78666ce06965 Mon Sep 17 00:00:00 2001 From: pdev <300827144+pdev-labs@users.noreply.github.com> Date: Wed, 2 Dec 2026 22:23:12 +0530 Subject: [PATCH 09/10] web: add fit, stretch, fill, and zoom view modes The canvas is now sized explicitly instead of relying on object-fit, so the desktop keeps its aspect ratio by default. The touch panel adds Fit, Stretch, Fill, and 1:1 modes plus a 50-200% zoom control, and remembers the choice in localStorage. Input mapping uses the displayed element rect, so it follows every mode. --- CHANGELOG.md | 3 +- README.md | 4 +- web/app.js | 114 ++++++++++++++++++++++++++++++++++++++++++------ web/player.html | 14 ++++++ web/style.css | 1 + 5 files changed, 121 insertions(+), 15 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d0bc9e2..bdbbd8a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -25,7 +25,8 @@ tag names, define the order. See the table at the bottom. works on Android. A browser without WebCodecs gets an MJPEG fallback. Phone and tablet viewers get a floating touch panel with a relative touchpad, tap-to-position, mouse buttons, hold-drag, scrolling, and an - on-screen keyboard. `--transport webrtc` uses go2rtc v1.9.15, downloaded on + on-screen keyboard. The panel also has Fit, Stretch, Fill, and 1:1 screen + modes with zoom. `--transport webrtc` uses go2rtc v1.9.15, downloaded on first use after a SHA-256 check. Video uses `h264_mediacodec` when ffmpeg supports it and falls back to `libx264 -preset ultrafast -tune zerolatency`. The passcode stays in memory, and the only LAN listener is the Python diff --git a/README.md b/README.md index 1f982e6..6eff8ae 100644 --- a/README.md +++ b/README.md @@ -740,7 +740,9 @@ more bandwidth. Use a WebCodecs browser when you can. A phone or tablet viewer shows a floating menu button. The touch panel switches between a relative touchpad and tap-to-position pointer mode, and adds left, right, and middle click, hold-drag, scrolling, arrow and modifier -keys, plus a text field that opens the on-screen keyboard. +keys, plus a text field that opens the on-screen keyboard. It also has Fit, +Stretch, Fill, and 1:1 screen modes with a zoom control. The screen mode is +remembered in the browser. `lfa web doctor` checks ffmpeg's X11 capture input (`x11grab` or `xcbgrab`) and H.264 encoders, the Python `websockets` and `python-xlib` modules, the diff --git a/web/app.js b/web/app.js index 683b679..327974f 100644 --- a/web/app.js +++ b/web/app.js @@ -31,12 +31,29 @@ const touchDrag = document.getElementById("touch-drag"); const softInput = document.getElementById("soft-input"); const touchStatus = document.getElementById("touch-status"); + const zoomLabel = document.getElementById("zoom-label"); + const zoomOut = document.getElementById("zoom-out"); + const zoomIn = document.getElementById("zoom-in"); + const zoomReset = document.getElementById("zoom-reset"); const isTouch = navigator.maxTouchPoints > 0 || (window.matchMedia && window.matchMedia("(pointer: coarse)").matches); if (isTouch) body.classList.add("touch"); let pointerMode = isTouch ? "touchpad" : "absolute"; + let viewMode = "fit"; + let zoom = 1; + try { + const savedView = localStorage.getItem("lfa.view"); + if (["fit", "stretch", "fill", "native"].includes(savedView)) { + viewMode = savedView; + } + const savedZoom = parseFloat(localStorage.getItem("lfa.zoom") || "1"); + if (Number.isFinite(savedZoom) && savedZoom >= 0.5 && savedZoom <= 2) { + zoom = savedZoom; + } + } catch (_) { /* storage can be blocked */ } + let pc = null; let ws = null; let wsTimer = null; @@ -94,6 +111,8 @@ video.hidden = false; canvas.hidden = true; video.play().catch(() => { /* autoplay is allowed because muted */ }); + video.addEventListener("loadedmetadata", applyViewMode, { once: true }); + applyViewMode(); }; pc.onconnectionstatechange = () => { const state = pc ? pc.connectionState : "closed"; @@ -123,11 +142,13 @@ } function paint(width, height, source) { - if (canvas.width !== width || canvas.height !== height) { + const changed = canvas.width !== width || canvas.height !== height; + if (changed) { canvas.width = width; canvas.height = height; } ctx.drawImage(source, 0, 0, canvas.width, canvas.height); + if (changed) applyViewMode(); decodedFrames += 1; if (!overlay.hidden) { setStatus("", false); @@ -167,6 +188,7 @@ canvas.height = 0; canvas.hidden = false; video.hidden = true; + applyViewMode(); } function handleVideo(data) { @@ -236,6 +258,7 @@ canvas.height = 0; canvas.hidden = false; video.hidden = true; + applyViewMode(); const url = cfg.wsScheme + "://" + window.location.hostname + ":" + cfg.wsPort + "/?mode=mjpeg"; ws = new WebSocket(url); @@ -310,19 +333,51 @@ ws.send(JSON.stringify(event)); } - function contentRect() { + function frameSize() { + if (!canvas.hidden) { + return [canvas.width || cfg.width, canvas.height || cfg.height]; + } + return [video.videoWidth || cfg.width, video.videoHeight || cfg.height]; + } + + function applyViewMode() { + const el = canvas.hidden ? video : canvas; + const [vw, vh] = frameSize(); + if (!el || !vw || !vh) return; const rect = stage.getBoundingClientRect(); - const vw = canvas.hidden ? (video.videoWidth || cfg.width) : (canvas.width || cfg.width); - const vh = canvas.hidden ? (video.videoHeight || cfg.height) : (canvas.height || cfg.height); - const scale = Math.min(rect.width / Math.max(1, vw), rect.height / Math.max(1, vh)); - const width = vw * scale; - const height = vh * scale; - return { - left: rect.left + (rect.width - width) / 2, - top: rect.top + (rect.height - height) / 2, - width, - height - }; + let width; + let height; + if (viewMode === "stretch") { + width = rect.width; + height = rect.height; + } else if (viewMode === "fill") { + const scale = Math.max(rect.width / vw, rect.height / vh); + width = vw * scale; + height = vh * scale; + } else if (viewMode === "native") { + width = vw; + height = vh; + } else { + const scale = Math.min(rect.width / vw, rect.height / vh); + width = vw * scale; + height = vh * scale; + } + width *= zoom; + height *= zoom; + el.style.width = width + "px"; + el.style.height = height + "px"; + el.style.objectFit = "fill"; + el.style.position = "absolute"; + el.style.left = "50%"; + el.style.top = "50%"; + el.style.transform = "translate(-50%, -50%)"; + if (zoomLabel) zoomLabel.textContent = Math.round(zoom * 100) + "%"; + } + + function contentRect() { + const el = canvas.hidden ? video : canvas; + const rect = el.getBoundingClientRect(); + return { left: rect.left, top: rect.top, width: rect.width, height: rect.height }; } function norm(ev) { @@ -475,6 +530,35 @@ }); }); + const viewButtons = panel.querySelectorAll("[data-view]"); + + function setView(mode) { + viewMode = mode; + viewButtons.forEach((button) => { + button.classList.toggle("active", button.dataset.view === mode); + }); + try { localStorage.setItem("lfa.view", mode); } catch (_) { /* blocked */ } + applyViewMode(); + } + + viewButtons.forEach((button) => { + button.addEventListener("click", () => { + setView(button.dataset.view); + button.blur(); + }); + button.classList.toggle("active", button.dataset.view === viewMode); + }); + + function setZoom(value) { + zoom = Math.min(2, Math.max(0.5, Math.round(value * 100) / 100)); + try { localStorage.setItem("lfa.zoom", String(zoom)); } catch (_) { /* blocked */ } + applyViewMode(); + } + + zoomOut.addEventListener("click", () => { setZoom(zoom - 0.25); zoomOut.blur(); }); + zoomIn.addEventListener("click", () => { setZoom(zoom + 0.25); zoomIn.blur(); }); + zoomReset.addEventListener("click", () => { setZoom(1); zoomReset.blur(); }); + panel.querySelectorAll("[data-button]").forEach((button) => { button.addEventListener("click", () => { const number = Number(button.dataset.button); @@ -713,6 +797,10 @@ } }); + applyViewMode(); + window.addEventListener("resize", applyViewMode); + document.addEventListener("fullscreenchange", applyViewMode); + if (cfg.transport === "webcodecs") { connectWebCodecs(); } else { diff --git a/web/player.html b/web/player.html index 813fce8..8136a36 100644 --- a/web/player.html +++ b/web/player.html @@ -59,6 +59,20 @@

LFA web desktop

+
+ Screen + + + + +
+
+ Zoom + + 100% + + +
diff --git a/web/style.css b/web/style.css index c9af8c8..4c20f68 100644 --- a/web/style.css +++ b/web/style.css @@ -88,6 +88,7 @@ body.player { overflow: hidden; } place-items: center; touch-action: none; user-select: none; + overflow: hidden; } #screen, .screen { From 6235bc49c18d7f486953cc9ec40171ecd9591f2f Mon Sep 17 00:00:00 2001 From: pdev <300827144+pdev-labs@users.noreply.github.com> Date: Thu, 3 Dec 2026 13:34:24 +0530 Subject: [PATCH 10/10] codec: add hardware video decode through Android MediaCodec Add `lfa codec`, a bridge between VA-API in the container and the phone's MediaCodec decoders. A Termux daemon drives AMediaCodec over a Unix socket in the shared /tmp, and a standalone libva driver in the guest turns decode calls into that protocol and copies NV12 frames into VA surfaces. Commands: install, status, start, stop, doctor, test, play, env, run. The daemon follows the desktop through start-linux/stop-linux, and existing launchers are patched on install. The driver installs under /usr/local/lib/lfa-codec/dri and does not touch the distro's Mesa files. H.264 (Baseline/Main/High), HEVC Main, VP9 Profile 0, and VP8 are supported. This is the CPU copy path, so Chromium and Firefox stay on software decode; mpv, VLC, and ffmpeg use the bridge. Vendored sources: the daemon from lfdevs/termux-va (GPL-3.0) and the driver from Re-s/droidspaces-media-decode (Apache-2.0). --- CHANGELOG.md | 8 + README.md | 60 +- SECURITY.md | 6 + codec/README.md | 87 + codec/common/tva_protocol.h | 202 +++ codec/daemon/LICENSE | 674 +++++++ codec/daemon/Makefile | 36 + codec/daemon/termux-va.c | 2888 ++++++++++++++++++++++++++++++ codec/vaapi/LICENSE | 190 ++ codec/vaapi/Makefile | 88 + codec/vaapi/src/av1_bitstream.c | 1097 ++++++++++++ codec/vaapi/src/av1_bitstream.h | 148 ++ codec/vaapi/src/bitstream.c | 119 ++ codec/vaapi/src/bitstream.h | 34 + codec/vaapi/src/decode.c | 2648 +++++++++++++++++++++++++++ codec/vaapi/src/dmd_client.c | 1168 ++++++++++++ codec/vaapi/src/dmd_client.h | 272 +++ codec/vaapi/src/driver.c | 230 +++ codec/vaapi/src/driver.h | 564 ++++++ codec/vaapi/src/export.c | 159 ++ codec/vaapi/src/h264_bitstream.c | 462 +++++ codec/vaapi/src/hevc_bitstream.c | 362 ++++ codec/vaapi/src/image.c | 348 ++++ codec/vaapi/src/profiles.c | 429 +++++ codec/vaapi/src/stubs.c | 270 +++ codec/vaapi/src/stubs.h | 33 + codec/vaapi/src/vtable.inc | 64 + codec/vaapi/tools/gen_stubs.py | 151 ++ codec/vaapi/tools/gen_vtable.py | 60 + docs/ARCHITECTURE.md | 54 + docs/DECISIONS.md | 39 + docs/INCOMPATIBLE.md | 4 +- docs/TROUBLESHOOTING.md | 47 + install_linux.sh | 36 +- lib/lfa-codec.sh | 666 +++++++ tests/test-all.sh | 77 + 36 files changed, 13774 insertions(+), 6 deletions(-) create mode 100644 codec/README.md create mode 100644 codec/common/tva_protocol.h create mode 100644 codec/daemon/LICENSE create mode 100644 codec/daemon/Makefile create mode 100644 codec/daemon/termux-va.c create mode 100644 codec/vaapi/LICENSE create mode 100644 codec/vaapi/Makefile create mode 100644 codec/vaapi/src/av1_bitstream.c create mode 100644 codec/vaapi/src/av1_bitstream.h create mode 100644 codec/vaapi/src/bitstream.c create mode 100644 codec/vaapi/src/bitstream.h create mode 100644 codec/vaapi/src/decode.c create mode 100644 codec/vaapi/src/dmd_client.c create mode 100644 codec/vaapi/src/dmd_client.h create mode 100644 codec/vaapi/src/driver.c create mode 100644 codec/vaapi/src/driver.h create mode 100644 codec/vaapi/src/export.c create mode 100644 codec/vaapi/src/h264_bitstream.c create mode 100644 codec/vaapi/src/hevc_bitstream.c create mode 100644 codec/vaapi/src/image.c create mode 100644 codec/vaapi/src/profiles.c create mode 100644 codec/vaapi/src/stubs.c create mode 100644 codec/vaapi/src/stubs.h create mode 100644 codec/vaapi/src/vtable.inc create mode 100644 codec/vaapi/tools/gen_stubs.py create mode 100644 codec/vaapi/tools/gen_vtable.py create mode 100644 lib/lfa-codec.sh diff --git a/CHANGELOG.md b/CHANGELOG.md index bdbbd8a..b07b18d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,6 +15,14 @@ tag names, define the order. See the table at the bottom. ### Added +- Hardware video decode. `lfa codec` installs a Termux MediaCodec daemon and + a VA-API driver in the container, so mpv, VLC, and ffmpeg decode H.264, + HEVC, VP9, and VP8 on the phone's decoder instead of the CPU. `install`, + `status`, `start`, `stop`, `doctor`, `test`, `play`, `env`, and `run` cover + setup and day-to-day use. The bridge copies frames through the CPU and does + not export dmabufs, so Chromium and Firefox still use software decode. The + daemon runs over a Unix socket in the shared `/tmp` and stops with + `lfa stop`. - Browser access to the desktop. `lfa web start` shares display `:1` with another device on the local network, with `status`, `stop`, and `doctor` alongside it. The command prints one 8-character passcode made of letters diff --git a/README.md b/README.md index 6eff8ae..f3e2190 100644 --- a/README.md +++ b/README.md @@ -133,7 +133,7 @@ hardware, not simulated. Full details, root causes, and evidence are in | Alpine 3.18 (Android 5) | Yes | Yes | legacy VNC desktop, panel works; X11 and Both hidden | v1.7.1 | | Ubuntu GNOME 46 (experimental) | Yes | Yes | shell and apps run; session services missing | v1.7.0 | -> The test suite runs `1022` checks with 0 failures. The same suite runs on the +> The test suite runs `1057` checks with 0 failures. The same suite runs on the > devices (`tests/device-matrix.sh`). The table is as of v1.7.1. Ubuntu was > re-verified on v1.7.1, and Alpine 3.18 was re-verified on Android 5 on > 2026-11-04; the other rows were last verified on v1.7.0. A row is @@ -152,6 +152,7 @@ same session: | Alpine 3.18, XFCE, and VNC on the Oppo A37fw (2016) | 3m 32s, 204 MB | | Ubuntu 24.04 and GNOME 46 on the Vivo V2437 | 27m 45s, about 2.5 GB | | Desktop cold start (XFCE, X11 on the Vivo) | about 10 seconds after `start-linux` | +| Hardware decode on the Vivo (MT6878) | 1080p H.264/HEVC/VP9 and 4K H.264 matched software output byte-for-byte; the copy path is CPU-bound | | GNOME over software rendering | 1 to 7 FPS video playback, usable shell | ## Hard problems solved @@ -482,6 +483,7 @@ is accepted. | `lfa run` | run an AppImage once without installing it | | `lfa storage` | Android storage status, repair, run, protected data helpers, and separate Android/external access toggles | | `lfa web` | share the running desktop with a browser on the local network; `start`, `status`, `stop`, `doctor` | +| `lfa codec` | hardware video decode through Android MediaCodec; `install`, `status`, `start`, `stop`, `doctor`, `test`, `play`, `env`, `run` | | `lfa diagnostics` (`diag`) | write a redacted support bundle | | `lfa notice` | `on`, `off`, or `status` for the `start-linux` change notice | | `lfa version` (`ver`) / `lfa help` | version and command list | @@ -513,6 +515,8 @@ lfa appimage run Foo lfa storage status lfa web start -i ubuntu lfa web status -i ubuntu +lfa codec install -i ubuntu +lfa codec play ~/Videos/sample.mp4 lfa notice off ``` @@ -766,6 +770,55 @@ If the browser connects but video stays black, check that the Wi-Fi access point allows client-to-client traffic; guest networks often block it. Try `--encoder x264` if the phone's hardware encoder fails on a large display. +### Hardware video decode + +`lfa codec` routes VA-API decode from the container to Android's MediaCodec +hardware decoders. H.264 (Constrained Baseline, Main, High), HEVC Main, VP9 +Profile 0, and VP8 are supported. The phone's decoder does the work; the +container gets NV12 frames through a small driver. + +```bash +lfa codec install -i ubuntu +lfa codec status +lfa codec test +lfa codec play ~/Videos/sample.mp4 +``` + +`install` builds a Termux-side daemon and a libva driver inside the container. +The daemon starts with the desktop and stops with `lfa stop`. `test` decodes a +small sample with the bridge and with software decode, then compares the two +results. `play` runs mpv with `--hwdec=vaapi-copy` and the right environment. +A Termux-local file is copied into the shared `/tmp` first; `/sdcard`, +`/storage`, and container paths are used as they are. + +Use it with any VA-API consumer: + +```bash +lfa codec run -- ffmpeg -hwaccel vaapi -vaapi_device :1 \ + -hwaccel_output_format vaapi -i in.mp4 -f null - +lfa codec env +``` + +The container and Termux share `/tmp`, so the daemon socket is +`/tmp/termux-va/termux-va.sock` in the guest. The driver is installed under +`/usr/local/lib/lfa-codec/dri`, separate from the distro's Mesa files. + +Two limits matter: + +- The bridge copies each decoded frame through the CPU. At low resolutions + software decode can be just as fast; the gain is CPU headroom and larger + frames, not a guaranteed higher frame rate. The test phone decoded 1080p + H.264, HEVC, and VP9 byte-for-byte identically to software. +- Chromium and Firefox need a DRM render node and dmabuf export to use a + hardware decoder. The container normally cannot open `/dev/dri`, so those + browsers stay on software decode. mpv and ffmpeg use the copy path; VLC can + decode with `--avcodec-hw=vaapi`, though its GL output may still choose + software. + +`lfa codec doctor` reports the daemon, socket, driver, libva, and whether a DRM +render node is available. If decode fails, check that the desktop is running +on `:1` and that `lfa codec status` shows the daemon as running. + ### Android/data and Android/obb Android 11 and later block `/storage/emulated/0/Android/data` and @@ -1412,7 +1465,8 @@ short list is: - `systemd`, `snapd`, Flatpak and bubblewrap sandboxes - Docker, Podman, LXC/LXD, libvirt, VirtualBox, QEMU/KVM, Waydroid - WireGuard/OpenVPN/TUN/TAP, raw packet capture, iptables/nftables enforcement -- CUDA, ROCm, vendor GPU compute, hardware video encode/decode +- CUDA, ROCm, vendor GPU compute, hardware video encode (decode is available + through `lfa codec`) - kernel modules, real `mount`/`chroot`/`unshare`, real root/SELinux control - Bluetooth/BlueZ, NFC, camera as `/dev/video*`, sensors, USB host as device nodes (`lfa usb` provides userspace access instead) @@ -1741,7 +1795,7 @@ plus `script` from util-linux for the pty test, which is skipped if absent: ```bash chmod +x tests/test-all.sh -./tests/test-all.sh # expect: PASS=1022 FAIL=0 +./tests/test-all.sh # expect: PASS=1057 FAIL=0 ``` The suite is deliberately stubbed. It cannot prove a desktop actually appears. diff --git a/SECURITY.md b/SECURITY.md index 4e557b0..f784dbf 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -77,3 +77,9 @@ Out of scope: other listener; when `--transport webrtc` is used, go2rtc listens on `127.0.0.1` only. The passcode page uses a self-signed HTTPS certificate by default. +- The hardware decode daemon (`lfa codec`) listens on a Unix socket under + Termux's private `$TMPDIR`, not on TCP. The daemon runs as the Termux user + and needs no root; the driver is built from vendored source in the + container. The socket is reachable by the Termux app and by the guest that + shares `/tmp`, which is the intended boundary. The daemon is stopped by + `lfa stop` and by uninstalling the instance. diff --git a/codec/README.md b/codec/README.md new file mode 100644 index 0000000..89a4e53 --- /dev/null +++ b/codec/README.md @@ -0,0 +1,87 @@ +# Hardware video decode + +This directory contains the two halves of the MediaCodec VA-API bridge: + +- `daemon/` runs in Termux and drives Android's `MediaCodec` decoders through + the NDK. It listens on a Unix socket under `$TMPDIR/termux-va/`. +- `vaapi/` is a libva driver loaded inside the Linux container. It turns VA-API + decode calls into the daemon protocol and copies the decoded NV12 frames into + VA surfaces. + +The container shares Termux's temporary directory (`proot-distro --shared-tmp` +does this), so the daemon socket is visible as +`/tmp/termux-va/termux-va.sock` inside the guest. + +``` +mpv / ffmpeg / VLC + | + libva + | + lfa_codec_drv_video.so (container) + | + /tmp/termux-va/termux-va.sock (shared tmp) + | + termux-va daemon (Termux) + | + Android MediaCodec +``` + +## What works + +Decode is implemented for H.264 (Constrained Baseline, Main, High), HEVC Main, +VP9 Profile 0, and VP8. Output is NV12. The driver also implements +`vaDeriveImage`, `vaCreateImage`, `vaGetImage`, and `vaMapBuffer`, which is the +path mpv and ffmpeg use for `vaapi-copy` / `hwdownload`. + +The bridge does not provide a DRM render node or zero-copy dmabuf export. On +devices where the container cannot open `/dev/dri`, `vaExportSurfaceHandle` +cannot hand a surface to a GPU consumer. That means Chromium and Firefox still +fall back to software decode. Media players using the copy path are the +supported target. + +## Build + +The daemon is built by Termux's clang: + +```sh +make -C daemon +``` + +The driver is built inside the container with `libva-dev`, `libdrm-dev`, +`build-essential`, `pkg-config`, and `python3`: + +```sh +make -C vaapi gen # regenerate the vtable for the container's libva +make -C vaapi +make -C vaapi install # /usr/local/lib/lfa-codec/dri/lfa_codec_drv_video.so +``` + +`lfa codec install` runs both steps for you. + +## Runtime environment + +The container-side consumer needs: + +```sh +LIBVA_DRIVER_NAME=lfa_codec +LIBVA_DRIVERS_PATH=/usr/local/lib/lfa-codec/dri +DMD_ENDPOINT=unix:/tmp/termux-va/termux-va.sock +``` + +`lfa codec play FILE` sets these and starts mpv with `--hwdec=vaapi-copy`. + +## Provenance and licenses + +`daemon/termux-va.c` and `common/tva_protocol.h` come from +[lfdevs/termux-va](https://github.com/lfdevs/termux-va), which is GPL-3.0. The +files keep their upstream copyright and modification notices. LFA is also +GPL-3.0, so the combined work is distributed under the same license. + +`vaapi/` comes from the socket-based VA-API proxy driver in +[Re-s/droidspaces-media-decode](https://github.com/Re-s/droidspaces-media-decode) +(commit before the V4L2 rewrite), which is Apache-2.0. The license text is in +`vaapi/LICENSE`. Apache-2.0 is compatible with GPL-3.0; the combined work is +distributed under GPL-3.0. + +The LFA changes are limited to the build layout, the driver name and version +string, and the `lfa codec` integration. diff --git a/codec/common/tva_protocol.h b/codec/common/tva_protocol.h new file mode 100644 index 0000000..24ecb88 --- /dev/null +++ b/codec/common/tva_protocol.h @@ -0,0 +1,202 @@ +/* + * SPDX-License-Identifier: GPL-3.0-or-later + * + * tva_protocol.h - Wire protocol constants shared by the termux-va daemon + * (Termux side) and the Mesa termux-va bridge (container + * side, mesa-for-android-container branch + * dev/adreno-main, file src/gallium/frontends/va/tva_protocol.h). + * + * This file is the single source of truth for everything that travels on + * the wire or must agree on both ends of the Unix socket. The two copies + * MUST be byte-identical; scripts/check-mirror.sh enforces that with cmp(1) + * (same discipline as anland-termux AGENTS.md). + * + * Copyright (C) 2026 lfdevs + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, version 3 of the License. + * + * This file is based on droidspaces-media-decode (src/decode-daemon.c and + * vaapi-driver/src/dmd_client.{c,h}), which is licensed under the Apache + * License, Version 2.0. It has been MODIFIED for the termux-va project and + * relicensed under the GNU General Public License version 3: + * - protocol constants extracted from the daemon/client inline defines + * into this shared header (decoder values and wire format unchanged), + * - default socket name changed from decode.sock to termux-va.sock, + * - XFER_TCP renamed to XFER_INLINE (wire value 0 unchanged; the transport + * is always a path-based Unix socket in termux-va, TCP was removed). + * + * Protocol compatibility statement: decoder handshakes and payloads stay + * byte-compatible with droidspaces-media-decode protocol v3 + * (HELLO_MAGIC 0x444D4400), so the upstream regression tools + * (tools/test_decode.py, dmd-probe) can be reused unchanged. Encoder-only + * bitrate and frame-rate words are an appended termux-va extension. + */ +#ifndef TVA_PROTOCOL_H +#define TVA_PROTOCOL_H + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/* ------------------------------------------------------------------ paths */ + +/* Fixed socket file name inside the socket directory. Both the daemon + * (directory mode) and the Mesa bridge (default endpoint) join this name + * onto the socket directory. */ +#define TVA_SOCK_NAME "termux-va.sock" + +/* Name of the socket directory relative to the shared tmp directory. + * Termux default: $TMPDIR/termux-va/termux-va.sock + * Container view: /tmp/termux-va/termux-va.sock (proot --shared-tmp) */ +#define TVA_SOCKET_DIR_NAME "termux-va" + +/* --------------------------------------------------------------- handshake */ + +/* + * Magic of the big-endian handshake request. Decoder sessions use the + * original 24-byte form: + * [u32 magic][u32 version][u32 codec][u32 width][u32 height][u32 xfer] + * Encoder sessions append the target bitrate and input frame rate: + * [... base fields][u32 bitrate][u32 fps_num][u32 fps_den] + * + * Kept identical to upstream droidspaces-media-decode ("DMD\0") so the + * upstream protocol v3 regression tools work unchanged. A legal NALU + * length can never equal this value (1145389568 >> MAX_FRAME), which is + * how the two are told apart... but note the handshake is REQUIRED here: + * a first word that is not the magic is rejected (status=4). + */ +#define HELLO_MAGIC 0x444D4400u + +/* + * Current protocol version. + * v2: shared-memory transport negotiation added + * v3: response may carry the endpoint dev/ino extension (bit31 of the + * name-length word), used by the client to verify it connected to + * the live socket inode (bind-mount safety). + * + * Version negotiation: the daemon accepts versions 2..HELLO_VERSION and + * takes the minimum; clients must do the same. + */ +#define HELLO_VERSION 3 +#define TVA_VERSION_MIN 2 + +/* + * Codec identifiers. This is part of the wire protocol (handshake word 3). + * Values may only be APPENDED, never reordered or reused. + */ +typedef enum { + CODEC_H264 = 0, + CODEC_HEVC = 1, + CODEC_VP9 = 2, + CODEC_VP8 = 3, + CODEC_AV1 = 4, /* AV1 Main decode */ + /* Encoder sessions use separate ids so the v3 six-word handshake stays + * byte-compatible with existing decoder clients. The payload framing is + * raw NV12 in and an encoded access unit out. */ + CODEC_H264_ENC = 5, + CODEC_HEVC_ENC = 6, + CODEC_VP9_ENC = 7, + /* Explicit AVC profiles; id 5 retains the legacy device-default profile. + * New ids use the same nine-word encoder handshake. Old daemons reject + * them as unsupported instead of silently choosing another profile. */ + CODEC_H264_BASELINE_ENC = 8, + CODEC_H264_MAIN_ENC = 9, + CODEC_H264_HIGH_ENC = 10, + CODEC_MAX +} CodecId; + +static inline int codec_is_encoder(int codec) +{ + return codec == CODEC_H264_ENC || codec == CODEC_HEVC_ENC || + codec == CODEC_VP9_ENC || codec == CODEC_H264_BASELINE_ENC || + codec == CODEC_H264_MAIN_ENC || codec == CODEC_H264_HIGH_ENC; +} + +static inline int codec_base_id(int codec) +{ + return (codec == CODEC_H264_ENC || codec == CODEC_H264_BASELINE_ENC || + codec == CODEC_H264_MAIN_ENC || codec == CODEC_H264_HIGH_ENC) ? CODEC_H264 : + codec == CODEC_HEVC_ENC ? CODEC_HEVC : + codec == CODEC_VP9_ENC ? CODEC_VP9 : codec; +} + +/* + * Frame return transport requested in the handshake and granted in the + * response ("actual xfer" word). + * + * 0 = inline : frame data is sent over the control socket itself + * 1 = SHM : frame data is written into a memfd slot pool; the socket + * only carries a 24-byte control message naming the slot + * + * TVA: upstream calls value 0 "XFER_TCP" because upstream also had a TCP + * control transport. termux-va is Unix-socket-only, so the constant is + * renamed XFER_INLINE; the WIRE VALUE 0 IS UNCHANGED and must stay 0. + */ +typedef enum { + XFER_INLINE = 0, + XFER_SHM = 1 +} XferMode; + +/* Handshake status codes (response word 1): + * 0 accepted / 1 version / 2 codec / 3 resolution out of range / + * 4 handshake missing. Error responses are always a bare 12 bytes. */ + +/* ------------------------------------------------------------------ limits */ + +/* Hard cap of one compressed decoder input unit. */ +#define MAX_FRAME (8 * 1024 * 1024) +/* Packed NV12 encoder inputs need 12.4 MB at 3840x2160. The framing is + * unchanged; both endpoints must be updated for raw frames over 8 MiB. */ +#define MAX_ENCODE_FRAME (16 * 1024 * 1024) + +/* Max concurrent decode sessions the daemon accepts (hardware supports 16). */ +#define MAX_CLIENTS 8 + +/* ------------------------------------------------- format descriptor block */ + +/* Number of u32 words in the 32-byte format descriptor body: + * [buf_w][buf_h][stride][slice_height][crop_l][crop_t][crop_r][crop_b] */ +#define FMTDESC_WORDS 8 + +/* frame_size values that mean "this is a control message, not a frame". */ +#define FMTDESC_SENTINEL 0xFFFFFFFFu /* followed by the 32-byte format block */ +#define SHMFRAME_SENTINEL 0xFFFFFFFEu /* followed by [slot][len][pts] in one + * 24-byte SHM control message */ + +/* Capability flag in format-block header word 2: every frame header carries + * a 4th field = input unit index (round-tripped through MediaCodec PTS). */ +#define CAP_FRAME_PTS 0x00000001u + +/* + * Input unit index -> presentationTimeUs multiplier. + * + * The decoder quantizes PTS to milliseconds; feeding the raw unit index + * (1us steps) collapses everything to 0. x1000 keeps indices unique after + * quantization. The client divides by this to recover the index. + */ +#define PTS_UNIT_SCALE 1000 + +/* ------------------------------------------------------- shared memory pool */ + +/* Pool layout: [control area SHM_CTRL_BYTES][slot 0]..[slot SHM_SLOTS-1]. + * Each slot has a u32 state word in the control area: daemon sets 1 + * (release) after writing, client resets 0 (acquire) after consuming. */ +#define SHM_SLOTS 8 +#define SHM_CTRL_BYTES 4096 + +/* + * How long the daemon spins waiting for a free slot (milliseconds). + * MUST stay well above the bridge-side per-call frame timeout (5s) or the + * daemon kills sessions the client would have completed. 15s = 3x. + */ +#define SHM_SLOT_WAIT_MS 15000 + +#ifdef __cplusplus +} +#endif + +#endif /* TVA_PROTOCOL_H */ diff --git a/codec/daemon/LICENSE b/codec/daemon/LICENSE new file mode 100644 index 0000000..f288702 --- /dev/null +++ b/codec/daemon/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/codec/daemon/Makefile b/codec/daemon/Makefile new file mode 100644 index 0000000..1d25a4c --- /dev/null +++ b/codec/daemon/Makefile @@ -0,0 +1,36 @@ +# Makefile for building the MediaCodec daemon inside Termux. +# +# make -C daemon # build build/termux-va +# make -C daemon install # install to $PREFIX/libexec/lfa-codec/termux-va +# +# The canonical release build is the NDK cross build from termux-va +# (scripts/build-ndk.sh, NDK 29.0.14206865). This Makefile is the on-device +# path: Termux's clang already targets bionic, but its default API level is +# too low for the MediaCodec NDK calls used here, so the target triple pins +# API 29 explicitly. +# +# -lmediandk provides both AMediaCodec_* and AMediaFormat_* symbols. + +CC ?= clang +ANDROID_TARGET ?= aarch64-linux-android29 +CFLAGS ?= -O2 -Wall -Wextra -std=c11 +PREFIX ?= /data/data/com.termux/files/usr +BINDIR ?= $(PREFIX)/libexec/lfa-codec + +ROOT := .. +BUILD := $(ROOT)/build +TARGET := $(BUILD)/termux-va + +.PHONY: all install clean + +all: $(TARGET) + +$(TARGET): termux-va.c $(ROOT)/common/tva_protocol.h + mkdir -p $(BUILD) + $(CC) -target $(ANDROID_TARGET) $(CFLAGS) -I$(ROOT)/common -o $@ termux-va.c -lmediandk -llog -landroid + +install: $(TARGET) + install -Dm700 $(TARGET) $(BINDIR)/termux-va + +clean: + rm -rf $(BUILD) diff --git a/codec/daemon/termux-va.c b/codec/daemon/termux-va.c new file mode 100644 index 0000000..6bd8d2b --- /dev/null +++ b/codec/daemon/termux-va.c @@ -0,0 +1,2888 @@ +/* + * SPDX-License-Identifier: GPL-3.0-or-later + * + * termux-va - Android MediaCodec hardware decode proxy daemon for Termux + * Copyright (C) 2026 lfdevs + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, version 3 of the License. + * + * ****************************************************************************** + * MODIFICATION NOTICE (GPL-3.0 section 5) + * + * This file is a MODIFIED version of src/decode-daemon.c from the + * droidspaces-media-decode project (Apache License, Version 2.0, + * https://github.com/... droidspaces-media-decode). It was ported to the + * termux-va project and relicensed under the GNU General Public License + * version 3. Summary of the modifications relative to the original file: + * + * 1. Renamed decode-daemon -> termux-va. + * 2. The TCP transport was REMOVED entirely: the daemon listens on a + * path-based Unix socket only. Dropped: DEFAULT_PORT, the AF_INET + * listener, SO_REUSEADDR, TCP_NODELAY and the positional port + * argument. The wire-level transport identifier 0 was renamed + * XFER_TCP -> XFER_INLINE (value unchanged, wire format unchanged). + * 3. Default endpoint resolution: TERMUX_VA_SOCKET (full path) > + * TERMUX_VA_SOCKET_DIR (directory) > $TMPDIR/termux-va/termux-va.sock, + * with a termux-x11-style TMPDIR fallback chain. + * 4. Parent directories of the socket are created recursively. + * 5. Protocol constants were extracted into common/tva_protocol.h + * (values unchanged; that header is mirrored into the Mesa bridge). + * 6. Socket file name decode.sock -> termux-va.sock. + * 7. Comments and log messages were translated to English. + * 8. Planar MediaCodec YUV420 output is normalized to the protocol's NV12 + * layout, including a direct SHM conversion path. + * 9. MediaFormat key names are passed as string literals to avoid runtime + * dependencies on optional exported key variables. + * 10. Decoder backpressure waits track output progress; stalled or cancelled + * sessions wake both workers before releasing MediaCodec and SHM. + * + * Everything else - the DMD v3 wire protocol, the MediaCodec session + * lifecycle, the memfd/SCM_RIGHTS shared-memory handoff, the drain + * semantics and the concurrency model - is kept faithful to the original. + * ****************************************************************************** + * + * Listens on a path-based Unix socket, receives H.264/HEVC/VP8/VP9/AV1 units, + * decodes them with MediaCodec in hardware, and returns NV12 frames. + * Consumers live in Linux containers sharing Termux's tmp directory + * (proot --shared-tmp mounts it as the container /tmp). + * + * Wire protocol (see common/tva_protocol.h and doc/protocol.md): + * client -> daemon: [4B unit length, big-endian][unit data] + * (H.264/HEVC: one Annex B NALU; VP8/VP9: full frame; + * AV1: one complete temporal unit) + * daemon -> client: [4B w][4B h][4B size][4B unit-index] + NV12 data + * (inline), or a 24-byte SHM control message + * + * Concurrency structure (one session per client, two threads per session): + * + * accept thread --+-> session 1 --+-- input thread : recv unit -> queueInputBuffer + * | \-- output thread: dequeueOutputBuffer -> send frame + * \-> session 2 --+-- ... + * + * Why send and receive must be separate threads: an early version ran + * "recv -> feed decoder -> take frame -> send 3.1MB" serially in one + * thread; while sending, nothing was received and no frame was dequeued, + * so the hardware decoder idled. That structure saturated 85.6% of one + * core (73% sys) and became the bottleneck of the whole pipeline. + */ +#include +#include +#include +#include +#include +#include +#include /* htonl/ntohl: byte order of the wire format only */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include /* flock: single-instance check, see main() */ +#include /* open/O_*: do not rely on to pull + * these in - bionic/glibc pass but musl fails to + * compile without it (verified upstream 2026-08-25) */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +/* MediaFormat keys are string literals in Android's MediaFormat API. Use + * them directly instead of importing AMEDIAFORMAT_KEY_* data symbols from + * libmediandk: some device builds do not export those variables even though + * the corresponding MediaFormat functions are available. */ +#define TVA_MF_KEY_BIT_RATE "bitrate" +#define TVA_MF_KEY_COLOR_FORMAT "color-format" +#define TVA_MF_KEY_DISPLAY_CROP "crop" +#define TVA_MF_KEY_FRAME_RATE "frame-rate" +#define TVA_MF_KEY_HEIGHT "height" +#define TVA_MF_KEY_I_FRAME_INTERVAL "i-frame-interval" +#define TVA_MF_KEY_MAX_HEIGHT "max-height" +#define TVA_MF_KEY_MAX_INPUT_SIZE "max-input-size" +#define TVA_MF_KEY_MAX_WIDTH "max-width" +#define TVA_MF_KEY_MIME "mime" +#define TVA_MF_KEY_SLICE_HEIGHT "slice-height" +#define TVA_MF_KEY_STRIDE "stride" +#define TVA_MF_KEY_WIDTH "width" + +#include "tva_protocol.h" + +#define INPUT_TIMEOUT_US 5000000 +#define OUTPUT_TIMEOUT_US 20000 +#define INPUT_POLL_US 100000 +#define DEFAULT_STALL_MS 15000 +#define SEND_CHUNK 262144 +#define MAX_ENCODE_PACKET (64u * 1024u * 1024u) + +/* MediaCodec buffer flags (not every NDK version exports these constants) */ +#define FLAG_KEY_FRAME 1 +#define FLAG_CODEC_CONFIG 2 +#define FLAG_END_OF_STREAM 4 + +/* Android MediaCodec colour-format values used by byte-buffer decoders. + * The wire protocol deliberately exposes one layout (linear NV12), so + * planar output must be converted before it reaches the container-side VA + * bridge. Keep these values local instead of depending on non-NDK codec + * headers; the Qualcomm values are also used by FFmpeg's MediaCodec code. */ +#define COLOR_FORMAT_YUV420_PLANAR 0x13 +#define COLOR_FORMAT_YUV420_PACKED_PLANAR 0x14 +#define COLOR_FORMAT_YUV420_SEMIPLANAR 0x15 +#define COLOR_FORMAT_YUV420_PACKED_SEMIPLANAR 0x27 +#define COLOR_FORMAT_YUV420_FLEXIBLE 0x7f420888 +#define COLOR_QCOM_YUV420_SEMIPLANAR 0x7fa30c00 +#define COLOR_QCOM_YUV420_SEMIPLANAR_32M 0x7fa30c04 +#define COLOR_QCOM_YUV420_SEMIPLANAR_64X32 0x7fa30c03 +#define COLOR_TI_YUV420_SEMIPLANAR 0x7f000100 +#define COLOR_TI_YUV420_SEMIPLANAR_INTERLACED 0x7f000001 + +enum OutputLayout { + OUTPUT_LAYOUT_NV12 = 0, + OUTPUT_LAYOUT_I420 = 1, +}; + +/* ------------------------------------------------------------------ log */ +/* + * 0=quiet (errors only) 1=info (connections/session stats, default) + * 2=debug (per-frame) + * + * -t adds a local wall-clock timestamp to every emitted log line. + * + * Per-frame logging must stay at level 2 and off by default: an early + * version did fprintf + fflush per frame, synchronously hitting the disk, + * which contributed measurably to the sys-time share. At the default + * level those calls are skipped entirely. + */ +static int log_level = 1; +static int log_timestamps = 0; +static pthread_mutex_t log_lock = PTHREAD_MUTEX_INITIALIZER; + +static void log_prefix(void) +{ + if (!log_timestamps) + return; + + struct timeval tv; + struct tm tm; + if (gettimeofday(&tv, NULL) == 0 && + localtime_r(&tv.tv_sec, &tm) != NULL) { + fprintf(stderr, "[%02d-%02d %02d:%02d:%02d.%03ld] ", + tm.tm_mon + 1, tm.tm_mday, + tm.tm_hour, tm.tm_min, tm.tm_sec, + (long)(tv.tv_usec / 1000)); + } else { + /* A real device always has a usable realtime clock; retain the + * line-prefix contract even if a non-standard libc lacks one. */ + fputs("[00-00 00:00:00.000] ", stderr); + } +} + +static void dlog(int lvl, const char *fmt, ...) +{ + if (lvl > log_level) return; + pthread_mutex_lock(&log_lock); + va_list ap; + va_start(ap, fmt); + log_prefix(); + vfprintf(stderr, fmt, ap); + va_end(ap); + fputc('\n', stderr); + /* flush info-and-above immediately; debug level stays buffered */ + if (lvl <= 1) fflush(stderr); + pthread_mutex_unlock(&log_lock); +} + +/* Android 15 and newer require an application-side Binder thread pool for + * Codec2 callbacks. Resolve the NDK Binder entry points dynamically so the + * daemon remains loadable on older releases while matching FFmpeg's + * MediaCodec initialization path. */ +static void android_binder_threadpool_init(void) +{ +#if defined(__ANDROID__) +#if __ANDROID_API__ >= 24 + if (android_get_device_api_level() < 35) + return; +#endif + typedef bool (*set_max_threads_fn)(uint32_t); + typedef void (*start_thread_pool_fn)(void); + + void *handle = dlopen("libbinder_ndk.so", RTLD_NOW | RTLD_LOCAL); + if (!handle) { + dlog(1, "Binder thread pool unavailable: %s", dlerror()); + return; + } + + set_max_threads_fn set_max = (set_max_threads_fn)dlsym( + handle, "ABinderProcess_setThreadPoolMaxThreadCount"); + start_thread_pool_fn start = (start_thread_pool_fn)dlsym( + handle, "ABinderProcess_startThreadPool"); + if (!start) { + dlog(2, "ABinderProcess_startThreadPool unavailable"); + return; + } + if (set_max) + dlog(2, "ABinderProcess_setThreadPoolMaxThreadCount(1) => %s", + set_max(1) ? "ok" : "fail"); + start(); + dlog(2, "ABinderProcess_startThreadPool() called"); +#endif +} + +/* ----------------------------------------------------------- exit control */ +static volatile sig_atomic_t running = 1; + +/* self-pipe: the running flag alone cannot wake a main loop blocked in + * accept(); on a signal we write one byte to the pipe so the select() + * before accept() returns immediately and SIGTERM is handled promptly + * (otherwise the only way out is SIGKILL). */ +static int wakefd[2] = { -1, -1 }; + +static void on_signal(int s) +{ + (void)s; + running = 0; + if (wakefd[1] >= 0) { + ssize_t r = write(wakefd[1], "x", 1); + (void)r; /* errors cannot be handled inside a signal handler */ + } +} + +/* -------------------------------------------------------- endpoint probe */ +/* + * (st_dev, st_ino) of the listening endpoint: after bind+listen succeeds we + * stat() the final socket path once, and every handshake response reports + * it verbatim. The client stats the same path on its side and compares -- + * a mismatch means the client resolved a stale socket (classic cause: a + * platform bind-mounting the single socket file instead of the directory + * while the daemon restarted and changed the inode). Historically both + * sides could even stat the SAME orphan inode, which made this extremely + * hard to diagnose by hand; having the daemon report the truth and the + * client verify turns it into an automatic error. + * Abstract-namespace endpoints have no path; they report 0 and the client + * skips the check. + */ +static uint64_t g_ep_dev = 0; +static uint64_t g_ep_ino = 0; + +/* Called after bind/listen succeeds: capture the real endpoint identity + * and apply the TEST-ONLY overrides. */ +static void endpoint_probe(const char *sock_path) +{ + struct stat st; + if (sock_path && stat(sock_path, &st) == 0 && S_ISSOCK(st.st_mode)) { + g_ep_dev = (uint64_t)st.st_dev; + g_ep_ino = (uint64_t)st.st_ino; + } + /* ---- TEST-ONLY: for local verification of the client's mismatch + * path only; never set in deployment. ---- */ + const char *fake = getenv("DMD_TEST_FAKE_INO"); + if (fake && *fake) { + unsigned long long d = 0, i = 0; + if (sscanf(fake, "%llu:%llu", &d, &i) == 2) { + g_ep_dev = (uint64_t)d; + g_ep_ino = (uint64_t)i; + dlog(1, "[TEST-ONLY] endpoint override: dev=%llu ino=%llu", d, i); + } else { + dlog(1, "[TEST-ONLY] DMD_TEST_FAKE_INO format is \"dev:ino\", ignored"); + } + } +} + +/* + * Shared-memory pool: SHM_SLOTS slots used in rotation; the client returns + * a slot by resetting its state word. + * + * Slot size is computed from the negotiated resolution (4K NV12 needs + * 12441600 bytes; a hardcoded 8MB is not enough) with alignment headroom: + * width aligned to 128, height to 32, then x1.5. The whole pool is + * rebuilt if the resolution grows mid-stream. + * + * SHM_SLOTS must stay >= the bridge-side pipeline depth (DMD_PIPELINE_DEPTH, + * 6 in src/gallium/frontends/va/tva_bridge.c of the Mesa tree): the bridge + * keeps issuing decode requests while pending < 6 without collecting + * frames, so a 4-slot pool hits "all busy" at frame 5. These two constants + * live in different repositories; changing either requires checking the + * other. 8 slots is ~95MB at 4K (8 x 12533760) and buys no-frame-loss + * under slow consumers. + */ +/* TVA: shm_slot_bytes() kept identical to upstream (alignment 128x32, 1.5 + * bytes per pixel, 64KB floor), computed against the adaptive-playback + * ceiling rather than the negotiated resolution - see the comment inside. */ +static size_t shm_slot_bytes(int w, int h) +{ + /* Compute against the ceiling declared for adaptive playback, not the + * handshake resolution. + * + * The decoder is configured with MAX_WIDTH/MAX_HEIGHT = max(w,1920) x + * max(h,1088) and promises not to exceed that. If slots were sized for + * the current resolution only, a mid-stream resolution increase + * (480p->720p) would overflow the slot and force the SHM session to + * terminate - the same stream decodes fully over inline delivery but + * truncates over SHM. That was measured upstream as a real regression. + * + * The cost is that a 720p stream also reserves 1080p-sized slots + * (4 x 3133440 ~= 12 MB) - trading memory for correctness, which beats + * silently dropping the second half of the stream. */ + int mw = w > 1920 ? w : 1920; + int mh = h > 1088 ? h : 1088; + size_t aw = ((size_t)mw + 127) & ~(size_t)127; + size_t ah = ((size_t)mh + 31) & ~(size_t)31; + size_t sz = aw * ah * 3 / 2; + return sz < 64 * 1024 ? 64 * 1024 : sz; +} + +/* MIME of each supported decoder or encoder (see upstream + * doc/verified-platform-facts.md for the capability matrix). + * + * This is a static id->MIME mapping only; it does not mean the device has + * the corresponding hardware. AV1 needs an Iris-class decoder (Snapdragon + * 8 Elite tier); SM8150 has no such unit. Actual availability is decided + * by MediaCodec at configure time - failing to obtain a codec fails the + * session, which is the intended behavior; no per-device branching here. */ +static const char *codec_mime(int id) +{ + switch (codec_base_id(id)) { + case CODEC_H264: return "video/avc"; + case CODEC_HEVC: return "video/hevc"; + case CODEC_VP9: return "video/x-vnd.on2.vp9"; + case CODEC_VP8: return "video/x-vnd.on2.vp8"; + case CODEC_AV1: return "video/av01"; + default: return NULL; + } +} + +/* ------------------------------------------------------------ utilities */ +/* + * H.264 NAL unit type. The start code may be 3 bytes (00 00 01) or + * 4 bytes (00 00 00 01); the nal_unit_header must be read AFTER skipping + * the start code, otherwise with a 4-byte start code buf[3]==0x01 and + * SPS(7)/PPS(8) are misread as type 1, so the CSD is never recognized. + * Returns -1 when the type cannot be determined. + */ +static int nalu_type(const uint8_t *b, size_t len) +{ + size_t off = 0; + if (len >= 4 && b[0] == 0 && b[1] == 0 && b[2] == 0 && b[3] == 1) off = 4; + else if (len >= 3 && b[0] == 0 && b[1] == 0 && b[2] == 1) off = 3; + if (off == 0 || off >= len) return -1; + return b[off] & 0x1f; +} + +/* + * Whether this unit is a parameter set that must accumulate into the CSD. + * + * H.264: nal_unit_type = low 5 bits of the header byte, SPS=7 PPS=8 + * HEVC: nal_unit_type = bits 1-6 of the first header byte, VPS=32 SPS=33 PPS=34 + * VP8/VP9: no Annex B parameter-set concept; whole frames are fed as-is + */ +static int is_param_set(int codec_id, const uint8_t *b, size_t len) +{ + if (codec_id == CODEC_H264) { + int t = nalu_type(b, len); + return (t == 7 || t == 8); + } + if (codec_id == CODEC_HEVC) { + size_t off = 0; + if (len >= 4 && b[0] == 0 && b[1] == 0 && b[2] == 0 && b[3] == 1) off = 4; + else if (len >= 3 && b[0] == 0 && b[1] == 0 && b[2] == 1) off = 3; + if (off == 0 || off >= len) return 0; + int t = (b[off] >> 1) & 0x3f; + return (t == 32 || t == 33 || t == 34); + } + /* VP8 / VP9 / AV1 always return 0: they do not use Annex-B start codes + * and have no independent parameter-set NALUs. AV1's sequence header + * is an OBU_SEQUENCE_HEADER inside the temporal unit that the consumer + * forwards as a whole; the daemon needs no special handling. */ + return 0; +} + +static int recv_all(int fd, void *b, size_t l) +{ + char *p = b; + while (l > 0) { + ssize_t n = read(fd, p, l); + if (n < 0 && errno == EINTR) continue; + if (n <= 0) return -1; + p += n; l -= n; + } + return 0; +} + +/* + * Returns 0 on success, SEND_PEER_GONE when the peer closed normally, + * -1 on a real error. + * + * "Peer closed" is a separate bucket because a consumer closing after it + * has enough frames is a normal shutdown (ffmpeg -f null, player + * seek/stop), while the daemon usually still has a few frames in flight; + * writing to the closed fd yields EPIPE/ECONNRESET. Upstream measured + * 78.6% of 412 real sessions ending this way; logging them as "send + * failed" would bury real faults under noise. Byte-level accounting + * confirmed no frames are lost on this path: 933120000 bytes on disk / + * (1920x1080x1.5) = exactly 300.000 frames. + */ +#define SEND_PEER_GONE (-2) + +static int send_all(int fd, const void *b, size_t l) +{ + const char *p = b; + while (l > 0) { + ssize_t n = write(fd, p, l); + if (n < 0 && errno == EINTR) continue; + if (n < 0) { + /* Decoder sockets have a bounded send wait so an unresponsive + * consumer cannot pin codec buffers indefinitely. */ + if (errno == EPIPE || errno == ECONNRESET) { + dlog(2, "send_all: peer closed (%s)", strerror(errno)); + return SEND_PEER_GONE; + } + if (errno == EAGAIN || errno == EWOULDBLOCK) { + dlog(1, "send_all: receiver stalled (socket send timeout)"); + return -1; + } + dlog(1, "send_all: write failed: %s", strerror(errno)); + return -1; + } + if (n == 0) { + dlog(2, "send_all: write returned 0 (peer closed)"); + return SEND_PEER_GONE; + } + p += n; l -= n; + } + return 0; +} + +/* ---------------------------------------------------------------- session */ +typedef struct { + int fd; + AMediaCodec *codec; + volatile sig_atomic_t stop; /* set on any-direction error; both threads exit */ + volatile sig_atomic_t input_done; /* input thread finished (EOS attempted) */ + unsigned int output_progress; /* atomic count of returned codec buffers */ + int stall_timeout_ms; + int w, h; /* written by the output thread only */ + long units_in; + long frames_out; + /* Pipeline tail frames that could not be delivered after the client + * closed early. Not frame loss: the client no longer needs them + * (upstream verified per-frame md5 against the software reference, + * 10/10 identical). Counted separately so operations can tell a + * normal shutdown from a transport fault at a glance. */ + long frames_dropped_at_exit; + int peer_gone; /* client closed normally, not a fault */ + int id; + + /* handshake result */ + int codec_id; /* CodecId, defaults to CODEC_H264 */ + const char *mime; + int encoder; /* raw NV12 input -> encoded packets */ + uint32_t bitrate; /* encoder target, bits per second */ + uint32_t fps_num; /* encoder input frame rate */ + uint32_t fps_den; + int encoder_stride; + int encoder_slice_height; + int avc_profile_verified; /* explicit profile matched an output SPS */ + int negotiated; /* 1 = client completed the handshake */ + + /* output format details (written by the output thread only) */ + int stride; + int slice_height; + int crop_l, crop_t, crop_r, crop_b; + int fmt_sent; /* descriptor for the current format sent */ + int fmt_changes; /* format change count (including first) */ + int color_format; /* MediaCodec "color-format", -1 if absent */ + int output_layout; /* enum OutputLayout; -1 until known */ + uint8_t *convert_buf; /* reusable I420 -> NV12 conversion buffer */ + size_t convert_cap; + + /* shared-memory transport */ + XferMode xfer; + int shm_fd; /* memfd, -1 = not established */ + int shm_listen; /* abstract socket listen fd, -1 = none */ + char shm_name[64]; /* abstract socket name, chosen by the daemon */ + uint8_t *shm_base; /* mmap base */ + size_t shm_slot; /* bytes per slot */ + size_t shm_total; /* pool size including control area */ + int shm_next; /* next slot to write */ + + /* Reversible drain (in-band request of length 0) + * + * drain_req is incremented by the input thread, drain_done by the + * output thread after finishing the EOS handling + AMediaCodec_flush. + * The input thread waits until they are equal before feeding more + * data, otherwise new data would be flushed away too (lost frames). */ + volatile sig_atomic_t drain_req; + volatile sig_atomic_t drain_done; + + /* Input unit index used as the PTS tag (starting at 1). Written by the + * input thread only. Gives every output frame a traceable "which + * submission" identity; the bridge pairs surfaces by this index and + * never needs to know the decoder's output order. */ + uint64_t vcl_in; + /* CSD copy: flush clears the parameter sets inside the decoder, so + * after a drain they must be re-sent verbatim. SPS+PPS is tiny; + * 256 bytes is enough (1080p measured at 31+9). */ + uint8_t csd_keep[256]; + size_t csd_keep_len; +} Session; + +/* + * Shared-memory pool layout: + * + * [control area 4096 bytes][slot 0][slot 1] ... [slot SHM_SLOTS-1] + * + * Each slot has a 32-bit state word in the control area; the daemon sets + * it to 1 after writing (occupied), the client resets it to 0 when done + * (free). Accessed with __atomic builtins, no lock needed. The return + * path therefore never occupies the socket or interleaves with the unit + * uplink. + */ + +static inline volatile uint32_t *shm_slot_state(Session *s, int idx) +{ + return (volatile uint32_t *)(s->shm_base + (size_t)idx * sizeof(uint32_t)); +} + +static inline uint8_t *shm_slot_data(Session *s, int idx) +{ + return s->shm_base + SHM_CTRL_BYTES + (size_t)idx * s->shm_slot; +} + +/* A fatal worker exit must wake the other direction before the session + * owner joins either thread. Codec stop/delete and SHM teardown remain in + * the owner, after both workers have released their borrowed buffers. */ +static void session_abort(Session *s) +{ + s->stop = 1; + shutdown(s->fd, SHUT_RDWR); +} + +static int decoder_stall_timeout(Session *s) +{ + const char *value = getenv("TERMUX_VA_STALL_TIMEOUT_MS"); + if (!value || !*value) + return DEFAULT_STALL_MS; + char *end; + errno = 0; + long ms = strtol(value, &end, 10); + if (errno || *end || ms < 1000 || ms > 600000) { + dlog(1, "[%d] invalid TERMUX_VA_STALL_TIMEOUT_MS; using %d ms", + s->id, DEFAULT_STALL_MS); + return DEFAULT_STALL_MS; + } + return (int)ms; +} + +static int64_t monotonic_ms(void) +{ + struct timespec ts = {0}; + clock_gettime(CLOCK_MONOTONIC, &ts); + return (int64_t)ts.tv_sec * 1000 + ts.tv_nsec / 1000000; +} + +static ssize_t decoder_input_buffer(Session *s) +{ + int64_t started = monotonic_ms(); + int64_t progress_at = started; + int64_t next_log = started + 5000; + unsigned int progress = __atomic_load_n(&s->output_progress, __ATOMIC_RELAXED); + + while (running && !s->stop) { + /* POLLHUP denotes a fully closed peer, including one with unread + * queued input. Do not treat a write-half close as cancellation: + * shutdown(SHUT_WR) is the protocol's normal end-of-stream request. */ + struct pollfd peer = {.fd = s->fd}; + if (poll(&peer, 1, 0) > 0 && + (peer.revents & (POLLHUP | POLLERR | POLLNVAL))) { + s->peer_gone = 1; + session_abort(s); + return -1; + } + + ssize_t index = AMediaCodec_dequeueInputBuffer(s->codec, INPUT_POLL_US); + if (index >= 0) + return index; + if (index != AMEDIACODEC_INFO_TRY_AGAIN_LATER) { + dlog(1, "[%d] dequeueInputBuffer error: %zd", s->id, index); + session_abort(s); + return index; + } + + int64_t now = monotonic_ms(); + unsigned int current = __atomic_load_n(&s->output_progress, __ATOMIC_RELAXED); + if (current != progress) { + progress = current; + progress_at = now; + } + if (s->stop) + break; + if (now - progress_at >= s->stall_timeout_ms) { + unsigned busy = 0; + if (s->shm_base) { + for (int i = 0; i < SHM_SLOTS; i++) + busy += __atomic_load_n(shm_slot_state(s, i), __ATOMIC_ACQUIRE) != 0; + } + dlog(1, "[%d] decoder stalled: no input buffer or output progress for %lld ms; " + "SHM busy=%u/%d; releasing session", + s->id, (long long)(now - progress_at), busy, + s->shm_base ? SHM_SLOTS : 0); + session_abort(s); + return -1; + } + if (now >= next_log) { + dlog(1, "[%d] input buffers full (waited %lld ms, no output progress %lld ms)", + s->id, (long long)(now - started), (long long)(now - progress_at)); + next_log = now + 5000; + } + } + session_abort(s); + return -1; +} + +/* Pool setup/teardown are defined later; the handshake path needs them. */ +static int shm_prepare(Session *s, int w, int h); +static int shm_handoff(Session *s); +static void shm_teardown(Session *s); + +/* + * Handshake. Reads the first 4 bytes: + * equal to the magic -> read the remaining base fields (plus the + * encoder extension when requested), configure the + * session accordingly, send the handshake response + * anything else -> protocol violation, reject (bare 12-byte status=4) + * Returns 0 to continue, -1 to drop the connection. + * Response format and version negotiation: see the comments inside the + * function and at HELLO_VERSION in common/tva_protocol.h. + */ +static int do_handshake(Session *s) +{ + uint32_t first; + if (recv_all(s->fd, &first, 4) < 0) return -1; /* connected then gone */ + first = ntohl(first); + + if (first != HELLO_MAGIC) { + /* The handshake is REQUIRED: daemon and consumers ship together, and + * the no-handshake weak path is not kept. Without a handshake there + * is no MIME or initial size, and no stride/crop can be delivered. */ + dlog(1, "[%d] missing handshake (first word 0x%08x), rejecting", s->id, first); + /* Same shape as every other rejection (12 bytes): the client reads + * [status][mode][name_len] uniformly; replying only 4 bytes would + * leave it blocked on the remaining 8. */ + uint32_t reply[3] = { htonl(4), htonl(XFER_INLINE), htonl(0) }; + send_all(s->fd, reply, sizeof(reply)); + return -1; + } + + uint32_t rest[5]; + if (recv_all(s->fd, rest, sizeof(rest)) < 0) { + dlog(1, "[%d] incomplete handshake frame", s->id); + return -1; + } + uint32_t ver = ntohl(rest[0]); + uint32_t cid = ntohl(rest[1]); + uint32_t w = ntohl(rest[2]); + uint32_t h = ntohl(rest[3]); + uint32_t xfer = ntohl(rest[4]); /* requested transport, may be downgraded */ + uint32_t bitrate = 0; + uint32_t fps_num = 30, fps_den = 1; + + /* Encoder handshakes append the VA-API target bitrate and frame rate. + * Decoder handshakes remain the original six words, so existing decode + * clients retain byte-compatible protocol-v3 behavior. Zero requests + * the historical daemon default. */ + if (codec_is_encoder((int)cid) && recv_all(s->fd, &bitrate, 4) < 0) { + dlog(1, "[%d] incomplete encoder bitrate in handshake", s->id); + return -1; + } + bitrate = ntohl(bitrate); + if (codec_is_encoder((int)cid)) { + uint32_t rate[2]; + if (recv_all(s->fd, rate, sizeof(rate)) < 0) { + dlog(1, "[%d] incomplete encoder frame rate in handshake", s->id); + return -1; + } + fps_num = ntohl(rate[0]); + fps_den = ntohl(rate[1]); + /* Validate the rate, not the individual rational terms: common + * rates such as 30000/1001 and 60000/1001 exceed 1000 in both fields. */ + if (!fps_num || !fps_den || (uint64_t)fps_num > (uint64_t)fps_den * 1000 || + (uint64_t)fps_num * 1000 < fps_den) { + dlog(1, "[%d] encoder frame rate %u/%u is out of range, using 30/1", + s->id, fps_num, fps_den); + fps_num = 30; + fps_den = 1; + } + } + if (bitrate > 100000000u) { + dlog(1, "[%d] encoder bitrate %u is out of range, using default", + s->id, bitrate); + bitrate = 0; + } + + uint32_t status = 0; + const char *mime = (cid < CODEC_MAX) ? codec_mime((int)cid) : NULL; + + /* Version negotiation: the daemon accepts {2..HELLO_VERSION}. Strict + * equality is NOT required - that would force daemon and consumers to + * upgrade in lockstep, and any one-sided update would break everyone. + * A client at version>=3 gets the endpoint extension in the response; + * a v2 client receives exactly the old 12 bytes. */ + if (ver < TVA_VERSION_MIN || ver > HELLO_VERSION) { + dlog(1, "[%d] unsupported handshake version: %u (supported %d..%d)", + s->id, ver, TVA_VERSION_MIN, HELLO_VERSION); + status = 1; + } else if (!mime) { + dlog(1, "[%d] unknown codec id: %u", s->id, cid); + status = 2; + } else if (w < 96 || h < 96 || w > 8192 || h > 4320) { + /* hardware range 96x96 .. 8192x4320 (upstream platform facts) */ + dlog(1, "[%d] resolution out of hardware range: %ux%u", s->id, w, h); + status = 3; + } + + if (status != 0) { + uint32_t reply[3] = { htonl(status), htonl(XFER_INLINE), htonl(0) }; + send_all(s->fd, reply, sizeof(reply)); + return -1; + } + + s->codec_id = (int)cid; + s->mime = mime; + s->encoder = codec_is_encoder((int)cid); + s->bitrate = bitrate; + s->fps_num = fps_num; + s->fps_den = fps_den; + s->w = (int)w; + s->h = (int)h; + s->negotiated = 1; + + /* The SHM pool must exist before the response is sent: the response + * carries the abstract socket name. The daemon picks the name - the + * client cannot know it is connection #N, and guessing would collide. */ + XferMode want = XFER_INLINE; + if (xfer == XFER_SHM && !s->encoder) { + if (shm_prepare(s, (int)w, (int)h) == 0) { + want = XFER_SHM; + } else { + dlog(1, "[%d] SHM pool preparation failed, falling back to inline", s->id); + } + } + + /* + * Response: [4B status][4B actual mode][4B name length][name...] + * Inline mode has name length 0 and no following bytes. + * + * v3 extension (client requested version>=3): bit31 of the namelen word + * is set as a marker (a real namelen is far below 2^31), followed by + * 16 bytes before the name: + * [u32 dev_hi][u32 dev_lo][u32 ino_hi][u32 ino_lo] (each big-endian) + * i.e. g_ep_dev/g_ep_ino split into high/low u32s. + * A v2 client's response is byte-identical to the old daemon; error + * responses keep the bare 12-byte shape, and the client reads status + * before deciding whether to parse the extension. + * + * TEST-ONLY: DMD_TEST_REPLY_LEGACY=1 forces a v2-shaped reply, to + * exercise the client's downgrade path against an old daemon. + */ + size_t nlen = (want == XFER_SHM) ? strlen(s->shm_name) : 0; + int use_ext = (ver >= 3) && getenv("DMD_TEST_REPLY_LEGACY") == NULL; + uint32_t nlen_wire = (uint32_t)nlen; + if (use_ext) + nlen_wire |= 0x80000000u; + uint32_t reply[3] = { htonl(0), htonl((uint32_t)want), htonl(nlen_wire) }; + if (send_all(s->fd, reply, sizeof(reply)) < 0) goto reply_fail; + if (use_ext) { + uint32_t ext[4] = { + htonl((uint32_t)(g_ep_dev >> 32)), htonl((uint32_t)(g_ep_dev & 0xffffffffu)), + htonl((uint32_t)(g_ep_ino >> 32)), htonl((uint32_t)(g_ep_ino & 0xffffffffu)), + }; + if (send_all(s->fd, ext, sizeof(ext)) < 0) goto reply_fail; + } + if (nlen > 0 && send_all(s->fd, s->shm_name, nlen) < 0) goto reply_fail; + + if (want == XFER_SHM) { + /* The client has the name; now wait for it to pick up the memfd */ + if (shm_handoff(s) == 0) { + s->xfer = XFER_SHM; + } else { + /* A failed handoff can only downgrade. The client times out + * into inline delivery on its side as well. */ + shm_teardown(s); + s->xfer = XFER_INLINE; + dlog(1, "[%d] SHM handoff failed, falling back to inline", s->id); + } + } else { + s->xfer = XFER_INLINE; + } + + /* Frame return has exactly two modes: SHM (memfd zero-copy) or inline + * on the control connection. + * + * TVA: upstream deliberately did NOT print "TCP" here even when it + * meant inline - the field describes "frames do not go through SHM but + * are inlined on the control connection", regardless of the control + * transport. That ambiguity once cost upstream a misdiagnosis. With + * TCP removed the naming is unambiguous: SHM or inline. The control + * transport is always the Unix socket printed by "listening on ...". */ + if (s->encoder) + dlog(1, "[%d] handshake ok: encoder %s %ux%u transport=%s bitrate=%u fps=%u/%u", + s->id, mime, w, h, s->xfer == XFER_SHM ? "SHM" : "inline", + s->bitrate, s->fps_num, s->fps_den); + else + dlog(1, "[%d] handshake ok: decoder %s %ux%u transport=%s", + s->id, mime, w, h, s->xfer == XFER_SHM ? "SHM" : "inline"); + return 0; + +reply_fail: + shm_teardown(s); + return -1; +} + +/* + * Input thread: reads units from the socket and feeds the decoder. + * SPS/PPS accumulate into codec-specific data submitted with + * FLAG_CODEC_CONFIG; they produce no frames. + */ +static void *input_thread(void *arg) +{ + Session *s = arg; + uint8_t *buf = malloc(MAX_FRAME); + uint8_t *csd = malloc(MAX_FRAME); + size_t csd_len = 0; + + if (!buf || !csd) { + dlog(0, "[%d] input buffer allocation failed", s->id); + session_abort(s); + goto done; + } + + while (running && !s->stop) { + uint32_t sz; + if (recv_all(s->fd, &sz, 4) < 0) break; /* client closed, normal end */ + sz = ntohl(sz); + + /* Length 0 = drain request (reversible), not a data unit. + * + * Why it exists: the consumer keeps only ~3 frames in flight while + * the decoder needs a 4th input unit before emitting its first + * frame when B-frames are present - a mutual wait. The consumer + * used to force frames out with shutdown(SHUT_WR), but that is + * IRREVERSIBLE: the session is dead and must be rebuilt (measured + * at 155 ms per frame, playback 4.7x slower). + * + * EOS + AMediaCodec_flush is reversible in the sense that the + * session object stays usable: EOS makes the decoder emit whatever + * it holds, then flush resets it and the CSD is re-sent, and the + * session continues without a new connection. + * + * NOTE: "reversible" refers to the SESSION OBJECT only, not to + * lossless video. flush DESTROYS the reference-frame chain; P/B + * frames decoded after it stay black until the next IDR (upstream + * measured 135/708 all-black frames in a browser before tightening + * the drain trigger). Drain is a picture-quality-costly operation + * and the bridge triggers it almost never (wait_is_futile logic). + * + * sz==0 carries it: it used to be an illegal length that old + * clients never send, so no protocol version negotiation is needed. */ + if (sz == 0) { + s->drain_req++; + dlog(2, "[%d] drain request #%u", s->id, s->drain_req); + + ssize_t di = AMediaCodec_dequeueInputBuffer(s->codec, INPUT_TIMEOUT_US); + if (di < 0) { + dlog(1, "[%d] drain: dequeueInputBuffer failed: %zd", s->id, di); + continue; + } + /* Queue EOS: the decoder emits everything queued and held back. */ + AMediaCodec_queueInputBuffer(s->codec, di, 0, 0, 0, FLAG_END_OF_STREAM); + + /* Wait for the output thread to see the EOS and finish the + * flush before feeding the next unit. This wait is mandatory: + * flush discards everything inside the decoder, so data queued + * meanwhile would be lost with it (lost frames). + * + * The wait MUST be bounded. The output thread may have exited + * early on a decode error, in which case drain_done never + * catches up and an unbounded wait leaks the session forever. + * Upstream saw all 8 sessions leak this way, the daemon spin at + * 200% CPU and refuse new connections ("session limit reached") + * while the browser simply decoded nothing - easy to misread as + * an unrelated failure. */ + int waited_us = 0; + const int drain_wait_max_us = 2000000; /* 2s: far above normal drain time */ + while (running && !s->stop && + s->drain_done < s->drain_req && + waited_us < drain_wait_max_us) { + usleep(1000); + waited_us += 1000; + } + if (s->drain_done < s->drain_req) { + dlog(1, "[%d] drain wait timed out (%d ms), abandoning session", + s->id, waited_us / 1000); + s->stop = 1; + break; + } + + /* flush cleared the CSD; it must be re-sent or every following + * VCL unit lacks its parameter sets. Uses the accumulated copy + * saved when the CSD was first submitted. */ + if (s->csd_keep_len > 0) { + ssize_t ci = AMediaCodec_dequeueInputBuffer(s->codec, INPUT_TIMEOUT_US); + if (ci >= 0) { + size_t cap; + uint8_t *ib = AMediaCodec_getInputBuffer(s->codec, ci, &cap); + if (ib && cap >= s->csd_keep_len) { + memcpy(ib, s->csd_keep, s->csd_keep_len); + AMediaCodec_queueInputBuffer(s->codec, ci, 0, + s->csd_keep_len, 0, + FLAG_CODEC_CONFIG); + dlog(2, "[%d] CSD re-sent after drain (%zu bytes)", + s->id, s->csd_keep_len); + } else { + AMediaCodec_queueInputBuffer(s->codec, ci, 0, 0, 0, 0); + } + } + } + continue; + } + + if (sz > MAX_FRAME) { + dlog(1, "[%d] illegal unit length: %u", s->id, sz); + session_abort(s); + goto done; + } + if (recv_all(s->fd, buf, sz) < 0) { + dlog(1, "[%d] reading unit data interrupted", s->id); + session_abort(s); + goto done; + } + s->units_in++; + + if (is_param_set(s->codec_id, buf, sz)) { /* parameter set -> CSD */ + if (csd_len + sz <= MAX_FRAME) { + memcpy(csd + csd_len, buf, sz); + csd_len += sz; + } else { + dlog(1, "[%d] CSD accumulation over limit, dropped", s->id); + } + continue; + } + + if (csd_len > 0) { + ssize_t ci = AMediaCodec_dequeueInputBuffer(s->codec, INPUT_TIMEOUT_US); + if (ci >= 0) { + size_t cap; + uint8_t *ib = AMediaCodec_getInputBuffer(s->codec, ci, &cap); + if (ib && cap >= csd_len) { + memcpy(ib, csd, csd_len); + AMediaCodec_queueInputBuffer(s->codec, ci, 0, csd_len, 0, + FLAG_CODEC_CONFIG); + dlog(2, "[%d] CSD submitted (%zu bytes)", s->id, csd_len); + /* Keep a copy: the flush after a drain clears the CSD + * inside the decoder and it must be re-sent verbatim, + * or later VCL units have no parameter sets. */ + if (csd_len <= sizeof(s->csd_keep)) { + memcpy(s->csd_keep, csd, csd_len); + s->csd_keep_len = csd_len; + } + } else { + dlog(1, "[%d] CSD exceeds input buffer capacity", s->id); + AMediaCodec_queueInputBuffer(s->codec, ci, 0, 0, 0, 0); + } + } else { + dlog(1, "[%d] dequeueInputBuffer(CSD) failed: %zd", s->id, ci); + } + csd_len = 0; + } + + /* Dequeue an input buffer: failure here MUST be retried, never + * silently dropped - dropping any VCL unit destroys the reference + * chain and the picture is corrupted from that point on. + * + * When does it happen? The input buffers are full, which only + * occurs with aggressive feeders: ffmpeg and Firefox keep few + * frames in flight and never trigger it; Chrome bursts hundreds of + * decode requests and upstream measured 259 queued units exhausting + * the input buffers, after which "dequeue failed: -1" ended the + * session and Chrome lost hardware decoding entirely. + * + * Input-buffer exhaustion is BACKPRESSURE, not an error. Keep + * waiting while output buffers are being returned; cancel only + * after a complete interval without progress, or a peer close. */ + ssize_t bi = decoder_input_buffer(s); + if (bi < 0) + goto done; /* no buffer available: end the session, do not drop frames */ + size_t cap = 0; + uint8_t *ib = AMediaCodec_getInputBuffer(s->codec, bi, &cap); + if (!ib || cap < sz) { + dlog(1, "[%d] unit exceeds input buffer capacity (%u > %zu)", s->id, sz, cap); + session_abort(s); + goto done; + } + memcpy(ib, buf, sz); + /* PTS = index of this data unit (starting at 1, 1us steps). + * + * Not for timing: it gives every input unit a RETURNABLE identity. + * MediaCodec carries presentationTimeUs verbatim onto the matching + * output frame (verified upstream: values and strides match, never + * rewritten). The output thread puts it into the frame header so + * the bridge knows exactly which submission a frame belongs to and + * can pair it with a surface by submission index - completely + * independent of the decoder's output order. + * + * That removes the need for the consumer to guess or negotiate the + * output order: display order or decode order, the pairing is + * correct either way. Relying on output order was fragile: any + * mismatch between the two sides produced silently misordered video + * (105/150 frames out of order in an upstream measurement). + * + * Starting at 1: 0 is the "no PTS info" sentinel. */ + media_status_t queued = AMediaCodec_queueInputBuffer(s->codec, bi, 0, sz, + (int64_t)s->vcl_in * PTS_UNIT_SCALE, 0); + if (queued != AMEDIA_OK) { + dlog(1, "[%d] queueInputBuffer failed: %d", s->id, queued); + session_abort(s); + goto done; + } + s->vcl_in++; + } + + /* Submit end-of-stream so the output thread can deterministically + * collect the remaining frames. The correct way with buffered input is + * an empty buffer flagged EOS, not AMediaCodec_signalEndOfInputStream + * (that is for Surface input). */ + if (!s->stop) { + ssize_t bi = AMediaCodec_dequeueInputBuffer(s->codec, INPUT_TIMEOUT_US); + if (bi >= 0) { + AMediaCodec_queueInputBuffer(s->codec, bi, 0, 0, 0, FLAG_END_OF_STREAM); + dlog(2, "[%d] EOS submitted", s->id); + } else { + dlog(1, "[%d] could not submit EOS: %zd", s->id, bi); + } + } + +done: + free(buf); + free(csd); + s->input_done = 1; + return NULL; +} + +/* + * Create the shared-memory pool and hand the memfd to the client through an + * abstract socket. + * + * The name is derived from the session (dmd-shm---); the + * client listens on it right after the handshake response. An abstract + * socket is used instead of a path-based one because the container and + * Termux share the network namespace (abstract sockets belong to the net + * namespace and are visible on both sides), while mount namespaces are + * separate - a path-based Unix socket created by the daemon would not exist + * under the container's mount view. + * + * Returns 0 on success; on failure the caller degrades to inline delivery. + */ +static int shm_prepare(Session *s, int w, int h) +{ + s->shm_slot = shm_slot_bytes(w, h); + s->shm_total = SHM_CTRL_BYTES + s->shm_slot * SHM_SLOTS; + + s->shm_fd = (int)syscall(SYS_memfd_create, "dmd-frames", MFD_CLOEXEC); + if (s->shm_fd < 0) { + dlog(1, "[%d] memfd_create failed: %s", s->id, strerror(errno)); + return -1; + } + if (ftruncate(s->shm_fd, (off_t)s->shm_total) < 0) { + dlog(1, "[%d] ftruncate failed: %s", s->id, strerror(errno)); + goto fail; + } + s->shm_base = mmap(NULL, s->shm_total, PROT_READ | PROT_WRITE, + MAP_SHARED, s->shm_fd, 0); + if (s->shm_base == MAP_FAILED) { + dlog(1, "[%d] mmap failed: %s", s->id, strerror(errno)); + s->shm_base = NULL; + goto fail; + } + memset(s->shm_base, 0, SHM_CTRL_BYTES); /* mark all slots free */ + + /* The daemon picks the name and listens: the client cannot know which + * connection number it is, and guessing would collide or miss. + * + * pid + session id is already unique, but predictable - any process in + * the same net namespace could bind the name first, making the daemon's + * bind fail and degrading the session (no fd leak, but a cheap + * downgrade attack). A 32-bit random suffix removes predictability. */ + snprintf(s->shm_name, sizeof(s->shm_name), "dmd-shm-%d-%d-%08x", + (int)getpid(), s->id, (unsigned)arc4random()); + + s->shm_listen = socket(AF_UNIX, SOCK_STREAM, 0); + if (s->shm_listen < 0) { + dlog(1, "[%d] abstract socket creation failed: %s", s->id, strerror(errno)); + goto fail; + } + struct sockaddr_un ua; + memset(&ua, 0, sizeof(ua)); + ua.sun_family = AF_UNIX; + ua.sun_path[0] = 0; /* abstract namespace */ + strncpy(ua.sun_path + 1, s->shm_name, sizeof(ua.sun_path) - 2); + socklen_t ulen = (socklen_t)(offsetof(struct sockaddr_un, sun_path) + + 1 + strlen(s->shm_name)); + if (bind(s->shm_listen, (struct sockaddr *)&ua, ulen) < 0 || + listen(s->shm_listen, 1) < 0) { + dlog(1, "[%d] abstract socket bind/listen failed: %s", s->id, strerror(errno)); + close(s->shm_listen); + s->shm_listen = -1; + goto fail; + } + return 0; + +fail: + if (s->shm_base) { munmap(s->shm_base, s->shm_total); s->shm_base = NULL; } + if (s->shm_fd >= 0) { close(s->shm_fd); s->shm_fd = -1; } + return -1; +} + +/* + * Wait for the client to connect and hand over the memfd. Must be called + * after the handshake response - the client learns the name from it. + */ +static int shm_handoff(Session *s) +{ + /* Bounded wait: the client may have crashed or may not understand SHM; + * never block the session indefinitely */ + fd_set rs; + FD_ZERO(&rs); + FD_SET(s->shm_listen, &rs); + struct timeval tv = { 3, 0 }; + int r = select(s->shm_listen + 1, &rs, NULL, NULL, &tv); + if (r <= 0) { + dlog(1, "[%d] timed out waiting for the client to pick up SHM", s->id); + return -1; + } + int cs = accept(s->shm_listen, NULL, NULL); + if (cs < 0) { + dlog(1, "[%d] accept failed: %s", s->id, strerror(errno)); + return -1; + } + + /* SCM_RIGHTS carries the fd; the slot parameters accompany it so the + * client can mmap correctly */ + uint32_t meta[3] = { + htonl((uint32_t)SHM_SLOTS), + htonl((uint32_t)s->shm_slot), + htonl((uint32_t)s->shm_total) + }; + struct iovec io = { meta, sizeof(meta) }; + char cbuf[CMSG_SPACE(sizeof(int))]; + memset(cbuf, 0, sizeof(cbuf)); + struct msghdr mh; + memset(&mh, 0, sizeof(mh)); + mh.msg_iov = &io; mh.msg_iovlen = 1; + mh.msg_control = cbuf; mh.msg_controllen = sizeof(cbuf); + struct cmsghdr *cm = CMSG_FIRSTHDR(&mh); + cm->cmsg_level = SOL_SOCKET; + cm->cmsg_type = SCM_RIGHTS; + cm->cmsg_len = CMSG_LEN(sizeof(int)); + memcpy(CMSG_DATA(cm), &s->shm_fd, sizeof(int)); + + if (sendmsg(cs, &mh, 0) < 0) { + dlog(1, "[%d] memfd transfer failed: %s", s->id, strerror(errno)); + close(cs); + return -1; + } + close(cs); + + /* handoff complete; the listener is no longer needed */ + close(s->shm_listen); + s->shm_listen = -1; + + dlog(1, "[%d] SHM handed over: %d slots x %zu bytes (total %zu)", + s->id, SHM_SLOTS, s->shm_slot, s->shm_total); + return 0; +} + +static void shm_teardown(Session *s) +{ + if (s->shm_listen >= 0) { close(s->shm_listen); s->shm_listen = -1; } + if (s->shm_base) { munmap(s->shm_base, s->shm_total); s->shm_base = NULL; } + if (s->shm_fd >= 0) { close(s->shm_fd); s->shm_fd = -1; } +} + +/* Find a free SHM slot and claim it for the output thread. The caller must + * publish the slot (or reset its state word on conversion failure). */ +static int shm_claim_slot(Session *s) +{ + /* Find a free slot. Rotation starts at shm_next so all slots get fair + * use; the client resets the state word when done. + * + * The wait bound must stay well above the bridge-side per-call frame + * timeout (DMD_FRAME_TIMEOUT_MS, 5000ms in tva_bridge.c): the client may + * legitimately block 5 seconds on each fetch, while an early version + * here gave up after 1 second and killed the whole session - + * 1000 < 5000 is a bug by construction. Upstream measured 4K + slow + * consumer (ffmpeg to disk) triggering it 10/10 times, dropping 56-83% + * of frames with the client reporting "Conversion failed!". This was + * the only real frame-loss path in the module. + * + * A transiently exhausted pool is NORMAL BACKPRESSURE, not a fault: as + * long as the client is alive we keep waiting and let the client's own + * timeout decide when to give up. Same stance as Wayland + * wl_buffer.release, GstBufferPool blocking, V4L2 buffer pools - none of + * them treat pool exhaustion as fatal. */ + int slot = -1; + for (int spin = 0; spin < SHM_SLOT_WAIT_MS && slot < 0; spin++) { + for (int k = 0; k < SHM_SLOTS; k++) { + int idx = (s->shm_next + k) % SHM_SLOTS; + uint32_t st = __atomic_load_n(shm_slot_state(s, idx), __ATOMIC_ACQUIRE); + if (st == 0) { slot = idx; break; } + } + if (slot < 0) { + /* client gone or daemon exiting: treat as "peer left", not a fault */ + if (!running || s->stop) return SEND_PEER_GONE; + /* leave a trace during long waits to diagnose slow consumers + * (one line every 2 seconds) */ + if (spin > 0 && spin % 2000 == 0) + dlog(2, "[%d] all slots busy, waited %d ms (slow consumer, normal backpressure)", + s->id, spin); + usleep(1000); + } + } + if (slot < 0) { + /* full bound elapsed with no slot - the client is genuinely stuck */ + dlog(1, "[%d] no free slot after %d ms (client stuck), ending session", + s->id, SHM_SLOT_WAIT_MS); + return -1; + } + + return slot; +} + +/* Publish one frame through a claimed shared-memory slot. The control + * message is six words: [w][h][sentinel][slot][length][unit index]. */ +static int shm_publish_slot(Session *s, int slot, size_t len, uint32_t pts) +{ + if (slot < 0 || slot >= SHM_SLOTS || len > s->shm_slot) + return -1; + + /* release ordering: make the data visible before the state word */ + __atomic_store_n(shm_slot_state(s, slot), 1u, __ATOMIC_RELEASE); + s->shm_next = (slot + 1) % SHM_SLOTS; + + /* 6th word = input unit index, same meaning as the 4th field of the + * inline frame header, so both delivery modes expose identical pairing + * information to the bridge. */ + uint32_t msg[6] = { + htonl((uint32_t)s->w), htonl((uint32_t)s->h), + htonl(SHMFRAME_SENTINEL), + htonl((uint32_t)slot), htonl((uint32_t)len), + htonl(pts) + }; + int rc = send_all(s->fd, msg, sizeof(msg)); + if (rc < 0) { + /* notify failed: release the slot immediately or the pool leaks */ + __atomic_store_n(shm_slot_state(s, slot), 0u, __ATOMIC_RELEASE); + return rc; + } + return 0; +} + +static int send_frame_shm(Session *s, const uint8_t *data, size_t len, + uint32_t pts) +{ + if (!data || len > s->shm_slot) { + dlog(1, "[%d] frame of %zu bytes exceeds slot of %zu, pool rebuild needed", + s->id, len, s->shm_slot); + return -1; + } + + int slot = shm_claim_slot(s); + if (slot < 0) + return slot; + memcpy(shm_slot_data(s, slot), data, len); + return shm_publish_slot(s, slot, len, pts); +} + +/* + * Send the format descriptor block (sentinel header + 32 bytes of body). + * Only sent to handshaked clients; old unhandshaked clients would not + * understand it and must not receive it. + * Returns 0 on success, -1 on failure (caller ends the session). + */ +static int send_format_desc(Session *s) +{ + /* Fallback for missing values: use what we know if FORMAT_CHANGED has + * not arrived yet */ + if (s->stride <= 0) s->stride = s->w; + if (s->slice_height <= 0) s->slice_height = s->h; + if (s->crop_r <= 0) s->crop_r = s->w - 1; + if (s->crop_b <= 0) s->crop_b = s->h - 1; + + /* Word 2 used to be a reserved 0 and is now the capability flags: + * CAP_FRAME_PTS announces that every frame header carries the 4th + * field (PTS = input unit index). Old daemons keep it 0 and clients + * parse 3-word headers accordingly - backwards compatible. */ + uint32_t hdr[3] = { htonl(0), htonl(CAP_FRAME_PTS), + htonl(FMTDESC_SENTINEL) }; + uint32_t body[FMTDESC_WORDS] = { + htonl((uint32_t)s->w), htonl((uint32_t)s->h), + htonl((uint32_t)s->stride), htonl((uint32_t)s->slice_height), + htonl((uint32_t)s->crop_l), htonl((uint32_t)s->crop_t), + htonl((uint32_t)s->crop_r), htonl((uint32_t)s->crop_b) + }; + if (send_all(s->fd, hdr, sizeof(hdr)) < 0 || + send_all(s->fd, body, sizeof(body)) < 0) { + dlog(1, "[%d] failed to send format descriptor", s->id); + s->stop = 1; + return -1; + } + s->fmt_sent = 1; + return 0; +} + +static int media_color_format_is_planar(int color_format) +{ + switch (color_format) { + case COLOR_FORMAT_YUV420_PLANAR: + case COLOR_FORMAT_YUV420_PACKED_PLANAR: + case COLOR_FORMAT_YUV420_FLEXIBLE: + return 1; + default: + return 0; + } +} + +static int media_color_format_is_semiplanar(int color_format) +{ + switch (color_format) { + case COLOR_FORMAT_YUV420_SEMIPLANAR: + case COLOR_FORMAT_YUV420_PACKED_SEMIPLANAR: + case COLOR_QCOM_YUV420_SEMIPLANAR: + case COLOR_QCOM_YUV420_SEMIPLANAR_32M: + case COLOR_QCOM_YUV420_SEMIPLANAR_64X32: + case COLOR_TI_YUV420_SEMIPLANAR: + case COLOR_TI_YUV420_SEMIPLANAR_INTERLACED: + return 1; + default: + return 0; + } +} + +/* Convert one linear I420 byte buffer to the linear NV12 layout promised by + * the termux-va protocol. MediaCodec's planar buffers use half-width U/V + * strides, while the protocol's interleaved UV plane uses the full luma + * stride. Padding rows/columns are retained so the bridge can continue to + * locate UV at stride * slice-height without a format-specific path. + * + * The conversion buffer belongs to the output thread and is reused for every + * frame. Returning -1 leaves the caller free to terminate the session when + * a malformed or truncated MediaCodec buffer is encountered. */ +struct I420Layout { + size_t stride; + size_t slice; + size_t chroma_width; + size_t chroma_rows; + size_t in_chroma_stride; + size_t y_bytes; + size_t uv_bytes; + size_t total; +}; + +static int i420_layout(Session *s, size_t len, struct I420Layout *layout) +{ + if (!layout || s->w <= 0 || s->h <= 0 || + s->stride <= 0 || s->slice_height <= 0) + return -1; + + size_t stride = (size_t)s->stride; + size_t slice = (size_t)s->slice_height; + size_t width = (size_t)s->w; + size_t chroma_width = (width + 1) / 2; + size_t chroma_rows = (slice + 1) / 2; + size_t in_chroma_stride = (stride + 1) / 2; + size_t y_bytes; + size_t in_chroma_bytes; + size_t in_need_tight; + size_t in_need_full; + size_t uv_bytes; + + if (stride > SIZE_MAX / slice) + return -1; + y_bytes = stride * slice; + if (in_chroma_stride > SIZE_MAX / chroma_rows) + return -1; + in_chroma_bytes = in_chroma_stride * chroma_rows; + if (in_chroma_bytes > (SIZE_MAX - y_bytes) / 2) + return -1; + in_need_tight = y_bytes + in_chroma_bytes * 2; + + /* A few codecs use a full luma stride for each planar chroma plane. The + * normal Android I420 layout is the tight half-width form; recognize the + * full-stride form only when the buffer length identifies it exactly. */ + if (stride > SIZE_MAX / chroma_rows) + return -1; + in_chroma_bytes = stride * chroma_rows; + if (in_chroma_bytes > (SIZE_MAX - y_bytes) / 2) + return -1; + in_need_full = y_bytes + in_chroma_bytes * 2; + if (len == in_need_full && in_need_full != in_need_tight) + in_chroma_stride = stride; + else if (len < in_need_tight) + return -1; + + if (chroma_width > stride / 2) + return -1; + if (stride > SIZE_MAX / chroma_rows) + return -1; + uv_bytes = stride * chroma_rows; + if (y_bytes > SIZE_MAX - uv_bytes) + return -1; + + layout->stride = stride; + layout->slice = slice; + layout->chroma_width = chroma_width; + layout->chroma_rows = chroma_rows; + layout->in_chroma_stride = in_chroma_stride; + layout->y_bytes = y_bytes; + layout->uv_bytes = uv_bytes; + layout->total = y_bytes + uv_bytes; + return 0; +} + +static int convert_i420_to_nv12_dst(Session *s, const uint8_t *src, size_t len, + uint8_t *dst, size_t dst_cap, + size_t *out_len) +{ + struct I420Layout layout; + if (!src || !dst || !out_len || i420_layout(s, len, &layout) < 0 || + dst_cap < layout.total) + return -1; + + const size_t stride = layout.stride; + const size_t chroma_rows = layout.chroma_rows; + const size_t chroma_width = layout.chroma_width; + const size_t in_chroma_stride = layout.in_chroma_stride; + const size_t y_bytes = layout.y_bytes; + const size_t uv_bytes = layout.uv_bytes; + + memcpy(dst, src, y_bytes); + memset(dst + y_bytes, 0, uv_bytes); + + const uint8_t *u = src + y_bytes; + const uint8_t *v = u + in_chroma_stride * chroma_rows; + uint8_t *uv = dst + y_bytes; + for (size_t row = 0; row < chroma_rows; row++) { + const uint8_t *ur = u + row * in_chroma_stride; + const uint8_t *vr = v + row * in_chroma_stride; + uint8_t *uvr = uv + row * stride; + for (size_t col = 0; col < chroma_width; col++) { + uvr[col * 2] = ur[col]; + uvr[col * 2 + 1] = vr[col]; + } + } + + *out_len = layout.total; + return 0; +} + +static int convert_i420_to_nv12(Session *s, const uint8_t *src, size_t len, + const uint8_t **out, size_t *out_len) +{ + struct I420Layout layout; + if (!src || !out || !out_len || i420_layout(s, len, &layout) < 0) + return -1; + + if (s->convert_cap < layout.total) { + uint8_t *p = realloc(s->convert_buf, layout.total); + if (!p) + return -1; + s->convert_buf = p; + s->convert_cap = layout.total; + } + + if (convert_i420_to_nv12_dst(s, src, len, s->convert_buf, + s->convert_cap, out_len) < 0) + return -1; + *out = s->convert_buf; + return 0; +} + +/* AV1's MediaCodec output is I420 on the target. For SHM delivery, write + * the normalized NV12 frame straight into the claimed slot so the output + * thread avoids a temporary full-frame conversion copy. */ +static int send_frame_shm_i420(Session *s, const uint8_t *data, size_t len, + uint32_t pts) +{ + struct I420Layout layout; + if (!data || i420_layout(s, len, &layout) < 0 || + layout.total > s->shm_slot) { + dlog(1, "[%d] invalid I420 output for SHM: %zu bytes (slot %zu)", + s->id, len, s->shm_slot); + return -1; + } + + int slot = shm_claim_slot(s); + if (slot < 0) + return slot; + + size_t out_len = 0; + uint8_t *dst = shm_slot_data(s, slot); + if (convert_i420_to_nv12_dst(s, data, len, dst, s->shm_slot, + &out_len) < 0) { + __atomic_store_n(shm_slot_state(s, slot), 0u, __ATOMIC_RELEASE); + dlog(1, "[%d] I420 to NV12 conversion failed for SHM frame", s->id); + return -1; + } + return shm_publish_slot(s, slot, out_len, pts); +} + +/* + * Output thread: dequeues decoded frames and writes them back to the + * socket. Fully decoupled from the input thread - sending a large frame + * never blocks unit reception or decoder feeding. + */ +static void *output_thread(void *arg) +{ + Session *s = arg; + int idle_after_eof = 0; + + while (running && !s->stop) { + AMediaCodecBufferInfo info; + ssize_t oi = AMediaCodec_dequeueOutputBuffer(s->codec, &info, OUTPUT_TIMEOUT_US); + + if (oi >= 0) { + idle_after_eof = 0; + int eos = (info.flags & FLAG_END_OF_STREAM) != 0; + + /* Handshaked clients must receive the format descriptor before + * any frame. Normally FORMAT_CHANGED arrives first, but do not + * depend on it: if the decoder yields a frame directly, send + * the descriptor from known values to keep the client aligned. */ + if (!s->fmt_sent && info.size > 0) { + if (send_format_desc(s) == 0) + dlog(2, "[%d] format descriptor sent late (FORMAT_CHANGED had not arrived)", s->id); + } + + if (info.size > 0 && !s->stop) { + size_t osz; + uint8_t *ob = AMediaCodec_getOutputBuffer(s->codec, oi, &osz); + if (ob) { + int rc = -1; + size_t off = (size_t)info.offset; + size_t frame_size = (size_t)info.size; + const uint8_t *frame_data = NULL; + + if (off <= osz && frame_size <= osz - off) { + frame_data = ob + off; + + if (s->output_layout < 0) + s->output_layout = s->codec_id == CODEC_AV1 + ? OUTPUT_LAYOUT_I420 + : OUTPUT_LAYOUT_NV12; + + } else { + dlog(0, "[%d] invalid output buffer range: offset=%zu size=%zu buffer=%zu", + s->id, off, frame_size, osz); + } + + if (frame_data) { + uint32_t pts = (uint32_t)(info.presentationTimeUs / + PTS_UNIT_SCALE); + bool i420 = s->output_layout == OUTPUT_LAYOUT_I420; + + /* The AV1 decoder on the target returns + * COLOR_FormatYUV420Planar (I420), unlike the NV12 + * output used by H.264/HEVC. Keep the wire format + * stable and normalize the frame. SHM delivery can + * convert directly into the claimed slot to avoid a + * second full-frame copy through convert_buf. */ + if (i420 && s->xfer == XFER_SHM) { + rc = send_frame_shm_i420(s, frame_data, frame_size, + pts); + } else { + if (i420 && + convert_i420_to_nv12(s, frame_data, frame_size, + &frame_data, &frame_size) < 0) { + dlog(0, "[%d] invalid I420 output buffer: %zu bytes", + s->id, frame_size); + frame_data = NULL; + } + if (frame_data && s->xfer == XFER_SHM) { + rc = send_frame_shm(s, frame_data, frame_size, + pts); + } else if (frame_data) { + /* 4th field = input unit index of this + * frame. MediaCodec carries the + * presentationTimeUs given at + * queueInputBuffer verbatim onto the output + * frame, so the bridge knows exactly which + * submission produced it. */ + uint32_t hdr[4] = { + htonl((uint32_t)s->w), + htonl((uint32_t)s->h), + htonl((uint32_t)frame_size), + htonl(pts) + }; + rc = send_all(s->fd, hdr, sizeof(hdr)); + size_t frame_off = 0; + size_t rem = frame_size; + while (rc == 0 && rem > 0) { + size_t ch = rem > SEND_CHUNK ? SEND_CHUNK : rem; + rc = send_all(s->fd, frame_data + frame_off, ch); + if (rc != 0) break; + frame_off += ch; + rem -= ch; + } + } + } + } + if (rc == SEND_PEER_GONE) { + /* The client took enough frames and closed normally; + * the remainder are pipeline tail frames (14 in the + * upstream measurement). A normal shutdown, not a + * fault: per-frame md5 matched the software + * reference 10/10 with no loss. Counted separately, + * logged at debug level. */ + s->frames_dropped_at_exit++; + if (!s->stop) + s->peer_gone = 1; + s->stop = 1; + } else if (rc < 0) { + dlog(1, "[%d] frame send failed (transport error), ending session", s->id); + s->stop = 1; + } else { + s->frames_out++; + dlog(2, "[%d] frame %dx%d %zu bytes", s->id, s->w, s->h, frame_size); + } + } + } + media_status_t released = AMediaCodec_releaseOutputBuffer(s->codec, oi, 0); + if (released != AMEDIA_OK) { + dlog(1, "[%d] releaseOutputBuffer failed: %d", s->id, released); + session_abort(s); + break; + } + __atomic_add_fetch(&s->output_progress, 1u, __ATOMIC_RELAXED); + if (eos) { + /* EOS has two sources with very different handling: + * 1) drain request (drain_req > drain_done) - the session + * stays alive; flush resets the decoder and the input + * thread re-sends the CSD + * 2) the client really closed its write end - end of + * stream, exit the thread + * The discriminator is whether a drain request is pending. */ + if (s->drain_req > s->drain_done) { + media_status_t fs = AMediaCodec_flush(s->codec); + if (fs != AMEDIA_OK) { + dlog(1, "[%d] flush after drain failed: %d", s->id, fs); + s->stop = 1; + break; + } + /* flush discards undelivered output; the format + * descriptor must be re-sent too or the client keeps + * parsing with stale stride/crop and every subsequent + * frame is misaligned. */ + s->fmt_sent = 0; + s->drain_done++; + dlog(2, "[%d] drain #%u complete, session continues", s->id, s->drain_done); + continue; + } + dlog(2, "[%d] EOS received, output finished", s->id); + break; + } + } else if (oi == AMEDIACODEC_INFO_OUTPUT_FORMAT_CHANGED) { + AMediaFormat *of = AMediaCodec_getOutputFormat(s->codec); + if (of) { + int w = s->w, h = s->h; + AMediaFormat_getInt32(of, TVA_MF_KEY_WIDTH, &w); + AMediaFormat_getInt32(of, TVA_MF_KEY_HEIGHT, &h); + s->w = w; s->h = h; + + /* stride / slice_height: the decoder output buffer's real + * line pitch and plane height. Qualcomm Venus aligns width + * to 128 and height to 32; without these values the UV + * plane offset cannot be located correctly. */ + int stride = 0, slice = 0; + if (!AMediaFormat_getInt32(of, TVA_MF_KEY_STRIDE, &stride)) + stride = w; + if (!AMediaFormat_getInt32(of, TVA_MF_KEY_SLICE_HEIGHT, &slice)) + slice = h; + s->stride = stride; + s->slice_height = slice; + + int32_t color_format = -1; + int have_color_format = AMediaFormat_getInt32( + of, TVA_MF_KEY_COLOR_FORMAT, &color_format); + s->color_format = have_color_format ? (int)color_format : -1; + if (have_color_format && + media_color_format_is_planar((int)color_format)) { + s->output_layout = OUTPUT_LAYOUT_I420; + } else if (have_color_format && + media_color_format_is_semiplanar((int)color_format)) { + s->output_layout = OUTPUT_LAYOUT_NV12; + } else { + /* AV1 on the tested Qualcomm decoder reports a vendor or + * flexible value inconsistently, but its byte layout is + * still I420. Preserve the historical NV12 assumption + * for other codecs when the format is missing/unknown. */ + s->output_layout = s->codec_id == CODEC_AV1 + ? OUTPUT_LAYOUT_I420 + : OUTPUT_LAYOUT_NV12; + } + + /* Display crop rect: the actually visible region. When + * 1080p decodes into a 1920x1088 buffer, crop_bottom is + * 1079 and the extra 8 rows are alignment padding. */ + int cl = 0, ct = 0, cr = w - 1, cb = h - 1; + AMediaFormat_getRect(of, TVA_MF_KEY_DISPLAY_CROP, + &cl, &ct, &cr, &cb); + s->crop_l = cl; s->crop_t = ct; + s->crop_r = cr; s->crop_b = cb; + AMediaFormat_delete(of); + + s->fmt_changes++; + dlog(1, "[%d] output format %dx%d stride=%d slice=%d color=0x%x layout=%s crop=(%d,%d)-(%d,%d)%s", + s->id, w, h, stride, slice, + (unsigned)(uint32_t)s->color_format, + s->output_layout == OUTPUT_LAYOUT_I420 ? "I420" : "NV12", + cl, ct, cr, cb, + s->fmt_changes > 1 ? " (mid-stream change)" : ""); + + /* Mark for (re)sending: on a mid-stream resolution change + * the client must learn the new stride/crop or it keeps + * parsing with the old geometry and every frame is offset. */ + s->fmt_sent = 0; + send_format_desc(s); + } + } else if (oi == AMEDIACODEC_INFO_OUTPUT_BUFFERS_CHANGED) { + /* nothing to do: with the NDK the buffer pointer is re-fetched + * via getOutputBuffer every time */ + } else if (oi == AMEDIACODEC_INFO_TRY_AGAIN_LATER) { + /* input finished but EOS never comes out: it could not be + * submitted; avoid spinning forever */ + if (s->input_done && ++idle_after_eof > 100) { + dlog(1, "[%d] no output long after input finished, giving up", s->id); + break; + } + } else { + dlog(1, "[%d] dequeueOutputBuffer unexpected: %zd", s->id, oi); + break; + } + } + /* Also covers unexpected MediaCodec errors and failed EOS delivery. + * The input worker may otherwise stay blocked in recv_all forever. */ + session_abort(s); + return NULL; +} + +/* ------------------------------------------------- concurrent client count */ +static int client_count = 0; +static pthread_mutex_t count_lock = PTHREAD_MUTEX_INITIALIZER; + +static void client_release(void) +{ + pthread_mutex_lock(&count_lock); + client_count--; + pthread_mutex_unlock(&count_lock); +} + +/* ---------------------------------------------------------------- encoder */ +/* + * Encoder sessions deliberately use a small synchronous protocol. The + * bridge sends one packed NV12 frame as a length-prefixed unit and waits for + * the corresponding encoded access unit before sending the next frame. This + * keeps the first implementation deterministic and avoids exposing decoder + * SHM slots to a variable-size bitstream. The Qualcomm C2 components used + * on the target have no B-frame requirement when max-bframes=0, so one output + * packet is available for each input frame. + */ +static int encoder_avc_profile(int codec_id) +{ + /* MediaCodecInfo.CodecProfileLevel values, also used by FFmpeg. */ + switch (codec_id) { + /* VA-API advertises Constrained Baseline; it is also a valid subset + * for WebCodecs callers requesting ordinary Baseline. */ + case CODEC_H264_BASELINE_ENC: return 0x10000; + case CODEC_H264_MAIN_ENC: return 0x02; + case CODEC_H264_HIGH_ENC: return 0x08; + default: return 0; + } +} + +static int encoder_validate_avc_profile(Session *s, const uint8_t *data, size_t len) +{ + int requested = encoder_avc_profile(s->codec_id); + if (!requested) + return 0; + + int expected = requested == 0x10000 ? 66 : requested == 0x02 ? 77 : 100; + /* Inspect SPS headers in codec-config buffers and in-band access units. + * profile_idc precedes any Exp-Golomb/RBSP data, so no bit parser or + * emulation-prevention removal is needed here. */ + for (size_t i = 0; i + 4 < len; i++) { + if (data[i] || data[i + 1] || data[i + 2] != 1 || + (data[i + 3] & 0x1f) != 7) + continue; + int actual = data[i + 4]; + if (actual != expected) { + dlog(0, "[%d] encoder ignored AVC profile: requested profile_idc=%d, got=%d", + s->id, expected, actual); + return -1; + } + if (requested == 0x10000 && (i + 5 >= len || !(data[i + 5] & 0x40))) { + dlog(0, "[%d] encoder returned Baseline without the constrained-baseline flag", + s->id); + return -1; + } + if (!s->avc_profile_verified) + dlog(1, "[%d] verified AVC SPS profile_idc=%d", s->id, actual); + s->avc_profile_verified = 1; + } + return 0; +} + +static int encoder_send_packet(Session *s, const uint8_t *data, size_t len, + uint32_t flags, uint32_t pts) +{ + if (!len || len > MAX_ENCODE_PACKET) + return -1; + /* Also validate assembled codec-config fragments before forwarding the + * first access unit. A successful configure is not proof that the device + * honored the requested profile. */ + if (encoder_validate_avc_profile(s, data, len) < 0) + return -1; + if (encoder_avc_profile(s->codec_id) && !s->avc_profile_verified) { + dlog(0, "[%d] encoder returned no SPS for the explicit AVC profile", s->id); + return -1; + } + + uint32_t hdr[3] = { htonl((uint32_t)len), htonl(flags), htonl(pts) }; + if (send_all(s->fd, hdr, sizeof(hdr)) < 0) + return -1; + size_t off = 0; + while (off < len) { + size_t chunk = len - off; + if (chunk > SEND_CHUNK) + chunk = SEND_CHUNK; + if (send_all(s->fd, data + off, chunk) < 0) + return -1; + off += chunk; + } + s->frames_out++; + return 0; +} + +static int encoder_append_csd(uint8_t **csd, size_t *csd_len, + size_t *csd_cap, const uint8_t *data, size_t len) +{ + if (!len || *csd_len > MAX_FRAME - len) + return -1; + if (*csd_len + len > *csd_cap) { + size_t cap = *csd_cap ? *csd_cap : 4096; + while (cap < *csd_len + len) + cap += cap / 2; + uint8_t *p = realloc(*csd, cap); + if (!p) + return -1; + *csd = p; + *csd_cap = cap; + } + memcpy(*csd + *csd_len, data, len); + *csd_len += len; + return 0; +} + +/* Some Pixel/Exynos VP9 MediaCodec encoders prepend a private key-frame + * header before the normal VP9 frame. Locate the mandatory VP9 sync code so + * the daemon exposes a standards-compliant access unit to VA-API clients. + * The prefix length is device-specific, so do not hard-code it. */ +static size_t vp9_keyframe_prefix(const uint8_t *data, size_t len) +{ + if (!data || len < 4) + return 0; + size_t limit = len < 64 ? len - 3 : 61; + for (size_t i = 0; i < limit; i++) { + if ((data[i] & 0x03) == 0x02 && data[i + 1] == 0x49 && + data[i + 2] == 0x83 && data[i + 3] == 0x42) + return i; + } + return 0; +} + +static int encoder_drain_output(Session *s, uint8_t **csd, size_t *csd_len, + size_t *csd_cap, bool *packet_sent, + uint32_t pts) +{ + for (;;) { + AMediaCodecBufferInfo info; + ssize_t oi = AMediaCodec_dequeueOutputBuffer(s->codec, &info, + OUTPUT_TIMEOUT_US * 250); + if (oi == AMEDIACODEC_INFO_OUTPUT_FORMAT_CHANGED || + oi == AMEDIACODEC_INFO_OUTPUT_BUFFERS_CHANGED) + continue; + if (oi == AMEDIACODEC_INFO_TRY_AGAIN_LATER) + return *packet_sent ? 0 : -1; + if (oi < 0) + return -1; + + size_t osz = 0; + uint8_t *ob = AMediaCodec_getOutputBuffer(s->codec, oi, &osz); + size_t off = info.offset < 0 ? 0 : (size_t)info.offset; + size_t len = info.size < 0 ? 0 : (size_t)info.size; + int rc = 0; + if (!ob || off > osz || len > osz - off) { + dlog(0, "[%d] encoder output range invalid: offset=%zu size=%zu buffer=%zu", + s->id, off, len, osz); + rc = -1; + } else if (encoder_validate_avc_profile(s, ob + off, len) < 0) { + rc = -1; + } else if (info.flags & FLAG_CODEC_CONFIG) { + /* VP9 has no codec-config access unit in the IVF/VA-API path. + * Pixel's Exynos component reports a short private header here; + * forwarding it would make the first VP9 frame undecodable. */ + if (s->codec_id == CODEC_VP9_ENC) { + dlog(1, "[%d] dropped VP9 codec-config buffer: %zu bytes", + s->id, len); + rc = 0; + } else { + rc = encoder_append_csd(csd, csd_len, csd_cap, ob + off, len); + } + } else if (len) { + const uint8_t *payload = ob + off; + size_t payload_len = len; + if (s->codec_id == CODEC_VP9_ENC && s->frames_out == 0 && + (info.flags & FLAG_KEY_FRAME)) { + size_t prefix = vp9_keyframe_prefix(payload, payload_len); + if (prefix) { + payload += prefix; + payload_len -= prefix; + dlog(1, "[%d] stripped VP9 key-frame prefix: %zu bytes", + s->id, prefix); + } + } + size_t total = payload_len + *csd_len; + uint8_t *packet = malloc(total); + if (!packet) + rc = -1; + else { + if (*csd_len) + memcpy(packet, *csd, *csd_len); + memcpy(packet + *csd_len, payload, payload_len); + rc = encoder_send_packet(s, packet, total, + (uint32_t)info.flags, pts); + free(packet); + if (rc == 0) { + *csd_len = 0; + *packet_sent = true; + } + } + } + AMediaCodec_releaseOutputBuffer(s->codec, oi, 0); + if (rc < 0) + return rc; + if (*packet_sent) + return 0; + } +} + +/* MediaCodec byte-buffer input may have storage padding even when width and + * height describe the visible image. Exynos VP9 uses a 64-byte row stride + * and a 16-row slice height. Keep the wire tightly packed and honor the + * negotiated layout when copying into the codec-owned buffer. */ +static int encoder_copy_input(Session *s, uint8_t *dst, size_t capacity, + const uint8_t *src, size_t length, + size_t *queued_size) +{ + if (!s->encoder_stride) { + int32_t stride = 0, slice = 0, color = 0; + AMediaFormat *format = AMediaCodec_getInputFormat(s->codec); + if (format) { + AMediaFormat_getInt32(format, "stride", &stride); + AMediaFormat_getInt32(format, "slice-height", &slice); + AMediaFormat_getInt32(format, "color-format", &color); + AMediaFormat_delete(format); + } + if (color && color != COLOR_FORMAT_YUV420_SEMIPLANAR) { + dlog(0, "[%d] unsupported encoder input color format: 0x%x", s->id, color); + return -1; + } + s->encoder_stride = stride > 0 ? stride : (int)s->w; + s->encoder_slice_height = slice > 0 ? slice : (int)s->h; + dlog(1, "[%d] encoder input NV12 %ux%u stride=%d slice-height=%d", + s->id, s->w, s->h, s->encoder_stride, s->encoder_slice_height); + } + + size_t width = s->w, height = s->h; + size_t stride = s->encoder_stride, slice = s->encoder_slice_height; + if ((width | height | stride | slice) & 1 || stride < width || slice < height || + slice > SIZE_MAX / stride) + return -1; + size_t y_size = stride * slice; + /* CCodec's byte buffer includes padded luma rows, but its chroma plane + * ends at the last visible byte, without trailing row padding. */ + size_t uv_size = stride * (height / 2 - 1) + width; + if (y_size > capacity || uv_size > capacity - y_size || + length != width * height + width * (height / 2)) { + dlog(0, "[%d] encoder input layout does not fit: frame=%zu buffer=%zu", + s->id, length, capacity); + return -1; + } + if (stride == width && slice == height) { + memcpy(dst, src, length); + *queued_size = length; + return 0; + } + /* Initialize padding so stale buffer contents cannot affect the edges. */ + memset(dst, 16, y_size); + memset(dst + y_size, 128, uv_size); + for (size_t y = 0; y < height; y++) + memcpy(dst + y * stride, src + y * width, width); + src += width * height; + for (size_t y = 0; y < height / 2; y++) + memcpy(dst + y_size + y * stride, src + y * width, width); + *queued_size = y_size + uv_size; + return 0; +} + +static int encoder_run(Session *s) +{ + uint8_t *input = malloc(MAX_ENCODE_FRAME); + uint8_t *csd = NULL; + size_t csd_len = 0, csd_cap = 0; + if (!input) + return -1; + + uint32_t frame_no = 0; + for (;;) { + uint32_t sz_be; + if (recv_all(s->fd, &sz_be, sizeof(sz_be)) < 0) + break; + uint32_t sz = ntohl(sz_be); + if (sz == 0) + break; + if (sz > MAX_ENCODE_FRAME || recv_all(s->fd, input, sz) < 0) { + dlog(1, "[%d] invalid encoder input frame size: %u", s->id, sz); + break; + } + s->units_in++; + + ssize_t bi; + int tries = 0; + do { + bi = AMediaCodec_dequeueInputBuffer(s->codec, INPUT_TIMEOUT_US); + if (bi == AMEDIACODEC_INFO_TRY_AGAIN_LATER && ++tries < 12) + continue; + break; + } while (running && !s->stop); + if (bi < 0) + break; + size_t cap = 0; + uint8_t *ib = AMediaCodec_getInputBuffer(s->codec, bi, &cap); + if (!ib || cap < sz) { + dlog(1, "[%d] encoder input buffer too small: %u > %zu", s->id, sz, cap); + break; + } + size_t queued_size = 0; + if (encoder_copy_input(s, ib, cap, input, sz, &queued_size) < 0) + break; + uint32_t pts = ++frame_no; + /* Encoder input timestamps are only used by MediaCodec's rate + * controller. A unit index scaled by 1 ms (the decoder pairing + * convention) would look like a 1000-fps stream and makes bitrate + * control ineffective. Match the input rate negotiated in the + * handshake; the bridge does not use this value for container PTS. */ + /* Round the absolute timestamp instead of accumulating a rounded + * frame duration. Split the division to avoid overflow for valid + * uint32 rational terms and long-running sessions. */ + uint64_t scaled = (uint64_t)pts * 1000000; + int64_t pts_us = (int64_t)((scaled / s->fps_num) * s->fps_den + + ((scaled % s->fps_num) * s->fps_den + s->fps_num / 2) / s->fps_num); + if (AMediaCodec_queueInputBuffer(s->codec, bi, 0, queued_size, + pts_us, 0) != AMEDIA_OK) + break; + + bool packet_sent = false; + if (encoder_drain_output(s, &csd, &csd_len, &csd_cap, + &packet_sent, pts) < 0) + break; + } + + /* Flush any delayed packet before closing the codec. */ + if (s->codec && !s->stop) { + ssize_t bi = AMediaCodec_dequeueInputBuffer(s->codec, INPUT_TIMEOUT_US); + if (bi >= 0) + AMediaCodec_queueInputBuffer(s->codec, bi, 0, 0, 0, + FLAG_END_OF_STREAM); + for (int i = 0; i < 64 && !s->stop; i++) { + AMediaCodecBufferInfo info; + ssize_t oi = AMediaCodec_dequeueOutputBuffer(s->codec, &info, + OUTPUT_TIMEOUT_US); + if (oi == AMEDIACODEC_INFO_TRY_AGAIN_LATER) + continue; + if (oi < 0) + continue; + AMediaCodec_releaseOutputBuffer(s->codec, oi, 0); + if (info.flags & FLAG_END_OF_STREAM) + break; + } + } + free(csd); + free(input); + return 0; +} + +/* + * Session thread: creates the decoder for one client and runs the + * input/output threads until the session ends. + */ +static void *session_thread(void *arg) +{ + Session *s = arg; + AMediaFormat *fmt = NULL; + + /* The handshake must complete before the decoder is configured: it + * decides the MIME and the initial resolution */ + if (do_handshake(s) < 0) goto out_fd; + + if (s->encoder) { + AMediaFormat *enc_fmt = AMediaFormat_new(); + if (!enc_fmt) { + dlog(0, "[%d] AMediaFormat_new failed for encoder", s->id); + goto out_fd; + } + AMediaFormat_setString(enc_fmt, TVA_MF_KEY_MIME, s->mime); + AMediaFormat_setInt32(enc_fmt, TVA_MF_KEY_WIDTH, s->w); + AMediaFormat_setInt32(enc_fmt, TVA_MF_KEY_HEIGHT, s->h); + /* The VA frontend sends -b:v through the encoder handshake. Keep + * the old 8 Mbps value only for clients that leave the field zero. */ + int bitrate = s->bitrate ? (int)s->bitrate : 8 * 1000 * 1000; + AMediaFormat_setInt32(enc_fmt, TVA_MF_KEY_BIT_RATE, bitrate); + if (s->fps_num % s->fps_den == 0) + AMediaFormat_setInt32(enc_fmt, TVA_MF_KEY_FRAME_RATE, + (int)(s->fps_num / s->fps_den)); + else + AMediaFormat_setFloat(enc_fmt, TVA_MF_KEY_FRAME_RATE, + (float)s->fps_num / s->fps_den); + AMediaFormat_setInt32(enc_fmt, TVA_MF_KEY_I_FRAME_INTERVAL, 1); + AMediaFormat_setInt32(enc_fmt, TVA_MF_KEY_MAX_INPUT_SIZE, MAX_ENCODE_FRAME); + /* Qualcomm's byte-buffer encoders accept semi-planar NV12. */ + AMediaFormat_setInt32(enc_fmt, "color-format", COLOR_FORMAT_YUV420_SEMIPLANAR); + /* CBR makes Qualcomm's encoder honor low VA-API targets instead of + * falling back to its quality-based floor in VBR mode. */ + AMediaFormat_setInt32(enc_fmt, "bitrate-mode", 2); /* CBR */ + AMediaFormat_setInt32(enc_fmt, "max-bframes", 0); + AMediaFormat_setInt32(enc_fmt, "low-latency", 1); + int avc_profile = encoder_avc_profile(s->codec_id); + if (avc_profile) { + AMediaFormat_setInt32(enc_fmt, "profile", avc_profile); + dlog(1, "[%d] requested AVC MediaCodec profile=%d", s->id, avc_profile); + } + + s->codec = AMediaCodec_createEncoderByType(s->mime); + if (!s->codec) { + dlog(0, "[%d] no available encoder: %s", s->id, s->mime); + AMediaFormat_delete(enc_fmt); + goto out_fd; + } + char *encoder_name = NULL; + if (AMediaCodec_getName(s->codec, &encoder_name) == AMEDIA_OK && + encoder_name) { + dlog(1, "[%d] selected encoder: %s", s->id, encoder_name); + AMediaCodec_releaseName(s->codec, encoder_name); + } + media_status_t st = AMediaCodec_configure(s->codec, enc_fmt, NULL, NULL, 1); + if (st != AMEDIA_OK) { + dlog(0, "[%d] encoder configure failed: %d", s->id, st); + AMediaFormat_delete(enc_fmt); + goto out_started; + } + st = AMediaCodec_start(s->codec); + AMediaFormat_delete(enc_fmt); + if (st != AMEDIA_OK) { + dlog(0, "[%d] encoder start failed: %d", s->id, st); + goto out_started; + } + encoder_run(s); + dlog(1, "[%d] encoder session end: %ld units in, %ld packets out", + s->id, s->units_in, s->frames_out); + goto out_started; + } + + s->stall_timeout_ms = decoder_stall_timeout(s); + struct timeval send_timeout = { + .tv_sec = s->stall_timeout_ms / 1000, + .tv_usec = (s->stall_timeout_ms % 1000) * 1000, + }; + /* A stalled receiver must not pin a codec output buffer and the input + * worker indefinitely. Never time out reads: an idle/paused client is + * allowed to keep its session without submitting new input. */ + if (setsockopt(s->fd, SOL_SOCKET, SO_SNDTIMEO, + &send_timeout, sizeof(send_timeout)) < 0) { + dlog(1, "[%d] cannot set decoder send timeout: %s", s->id, strerror(errno)); + goto out_fd; + } + + fmt = AMediaFormat_new(); + if (!fmt) { dlog(0, "[%d] AMediaFormat_new failed", s->id); goto out_fd; } + AMediaFormat_setString(fmt, TVA_MF_KEY_MIME, s->mime); + AMediaFormat_setInt32(fmt, TVA_MF_KEY_WIDTH, s->w); + AMediaFormat_setInt32(fmt, TVA_MF_KEY_HEIGHT, s->h); + AMediaFormat_setInt32(fmt, TVA_MF_KEY_MAX_INPUT_SIZE, MAX_FRAME); + + /* adaptive-playback: declare the largest size that may appear later so + * the decoder pre-allocates its output pool accordingly and a + * mid-stream resolution change does not require a reconfigure. + * max(handshake size, 1080p) - larger wastes memory, smaller forces + * reconfiguration after all. */ + int max_w = s->w > 1920 ? s->w : 1920; + int max_h = s->h > 1088 ? s->h : 1088; + AMediaFormat_setInt32(fmt, TVA_MF_KEY_MAX_WIDTH, max_w); + AMediaFormat_setInt32(fmt, TVA_MF_KEY_MAX_HEIGHT, max_h); + + /* Low latency: make the decoder emit frames as soon as possible instead + * of holding a few back to fill its pipeline. + * + * Why it matters: MediaCodec steadies out 2-3 input units behind, while + * a browser's ffmpeg keeps only 3 frames in flight (H.264 has_b_frames=2 + * decides) - it submits the 3rd frame and then blocks in + * vaSyncSurface waiting for the 1st. A one-frame mutual wait -> + * consumer-side flush fallback (irreversible shutdown(SHUT_WR)) -> + * session destroyed -> browser falls back to software decoding + * permanently. Upstream measured Firefox 140 getting exactly one + * hardware frame before dropping to software. Command-line ffmpeg is + * unaffected because it feeds far ahead of consumption. + * + * Why a literal string instead of AMEDIAFORMAT_KEY_LOW_LATENCY: the + * symbol is __INTRODUCED_IN(30) (NdkMediaFormat.h) while this daemon + * builds against API 29. The key is just a string constant; writing + * the literal avoids raising the build API and avoids weak-symbol + * null checks. On devices below API 30 MediaCodec ignores unknown + * keys - the pre-existing behavior, never a failure. + * + * DMD_NO_LOW_LATENCY=1 disables this key for decoder configuration + * diagnostics. It is unset by default, preserving normal behavior. */ + if (!getenv("DMD_NO_LOW_LATENCY")) + AMediaFormat_setInt32(fmt, "low-latency", 1); + + /* Make the decoder output in DECODE order instead of buffering for + * display order. + * + * This is the fix for the black/flickering frames. In display order + * with B-frames the first frame only comes out after the 4th input + * unit, but a browser keeps 3 frames in flight - one-frame mutual wait + * again. Forcing EOS used to be the workaround, but EOS/flush/rebuild + * destroy the reference chain and ~90% of frames came out black + * (luma 16 in 54/60 frames). + * + * With this key the lag drops from 4 to 1 (upstream measured key by + * key: low-latency, max-output-reorder-frames, output-delay, + * vendor.qti-ext-dec-low-latency all had no effect - only this one), + * the mutual wait disappears and drains/rebuilds are no longer needed. + * + * Historical note (resolved): the consumer once needed a compile-time + * constant declaring the decoder's output order and had to agree + * exactly, otherwise frames paired wrongly with no error (105/150 + * misordered). That is gone - every frame now carries its own input + * unit index (CAP_FRAME_PTS) and the bridge pairs by index, fully + * decoupled from the output order. + * + * Literal string: this is a Qualcomm vendor extension, absent from NDK + * headers. Non-Qualcomm platforms ignore the unknown key - the + * pre-existing behavior, never a failure. + * + * DMD_NO_PICTURE_ORDER=1 disables this key for decoder configuration + * diagnostics. It is unset by default, preserving normal behavior. */ + if (!getenv("DMD_NO_PICTURE_ORDER")) + AMediaFormat_setInt32(fmt, "vendor.qti-ext-dec-picture-order.enable", 1); + + s->codec = AMediaCodec_createDecoderByType(s->mime); + if (!s->codec) { dlog(0, "[%d] no available decoder: %s", s->id, s->mime); goto out_fmt; } + + media_status_t st = AMediaCodec_configure(s->codec, fmt, NULL, NULL, 0); + if (st != AMEDIA_OK) { dlog(0, "[%d] configure failed: %d", s->id, st); goto out_started; } + + st = AMediaCodec_start(s->codec); + if (st != AMEDIA_OK) { dlog(0, "[%d] start failed: %d", s->id, st); goto out_started; } + + pthread_t tin, tout; + int have_in = (pthread_create(&tin, NULL, input_thread, s) == 0); + if (!have_in) { dlog(0, "[%d] cannot create input thread", s->id); session_abort(s); } + int have_out = (pthread_create(&tout, NULL, output_thread, s) == 0); + if (!have_out) { dlog(0, "[%d] cannot create output thread", s->id); session_abort(s); } + + if (have_in) pthread_join(tin, NULL); + if (have_out) pthread_join(tout, NULL); + + /* Log the shutdown reason: upstream measured 78.6% of 412 real sessions + * ending as a normal client close, which used to share the "send frame + * failed" log line with real faults, making almost every session look + * broken. */ + if (s->peer_gone) + dlog(1, "[%d] session end (client closed normally): %ld units in, %ld frames out, " + "%ld tail frames undelivered", + s->id, s->units_in, s->frames_out, s->frames_dropped_at_exit); + else + dlog(1, "[%d] session end: %ld units in, %ld frames out", + s->id, s->units_in, s->frames_out); + +out_started: + /* configure / start failures must STILL stop the codec before deleting. + * + * This used to jump straight to delete on failure and the whole daemon + * died with SIGABRT: + * FORTIFY: pthread_mutex_lock called on a destroyed mutex + * Fatal signal 6 (SIGABRT) in tid NNNN (CodecLooper) + * + * As soon as AMediaCodec_createDecoderByType succeeds, Codec2 has + * already started its CodecLooper callback thread. A configure failure + * does not stop it, and deleting immediately destroys a mutex that + * thread is using - the crash is inside Codec2's own thread, so no + * pthread_mutex_destroy in this file is involved. + * + * The blast radius is far beyond one failed session: the watchdog + * restarts five times into cooldown and hardware decoding is dead for + * the whole device, including codecs that worked fine. The trigger is + * any configure failure (exposed on SM8750 when AV1 was added: + * QC2VppFilterCaps does not know c2.qti.av1.decoder). + * + * stop() on a codec that never started is safe: the NDK allows it in + * the Configured state and returns an error code without crashing; the + * return value is deliberately ignored - the only goal is letting + * Codec2 reap its callback thread. */ + AMediaCodec_stop(s->codec); + AMediaCodec_delete(s->codec); +out_fmt: + AMediaFormat_delete(fmt); +out_fd: + shm_teardown(s); + free(s->convert_buf); + close(s->fd); + free(s); + client_release(); + return NULL; +} + +/* -------------------------------------------------- endpoint resolution */ +/* + * TVA: default endpoint resolution (upstream had --sock only, defaulting to + * a TCP listener that termux-va removed). + * + * Order: + * 1. --sock command line argument (handled in main) + * 2. TERMUX_VA_SOCKET - full socket file path + * 3. TERMUX_VA_SOCKET_DIR - directory; TVA_SOCK_NAME is appended + * 4. $TMPDIR/termux-va/termux-va.sock + * + * TMPDIR fallback chain mirrors termux-x11 (cmdentrypoint.cpp): an adb + * shell injects TMPDIR=/data/local/tmp which is NOT what we want, so that + * value is treated as unset; then /tmp is used if it exists (container / + * shared-tmp view), and finally the Termux prefix tmp. + */ +#define TVA_DEFAULT_SOCK_DIR "/data/data/com.termux/files/usr/tmp" + +static const char *resolve_socket_path(char *buf, size_t bufsz) +{ + const char *env_sock = getenv("TERMUX_VA_SOCKET"); + if (env_sock && *env_sock) + return env_sock; + + const char *env_dir = getenv("TERMUX_VA_SOCKET_DIR"); + if (env_dir && *env_dir) { + snprintf(buf, bufsz, "%s/%s", env_dir, TVA_SOCK_NAME); + return buf; + } + + const char *tmp = getenv("TMPDIR"); + if (!tmp || !*tmp || strcmp(tmp, "/data/local/tmp") == 0) { + struct stat st; + if (stat("/tmp", &st) == 0 && S_ISDIR(st.st_mode)) + tmp = "/tmp"; + else + tmp = TVA_DEFAULT_SOCK_DIR; + } + snprintf(buf, bufsz, "%s/%s/%s", tmp, TVA_SOCKET_DIR_NAME, TVA_SOCK_NAME); + return buf; +} + +/* + * TVA: create every missing parent directory of `path` (0755). Upstream + * created at most one level; the termux-va default endpoint lives one level + * below $TMPDIR and env overrides may point deeper, so parents are created + * recursively. The socket file itself is created by bind(), never here. + * Returns 0 on success, -1 on failure. + */ +static int ensure_parent_dirs(const char *path) +{ + char buf[512]; + size_t len = strlen(path); + if (len == 0 || len >= sizeof(buf)) return -1; + memcpy(buf, path, len + 1); + + /* strip trailing slashes so "a/b/" does not end with an empty component */ + while (len > 1 && buf[len - 1] == '/') buf[--len] = '\0'; + + for (char *p = buf + 1; *p; p++) { + if (*p == '/') { + *p = '\0'; + if (mkdir(buf, 0755) < 0 && errno != EEXIST) return -1; + *p = '/'; + } + } + return 0; +} + +/* The daemon socket is intentionally reachable from a shared-tmp container. + * The file mode alone is insufficient: a Chroot user also needs execute/search + * permission on the containing directory. Keep the sticky bit so another + * user cannot replace or remove the daemon's socket or lock file. */ +static int make_socket_parent_shared(const char *sock_path) +{ + char parent[512]; + size_t len = strlen(sock_path); + if (len == 0 || len >= sizeof(parent)) + return -1; + memcpy(parent, sock_path, len + 1); + + char *slash = strrchr(parent, '/'); + if (!slash || slash == parent) + return 0; + *slash = '\0'; + return chmod(parent, 01777); +} + +/* ------------------------------------------------------------------ main */ +static void usage(const char *prog) +{ + printf( + "Usage: %s [options]\n" + " --sock Override the Unix socket location.\n" + " A directory receives the fixed file name %s\n" + " (created if missing); a path ending in .sock is\n" + " used as a single socket file (its inode changes on\n" + " every restart - prefer a directory).\n" + " -v Per-frame debug logging\n" + " -q Errors only\n" + " -t Prefix each log line with a local timestamp\n" + " -h This help\n" + "\n" + "Endpoint resolution order:\n" + " 1. --sock argument\n" + " 2. TERMUX_VA_SOCKET (full socket file path)\n" + " 3. TERMUX_VA_SOCKET_DIR (directory, %s is appended)\n" + " 4. $TMPDIR/%s/%s (TMPDIR falls back to /tmp, then\n" + " %s)\n" + "\n" + "termux-va listens on a path-based Unix socket ONLY - the upstream TCP\n" + "fallback listener was removed. Containers reach the socket through the\n" + "shared tmp directory: with proot-distro --shared-tmp the same directory\n" + "appears as /tmp/%s inside the container.\n" + "\n" + "MediaCodec access requires a SELinux domain that may talk to the media\n" + "services. Termux processes run as a normal app (untrusted_app), which\n" + "is the standard path used by every video app - no root needed.\n", + prog, TVA_SOCK_NAME, TVA_SOCK_NAME, + TVA_SOCKET_DIR_NAME, TVA_SOCK_NAME, TVA_DEFAULT_SOCK_DIR, + TVA_SOCKET_DIR_NAME); +} + +int main(int argc, char **argv) +{ + const char *sock_arg = NULL; /* non-NULL when --sock was given */ + + for (int i = 1; i < argc; i++) { + if (strcmp(argv[i], "-v") == 0) log_level = 2; + else if (strcmp(argv[i], "-q") == 0) log_level = 0; + else if (strcmp(argv[i], "-t") == 0) log_timestamps = 1; + else if (strcmp(argv[i], "--sock") == 0 && i + 1 < argc) { + sock_arg = argv[++i]; + } else if (strcmp(argv[i], "-h") == 0 || strcmp(argv[i], "--help") == 0) { + usage(argv[0]); + return 0; + } else { + /* TVA: upstream accepted a positional TCP port here; the TCP + * transport no longer exists. */ + dlog(0, "unknown argument: %s", argv[i]); + usage(argv[0]); + return 1; + } + } + + signal(SIGINT, on_signal); + signal(SIGTERM, on_signal); + signal(SIGPIPE, SIG_IGN); + + android_binder_threadpool_init(); + + if (pipe(wakefd) < 0) { + int pipe_errno = errno; + dlog(0, "pipe: %s", strerror(pipe_errno)); + return 1; + } + + /* Resolve the endpoint (see resolve_socket_path for the order). */ + char resolved[512]; + const char *sock_path = sock_arg ? sock_arg + : resolve_socket_path(resolved, sizeof(resolved)); + if (!sock_path || !*sock_path) { + dlog(0, "unable to determine the socket path: set --sock, " + "TERMUX_VA_SOCKET, TERMUX_VA_SOCKET_DIR or TMPDIR"); + return 1; + } + + int srv; + + /* A path pointing at a DIRECTORY receives the fixed socket file name + * inside it. + * + * This exists because of bind-mount inode semantics: bind() can only + * create a NEW inode, so every daemon restart changes the socket's + * inode while a bind mount pins an inode. Mounting a single socket + * file means every restart breaks the container side with + * ECONNREFUSED until it is remounted. + * + * Mounting the DIRECTORY has no such problem: the directory inode is + * stable and replacing the socket inside it does not affect the mount. + * The consumer only ever needs: + * Termux $TMPDIR/termux-va/ == container /tmp/termux-va/ + * and the daemon may restart as often as it likes. */ + char sock_in_dir[512]; + char sock_trimmed[512]; + { + /* trim trailing slashes first, otherwise the joined path becomes + * dir//termux-va.sock - functional, but the doubled slash makes + * log lines fail to match what docs and scripts expect. */ + size_t sl = strlen(sock_path); + while (sl > 1 && sock_path[sl - 1] == '/') sl--; + if (sl >= sizeof(sock_trimmed)) { + dlog(0, "socket path too long"); + return 1; + } + memcpy(sock_trimmed, sock_path, sl); + sock_trimmed[sl] = '\0'; + sock_path = sock_trimmed; + + /* stat exactly once and remember the result - do not re-stat or + * read errno in the branches: errno is undefined after a successful + * stat, so branching on it is fragile. */ + struct stat dst; + int st_ok = (stat(sock_path, &dst) == 0); + + if (st_ok && S_ISDIR(dst.st_mode)) { + snprintf(sock_in_dir, sizeof(sock_in_dir), "%s/%s", + sock_path, TVA_SOCK_NAME); + dlog(1, "--sock points at a directory, listening on %s", sock_in_dir); + sock_path = sock_in_dir; + } else if (!st_ok) { + /* The path does not exist. Blindly binding it as a socket file + * would SILENTLY create a single-file socket, which breaks on + * every restart when something bind-mounts the file (inode + * changes). So: a path that looks like a directory (no ".sock" + * suffix) is created as a directory; a .sock path is kept in + * single-file mode with a warning. */ + int wants_dir = (strstr(sock_path, ".sock") == NULL); + if (wants_dir) { + if (mkdir(sock_path, 0755) < 0 && errno != EEXIST) { + int mkdir_errno = errno; + dlog(0, "cannot create directory %s: %s", + sock_path, strerror(mkdir_errno)); + dlog(0, "(if a plain socket file was intended, make the"); + dlog(0, " path end with .sock)"); + return 1; + } + snprintf(sock_in_dir, sizeof(sock_in_dir), "%s/%s", + sock_path, TVA_SOCK_NAME); + dlog(1, "socket directory did not exist, created; listening on %s", + sock_in_dir); + sock_path = sock_in_dir; + } else { + /* TVA: create missing parent directories so an env-provided + * .sock path in a fresh directory works on first start. */ + if (ensure_parent_dirs(sock_path) < 0) { + int parent_errno = errno; + dlog(0, "cannot create parent directories of %s: %s", + sock_path, strerror(parent_errno)); + return 1; + } + dlog(1, "WARNING: %s is a single socket file - its inode changes on" + " every restart; if anything bind-mounts the file, remount" + " after each restart. Prefer passing a directory.", + sock_path); + } + } + } + + /* Unix socket listener: path-based, not part of any net namespace, + * shared with containers through the shared tmp directory. */ + srv = socket(AF_UNIX, SOCK_STREAM, 0); + if (srv < 0) { + int socket_errno = errno; + dlog(0, "socket: %s", strerror(socket_errno)); + return 1; + } + + struct sockaddr_un ua; + memset(&ua, 0, sizeof(ua)); + ua.sun_family = AF_UNIX; + if (strlen(sock_path) >= sizeof(ua.sun_path)) { + dlog(0, "socket path too long (limit %zu): %s", + sizeof(ua.sun_path) - 1, sock_path); + close(srv); return 1; + } + strncpy(ua.sun_path, sock_path, sizeof(ua.sun_path) - 1); + + /* Handling of a leftover socket file - read the deployment-order note. + * + * bind() can only create a NEW inode and cannot bind onto an existing + * file. A bind mount pins an inode, not a path: once the socket is + * unlinked and re-created, the container's mount point refers to an + * orphan inode and connect() returns ECONNREFUSED - while both sides + * may even stat the SAME orphan inode, which looks identical and is + * miserable to debug. + * + * Correct deployment order: + * 1. the daemon starts first and creates the socket file + * 2. the platform bind-mounts the DIRECTORY into the container + * 3. after a daemon restart, only the socket file inside changes + * (directory mounts do not care) + * + * A leftover is only removed once no live listener is confirmed. */ + /* Single-instance check uses flock, NOT a connect() probe. + * + * An early version probed with connect("if it connects, someone is + * serving"). Two problems: + * 1. a blocking socket with an unbounded connect - a full backlog on + * the old instance hangs the new process at startup; worse, if the + * kernel returned EAGAIN it would be misread as "no listener" and + * the LIVE instance's socket file would be unlinked. + * 2. side effects on the live instance: every rejected start made it + * run accept + thread create + teardown and briefly consume a + * concurrency slot. + * + * flock has none of these: it never touches the other process, needs no + * timeout, and the kernel releases the lock no matter how the holder + * dies (including SIGKILL), so no stale "occupied" state survives. The + * lock file lives next to the socket with its own name and the handle + * is deliberately NEVER closed - holding it is what holds the lock for + * the process lifetime. */ + char lockpath[560]; + snprintf(lockpath, sizeof(lockpath), "%s.lock", sock_path); + int lockfd = open(lockpath, O_RDWR | O_CREAT | O_CLOEXEC, 0600); + if (lockfd < 0) { + int lock_errno = errno; + dlog(0, "cannot open lock file %s: %s", + lockpath, strerror(lock_errno)); + close(srv); + return 1; + } + if (flock(lockfd, LOCK_EX | LOCK_NB) < 0) { + int flock_errno = errno; + if (flock_errno == EWOULDBLOCK) + dlog(0, "another instance is already serving %s, refusing to start", sock_path); + else + dlog(0, "flock %s failed: %s", + lockpath, strerror(flock_errno)); + close(lockfd); + close(srv); + return 1; + } + /* Lock acquired: no live instance. lockfd stays open on purpose. */ + + struct stat st; + if (stat(sock_path, &st) == 0 && S_ISSOCK(st.st_mode)) { + /* holding the lock and seeing a socket file = leftover from a dead + * instance, safe to remove. + * NOTE: this changes the inode; existing single-file bind mounts + * must be remounted (directory mounts are unaffected). */ + dlog(1, "removing stale socket file %s" + " (inode will change; single-file bind mounts need a remount)", + sock_path); + unlink(sock_path); + } + + if (bind(srv, (struct sockaddr *)&ua, sizeof(ua)) < 0) { + int bind_errno = errno; + dlog(0, "bind %s failed: %s", sock_path, strerror(bind_errno)); + if (bind_errno == EACCES) + dlog(0, " hint: check the SELinux context of the parent directory; " + "Termux app data directories are writable by the app itself"); + close(srv); return 1; + } + /* 0666 is deliberately permissive: PRoot containers share the Termux uid + * and need nothing special, but chroot/LXC consumers may run as root and + * must be able to connect. A real deployment can tighten this to a + * specific gid (mirroring how anland-termux lets its container scripts + * chmod the directory/socket). */ + if (chmod(sock_path, 0666) < 0) + dlog(1, "chmod %s warning: %s", sock_path, strerror(errno)); + if (make_socket_parent_shared(sock_path) < 0) { + int chmod_errno = errno; + dlog(0, "chmod shared socket directory for %s failed: %s", + sock_path, strerror(chmod_errno)); + close(srv); + unlink(sock_path); + return 1; + } + + if (listen(srv, MAX_CLIENTS) < 0) { + int listen_errno = errno; + dlog(0, "listen failed: %s", strerror(listen_errno)); + close(srv); unlink(sock_path); return 1; + } + /* Startup-success marker for external scripts; keep the format stable. */ + dlog(1, "listening on %s", sock_path); + /* Capture the endpoint identity for the handshake; TEST-ONLY hooks + * apply here too. This is the "server tells the truth" half of the + * inode verification mechanism - the client reconciles against it. */ + endpoint_probe(sock_path); + dlog(1, "listening endpoint: dev=%llu ino=%llu", + (unsigned long long)g_ep_dev, (unsigned long long)g_ep_ino); + fflush(stderr); + + int next_id = 1; + while (running) { + /* select() over the listener and the self-pipe so SIGTERM wakes the + * loop promptly */ + fd_set rs; + FD_ZERO(&rs); + FD_SET(srv, &rs); + FD_SET(wakefd[0], &rs); + int mx = srv > wakefd[0] ? srv : wakefd[0]; + + int sel = select(mx + 1, &rs, NULL, NULL, NULL); + if (sel < 0) { + if (errno == EINTR) continue; + int select_errno = errno; + dlog(0, "select: %s", strerror(select_errno)); + break; + } + if (FD_ISSET(wakefd[0], &rs)) break; /* exit signal */ + if (!FD_ISSET(srv, &rs)) continue; + + int cli = accept(srv, NULL, NULL); + if (cli < 0) { + /* almost all accept() errors affect only this one connection and + * must not take the daemon down. Linux surfaces pending network + * errors on the new connection through accept and the man page + * asks to retry them like EAGAIN. Only real process-level + * failures (fd exhaustion) justify exiting. */ + switch (errno) { + case EINTR: + case ECONNABORTED: + case EAGAIN: +#if defined(EWOULDBLOCK) && EWOULDBLOCK != EAGAIN + case EWOULDBLOCK: +#endif + case EMSGSIZE: + case EPROTO: + case ENOPROTOOPT: + case EHOSTDOWN: + case EHOSTUNREACH: + case ENETDOWN: + case ENETUNREACH: + case ENONET: + case EOPNOTSUPP: + case ETIMEDOUT: + dlog(1, "accept skipped one connection: %s", strerror(errno)); + continue; + default: + /* EMFILE/ENFILE/ENOBUFS/ENOMEM may be transient too, but + * retrying in a loop becomes a busy-wait; restarting from + * outside is cleaner. */ + { + int accept_errno = errno; + dlog(0, "accept: %s", strerror(accept_errno)); + goto accept_loop_done; + } + } + } + + pthread_mutex_lock(&count_lock); + int accepted = (client_count < MAX_CLIENTS); + if (accepted) client_count++; + pthread_mutex_unlock(&count_lock); + + if (!accepted) { + dlog(1, "concurrent session limit %d reached, rejecting new connection", MAX_CLIENTS); + close(cli); + continue; + } + + /* The return buffer MUST be enlarged explicitly or AF_UNIX throughput + * collapses below realtime decode speed. + * + * Upstream measurement (same binary, same hardware, 720p30 HEVC): + * with the default AF_UNIX SO_SNDBUF/SO_RCVBUF of 229376 (224KB), + * a single NV12 frame (720p = 1.38MB, 1080p = 3.11MB) does not fit, + * so every frame filled the buffer over and over, blocking the + * output thread -> MediaCodec output buffers not recycled -> input + * slots exhausted -> "input buffers full" -> session abandoned + * (0.92x realtime). 4MB holds a full 1080p NV12 frame with + * headroom; the kernel doubles the SO_SNDBUF bookkeeping and caps + * at net.core.{w,r}mem_max, so a failed setsockopt degrades to the + * default and is intentionally ignored. */ + { + int bufsz = 4 * 1024 * 1024; + (void)setsockopt(cli, SOL_SOCKET, SO_SNDBUF, &bufsz, sizeof(bufsz)); + (void)setsockopt(cli, SOL_SOCKET, SO_RCVBUF, &bufsz, sizeof(bufsz)); + } + + Session *s = calloc(1, sizeof(Session)); + if (!s) { + dlog(0, "session allocation failed"); + close(cli); + client_release(); + continue; + } + s->fd = cli; + s->w = 1920; /* placeholder until the handshake / FORMAT_CHANGED */ + s->h = 1080; + s->vcl_in = 1; /* PTS tags start at 1: 0 is the "no PTS" sentinel */ + s->id = next_id++; + s->codec_id = CODEC_H264; + s->mime = codec_mime(CODEC_H264); + s->xfer = XFER_INLINE; + s->shm_fd = -1; /* calloc zeroes; 0 is a legal fd, so set -1 here */ + s->shm_listen = -1; + s->color_format = -1; + s->output_layout = -1; + + pthread_t th; + if (pthread_create(&th, NULL, session_thread, s) != 0) { + dlog(0, "cannot create session thread"); + close(cli); + free(s); + client_release(); + continue; + } + pthread_detach(th); + dlog(1, "[%d] client connected", s->id); + } +accept_loop_done: + + close(srv); + /* Remove the socket file or the next start hits EADDRINUSE. (Startup + * also cleans a stale file - belt and braces for signal kills, which + * never reach this point.) */ + unlink(sock_path); + + /* Let running sessions wind down so decoder resources are not yanked */ + for (int i = 0; i < 50; i++) { + pthread_mutex_lock(&count_lock); + int n = client_count; + pthread_mutex_unlock(&count_lock); + if (n == 0) break; + usleep(100000); + } + + dlog(1, "termux-va exiting"); + return 0; +} diff --git a/codec/vaapi/LICENSE b/codec/vaapi/LICENSE new file mode 100644 index 0000000..06bd6e2 --- /dev/null +++ b/codec/vaapi/LICENSE @@ -0,0 +1,190 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to the Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by the Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding any notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + Copyright 2026 DroidSpaces + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. \ No newline at end of file diff --git a/codec/vaapi/Makefile b/codec/vaapi/Makefile new file mode 100644 index 0000000..ffe57d6 --- /dev/null +++ b/codec/vaapi/Makefile @@ -0,0 +1,88 @@ +# LFA MediaCodec VA-API driver +# +# The driver is a libva plugin. LFA installs it as +# /lfa_codec_drv_video.so +# and points consumers at it with LIBVA_DRIVER_NAME=lfa_codec and +# LIBVA_DRIVERS_PATH=. +# +# Build inside the Linux container (aarch64): the host-side x86_64 cross +# toolchain does not carry an aarch64 glibc. + +TARGET := lfa_codec_drv_video.so +SRCDIR := src +BUILD := build + +# libva only provides the headers here. The driver is dlopen()ed by libva +# inside the consumer process, so it must not link libva itself. +VA_CFLAGS := $(shell pkg-config --cflags libva 2>/dev/null) + +# libdrm headers are used for the optional dmabuf export path. Only the +# ioctl definitions and fourcc constants are needed; libdrm itself is not +# linked because the ioctls go straight to the kernel. +DRM_CFLAGS := $(shell pkg-config --cflags libdrm 2>/dev/null) + +CC ?= cc +CFLAGS ?= -O2 -g +# -MMD -MP keeps header changes from leaving a stale .so behind. +CFLAGS += -std=c11 -fPIC -Wall -Wextra -Wno-unused-parameter \ + -fvisibility=hidden -D_GNU_SOURCE $(VA_CFLAGS) $(DRM_CFLAGS) \ + -I$(SRCDIR) -MMD -MP +LDFLAGS += -shared -Wl,--no-undefined -Wl,-z,defs +LDLIBS += -lpthread + +SOURCES := $(SRCDIR)/bitstream.c $(SRCDIR)/driver.c $(SRCDIR)/profiles.c $(SRCDIR)/stubs.c \ + $(SRCDIR)/dmd_client.c $(SRCDIR)/decode.c $(SRCDIR)/image.c \ + $(SRCDIR)/h264_bitstream.c $(SRCDIR)/hevc_bitstream.c $(SRCDIR)/export.c \ + $(SRCDIR)/av1_bitstream.c +OBJECTS := $(patsubst $(SRCDIR)/%.c,$(BUILD)/%.o,$(SOURCES)) +DEPS := $(OBJECTS:.o=.d) + +# LFA keeps the driver out of the distro's own Mesa directory so an update +# cannot replace it and the path is the same on every distro. +DRIDIR ?= /usr/local/lib/lfa-codec/dri +DESTDIR ?= + +.PHONY: all clean install uninstall check gen + +all: $(BUILD)/$(TARGET) + +$(BUILD): + @mkdir -p $(BUILD) + +$(BUILD)/%.o: $(SRCDIR)/%.c | $(BUILD) + $(CC) $(CFLAGS) -c $< -o $@ + +$(BUILD)/$(TARGET): $(OBJECTS) + $(CC) $(OBJECTS) $(LDFLAGS) $(LDLIBS) -o $@ + +# Confirm that the driver entry point is actually exported. -fvisibility=hidden +# relies on VA_DRIVER_INIT_FUNC to export it; without that libva reports +# "has no function __vaDriverInit_*". +check: $(BUILD)/$(TARGET) + @echo "== exported driver entry points ==" + @nm -D --defined-only $(BUILD)/$(TARGET) | grep vaDriverInit || \ + { echo "error: __vaDriverInit_* is not exported"; exit 1; } + +# Regenerate the vtable shims for the libva installed in this container. +# Run this after a libva upgrade or when building against a different distro. +gen: + mkdir -p $(BUILD) + python3 tools/gen_vtable.py /usr/include/va/va_backend.h > $(BUILD)/vtable.json + cd $(BUILD) && mkdir -p out && python3 ../tools/gen_stubs.py vtable.json + cp $(BUILD)/out/stubs.c $(BUILD)/out/stubs.h $(BUILD)/out/vtable.inc $(SRCDIR)/ + +install: $(BUILD)/$(TARGET) + install -d $(DESTDIR)$(DRIDIR) + install -m 0644 $(BUILD)/$(TARGET) $(DESTDIR)$(DRIDIR)/$(TARGET) + @echo "installed $(DESTDIR)$(DRIDIR)/$(TARGET)" + +uninstall: + rm -f $(DESTDIR)$(DRIDIR)/$(TARGET) + @echo "removed $(DESTDIR)$(DRIDIR)/$(TARGET)" + +clean: + rm -rf $(BUILD) + +# Header dependencies generated by -MMD. The leading '-' ignores them on the +# first build. +-include $(DEPS) diff --git a/codec/vaapi/src/av1_bitstream.c b/codec/vaapi/src/av1_bitstream.c new file mode 100644 index 0000000..7d5e130 --- /dev/null +++ b/codec/vaapi/src/av1_bitstream.c @@ -0,0 +1,1097 @@ +/* AV1 OBU 反向合成——变长编码、对齐与 OBU 头。 + * + * 设计说明见 av1_bitstream.h 顶部。本文件只实现最底层的比特写入原语, + * 序列头/帧头/tile group 的语法在后续提交里加。 + */ +#include +#include + +#include "av1_bitstream.h" + +/* ---------------------------------------------------------------- leb128 */ + +size_t dmd_av1_leb128_len(uint64_t v) +{ + size_t n = 0; + do { + n++; + v >>= 7; + } while (v && n < DMD_LEB128_MAX); + return n; +} + +size_t dmd_av1_leb128(uint64_t v, unsigned char *out, size_t out_cap) +{ + size_t n = 0; + do { + if (n >= out_cap || n >= DMD_LEB128_MAX) + return 0; + unsigned char byte = (unsigned char)(v & 0x7f); + v >>= 7; + if (v) + byte |= 0x80; /* 还有后续字节 */ + out[n++] = byte; + } while (v); + return n; +} + +/* ------------------------------------------------------------------ uvlc */ + +void dmd_av1_put_uvlc(struct dmd_bitwriter *bw, uint32_t v) +{ + /* AV1 规范 4.10.3:leadingZeros 个 0,一个 1,然后 leadingZeros 位尾数。 + * 值 v 编码为 (1 << leadingZeros) - 1 + mantissa。 */ + uint32_t leading_zeros = 0; + uint64_t val = (uint64_t)v + 1; + + while ((val >> (leading_zeros + 1)) != 0) + leading_zeros++; + + if (leading_zeros >= 32) { + bw->overflow = 1; + return; + } + + /* leading_zeros 个 0 位;put_bits 不接受 nbits=0,所以判空。 */ + if (leading_zeros > 0) + dmd_bw_put_bits(bw, 0, (int)leading_zeros); + dmd_bw_put_flag(bw, 1); + if (leading_zeros > 0) + dmd_bw_put_bits(bw, (uint32_t)(val & ((1u << leading_zeros) - 1)), + (int)leading_zeros); +} + +/* -------------------------------------------------------------------- le */ + +void dmd_av1_put_le(struct dmd_bitwriter *bw, uint64_t v, int nbytes) +{ + /* AV1 规范 4.10.4:小端字节序,要求调用时已字节对齐。 */ + if (nbytes <= 0 || nbytes > 8 || bw->bit_pos != 0) { + bw->overflow = 1; + return; + } + for (int i = 0; i < nbytes; i++) + dmd_bw_put_bits(bw, (uint32_t)((v >> (i * 8)) & 0xff), 8); +} + +/* -------------------------------------------------------------------- ns */ + +void dmd_av1_put_ns(struct dmd_bitwriter *bw, uint32_t v, uint32_t n) +{ + /* AV1 规范 4.10.7 ns(n):非对称编码,小值省一位。 + * w = FloorLog2(n) + 1 + * m = (1 << w) - n + * v < m 时用 w-1 位直接写;否则写 (v + m) 的 w 位。 */ + if (n == 0) { + bw->overflow = 1; + return; + } + if (n == 1) + return; /* 只有一个取值,不占位 */ + + uint32_t w = 0, t = n; + while (t) { w++; t >>= 1; } /* w = FloorLog2(n) + 1 */ + uint32_t m = (1u << w) - n; + + if (v < m) { + dmd_bw_put_bits(bw, v, (int)(w - 1)); + } else { + uint32_t enc = v + m; + dmd_bw_put_bits(bw, enc >> 1, (int)(w - 1)); + dmd_bw_put_bits(bw, enc & 1, 1); + } +} + +/* -------------------------------------------------------------------- su */ + +void dmd_av1_put_su(struct dmd_bitwriter *bw, int32_t v, int nbits) +{ + /* AV1 规范 4.10.6 su(n):n 位补码。写入时取低 nbits 位即可, + * 解码侧按符号位扩展。 */ + if (nbits <= 0 || nbits > 32) { + bw->overflow = 1; + return; + } + uint32_t mask = (nbits == 32) ? 0xffffffffu : ((1u << nbits) - 1u); + dmd_bw_put_bits(bw, (uint32_t)v & mask, nbits); +} + +/* ------------------------------------------------------------------ 对齐 */ + +void dmd_av1_byte_align(struct dmd_bitwriter *bw) +{ + /* AV1 规范 5.3.5 byte_alignment():纯补零,**不写 stop bit**。 + * 这是与 H.264/HEVC rbsp_trailing_bits 的关键差别。 */ + while (bw->bit_pos != 0 && !bw->overflow) + dmd_bw_put_flag(bw, 0); +} + +void dmd_av1_trailing_bits(struct dmd_bitwriter *bw) +{ + /* AV1 规范 5.3.4 trailing_bits():一个 1,然后补零到字节边界。 + * 注意即使当前已对齐也要写这个 1 —— 它是 payload 结束标记。 */ + dmd_bw_put_flag(bw, 1); + while (bw->bit_pos != 0 && !bw->overflow) + dmd_bw_put_flag(bw, 0); +} + +/* ------------------------------------------------------- 序列头合成(2/4) */ + +/* 位宽计算:AV1 规范用 FloorLog2(x)+1 表示"表达 x 需要几位"。 */ +static int bits_for(uint32_t v) +{ + int n = 0; + while (v) { n++; v >>= 1; } + return n ? n : 1; +} + +/* color_config(),AV1 规范 5.5.2。 */ +static void put_color_config(struct dmd_bitwriter *bw, + const VADecPictureParameterBufferAV1 *p) +{ + const uint32_t depth_idx = p->bit_depth_idx; + const uint32_t mono = p->seq_info_fields.fields.mono_chrome; + const uint32_t sub_x = p->seq_info_fields.fields.subsampling_x; + const uint32_t sub_y = p->seq_info_fields.fields.subsampling_y; + + /* high_bitdepth / twelve_bit:bit_depth_idx 0/1/2 → 8/10/12 位 + * (va_dec_av1.h:255-260)。只有 profile 2 能到 12 位。 */ + const int high_bitdepth = (depth_idx != 0); + dmd_bw_put_flag(bw, high_bitdepth); + if (p->profile == 2 && high_bitdepth) + dmd_bw_put_flag(bw, depth_idx == 2); /* twelve_bit */ + + if (p->profile != 1) + dmd_bw_put_flag(bw, (int)mono); /* mono_chrome */ + + /* color_description_present_flag = 0。 + * + * ⚠️ 曾置 1 并显式写三个描述符(想保住 VA-API 给的 + * matrix_coefficients),实测与真实码流不符:libaom 置 0, + * 于是三者都取 UNSPECIFIED(2)。多写会让序列头长 3 字节。 + * + * 代价可接受:matrix_coefficients 只影响色彩转换矩阵的选择, + * 不影响能否解出帧;而本驱动输出 NV12 给上层,色彩解释由上层负责。 */ + dmd_bw_put_flag(bw, 0); + + if (mono) { + dmd_bw_put_flag(bw, (int)p->seq_info_fields.fields.color_range); + return; /* 单色分支到此结束 */ + } + + dmd_bw_put_flag(bw, (int)p->seq_info_fields.fields.color_range); + + /* subsampling 只在 profile 2 且 12 位时显式写入;profile 0 恒 4:2:0、 + * profile 1 恒 4:4:4,由 profile 推导,不占码流位(规范 5.5.2)。 */ + if (p->profile == 2 && depth_idx == 2) { + dmd_bw_put_flag(bw, (int)sub_x); + if (sub_x) + dmd_bw_put_flag(bw, (int)sub_y); + } + + /* chroma_sample_position 仅 4:2:0 时出现。VA-API 的同名字段已标 + * va_deprecated(:285),故写 UNKNOWN(0):它只影响色度插值相位假设, + * 不影响能否解出帧。 */ + /* chroma_sample_position = 1(CSP_VERTICAL)。真实码流用 1; + * VA-API 的同名字段已标 va_deprecated(:285)故不可信。 + * 该值只影响色度插值的相位假设,不影响能否解出帧。 */ + if (sub_x && sub_y) + dmd_bw_put_bits(bw, 1, 2); + + dmd_bw_put_flag(bw, 0); /* separate_uv_delta_q */ +} + +/* tile_info(),AV1 规范 5.9.15。 + * + * ⚠️ tile_size_bytes_minus_1 在这里写死 3(即 4 字节),第 4 步的 + * tile_group 必须用同样宽度写 tile_size_minus_1 —— 两处不一致会让 + * 解码器按错误宽度读 tile 长度,从第二个 tile 起全部错位。 */ +/* tile_info(),AV1 规范 5.9.15。 + * + * ⚠️ 本函数的边界值算错过两次,最终以 ffmpeg 的 CBS 实现为准逐行校对 + * (libavcodec/cbs_av1_syntax_template.c 的 tile_info())。两个坑: + * + * 1) 位移量是 sb_size = sb_shift + 2,**不是** sb_shift。CBS 原文: + * sb_size = sb_shift + 2; + * max_tile_width_sb = AV1_MAX_TILE_WIDTH >> sb_size; + * 用 sb_shift 会让 max_tile_width_sb 大 4 倍 → min_log2_tile_cols + * 偏小 → 一元码起点就错。 + * + * 2) min_log2_tiles 要对 min_log2_tile_cols 取 max。CBS 原文: + * min_log2_tiles = FFMAX(min_log2_tile_cols, + * cbs_av1_tile_log2(max_tile_area_sb, sb_rows*sb_cols)); + * 漏掉会让 min_log2_tile_rows 偏小 → 行方向多写若干个 1。 + * + * increment(v, min, max) 的编码规则(cbs_av1_write_increment): + * v == max → 写 (max-min) 个 1,**不写停止位** + * 否则 → 写 (v-min) 个 1,再写一个 0 + * + * ⚠️ tile_size_bytes_minus_1 写死 3(4 字节),第 4 步 tile_group 里写 + * tile_size_minus_1 必须用同样宽度 —— 两处不一致会从第二个 tile 起全错位。 */ +static void put_tile_info(struct dmd_bitwriter *bw, + const VADecPictureParameterBufferAV1 *p, + uint32_t mi_cols, uint32_t mi_rows) +{ + const int sb_shift = p->seq_info_fields.fields.use_128x128_superblock ? 5 : 4; + const int sb_size = sb_shift + 2; + + const uint32_t sb_cols = p->seq_info_fields.fields.use_128x128_superblock + ? ((mi_cols + 31) >> 5) : ((mi_cols + 15) >> 4); + const uint32_t sb_rows = p->seq_info_fields.fields.use_128x128_superblock + ? ((mi_rows + 31) >> 5) : ((mi_rows + 15) >> 4); + + const uint32_t MAX_TILE_COLS = 64, MAX_TILE_ROWS = 64; + const uint32_t max_tile_width_sb = 4096u >> sb_size; + const uint32_t max_tile_area_sb = (4096u * 2304u) >> (2 * sb_size); + + uint32_t max_log2_tile_cols = 0; + while ((1u << max_log2_tile_cols) < + (sb_cols < MAX_TILE_COLS ? sb_cols : MAX_TILE_COLS)) + max_log2_tile_cols++; + uint32_t max_log2_tile_rows = 0; + while ((1u << max_log2_tile_rows) < + (sb_rows < MAX_TILE_ROWS ? sb_rows : MAX_TILE_ROWS)) + max_log2_tile_rows++; + + uint32_t min_log2_tile_cols = 0; + while ((max_tile_width_sb << min_log2_tile_cols) < sb_cols) + min_log2_tile_cols++; + uint32_t min_log2_area = 0; + while ((max_tile_area_sb << min_log2_area) < sb_rows * sb_cols) + min_log2_area++; + const uint32_t min_log2_tiles = (min_log2_tile_cols > min_log2_area) + ? min_log2_tile_cols : min_log2_area; + + /* VA-API 给的是 tile_cols/tile_rows(个数),先反推 log2。 */ + uint32_t cols_log2 = 0; + while ((1u << cols_log2) < p->tile_cols) + cols_log2++; + uint32_t rows_log2 = 0; + while ((1u << rows_log2) < p->tile_rows) + rows_log2++; + + + dmd_bw_put_flag(bw, (int)p->pic_info_fields.bits.uniform_tile_spacing_flag); + + if (p->pic_info_fields.bits.uniform_tile_spacing_flag) { + /* increment(tile_cols_log2, min_log2_tile_cols, max_log2_tile_cols) + * 先夹到合法区间:CBS 的写入侧对越界直接报错拒绝。 */ + if (cols_log2 < min_log2_tile_cols) cols_log2 = min_log2_tile_cols; + if (cols_log2 > max_log2_tile_cols) cols_log2 = max_log2_tile_cols; + for (uint32_t i = min_log2_tile_cols; i < cols_log2; i++) + dmd_bw_put_flag(bw, 1); + if (cols_log2 != max_log2_tile_cols) + dmd_bw_put_flag(bw, 0); + + const uint32_t min_log2_tile_rows = + (min_log2_tiles > cols_log2) ? (min_log2_tiles - cols_log2) : 0; + if (rows_log2 < min_log2_tile_rows) rows_log2 = min_log2_tile_rows; + if (rows_log2 > max_log2_tile_rows) rows_log2 = max_log2_tile_rows; + for (uint32_t i = min_log2_tile_rows; i < rows_log2; i++) + dmd_bw_put_flag(bw, 1); + if (rows_log2 != max_log2_tile_rows) + dmd_bw_put_flag(bw, 0); + } else { + /* 非均匀:逐 tile 写 width_in_sbs_minus_1 / height_in_sbs_minus_1, + * 用 ns(n) 编码。上界是"剩余 sb 数"与 max_tile_*_sb 的较小者。 */ + uint32_t start_sb = 0; + for (int i = 0; i < p->tile_cols && start_sb < sb_cols; i++) { + const uint32_t rest = sb_cols - start_sb; + const uint32_t lim = rest < max_tile_width_sb ? rest + : max_tile_width_sb; + dmd_av1_put_ns(bw, p->width_in_sbs_minus_1[i], lim); + start_sb += p->width_in_sbs_minus_1[i] + 1; + } + start_sb = 0; + for (int i = 0; i < p->tile_rows && start_sb < sb_rows; i++) { + dmd_av1_put_ns(bw, p->height_in_sbs_minus_1[i], + sb_rows - start_sb); + start_sb += p->height_in_sbs_minus_1[i] + 1; + } + } + + /* TileCols*TileRows > 1 时写 context_update_tile_id 与 tile_size_bytes。 + * 位宽用**上面夹取修正后**的 log2 值,不能再按 tile_cols 重算。 */ + if (cols_log2 + rows_log2 > 0) { + dmd_bw_put_bits(bw, p->context_update_tile_id, + (int)(cols_log2 + rows_log2)); + /* tile_size_bytes_minus_1 = 1(2 字节)。 + * 依据:VA-API 给的 tile offset 之间恰好各差 2 字节 + * (实测 tile[0] off=2、tile[1] off=前一个末尾+2 …… 共 7 个间隙), + * 那 2 字节就是原始码流里的 tile_size 字段。跟随源码流宽度可让 + * 合成结果与原始 payload 长度一致,也避免无谓放大。 + * ⚠️ 必须与 dmd_av1_build_frame() 里写 tile_size_minus_1 的宽度一致。 */ + dmd_bw_put_bits(bw, 1, 2); + } +} + +/* quantization_params(),AV1 规范 5.9.12。 */ +static void put_quantization_params(struct dmd_bitwriter *bw, + const VADecPictureParameterBufferAV1 *p) +{ + const uint32_t mono = p->seq_info_fields.fields.mono_chrome; + + dmd_bw_put_bits(bw, p->base_qindex, 8); + + /* delta_q 用 su(1+6):1 位存在标志 + 6 位有符号值(规范 5.9.13 + * read_delta_q)。值为 0 时只写标志位 0。 */ + #define PUT_DELTA_Q(v) do { \ + if ((v) != 0) { dmd_bw_put_flag(bw, 1); \ + dmd_av1_put_su(bw, (v), 7); } \ + else dmd_bw_put_flag(bw, 0); \ + } while (0) + + PUT_DELTA_Q(p->y_dc_delta_q); + + if (!mono) { + /* diff_uv_delta 只在 separate_uv_delta_q 时出现;序列头里我们把 + * separate_uv_delta_q 写成 0,所以这里不写该标志, + * 且 U/V 共用一组 delta(写 U 的即可)。 */ + PUT_DELTA_Q(p->u_dc_delta_q); + PUT_DELTA_Q(p->u_ac_delta_q); + } + + #undef PUT_DELTA_Q + + dmd_bw_put_flag(bw, (int)p->qmatrix_fields.bits.using_qmatrix); + if (p->qmatrix_fields.bits.using_qmatrix) { + dmd_bw_put_bits(bw, p->qmatrix_fields.bits.qm_y, 4); + dmd_bw_put_bits(bw, p->qmatrix_fields.bits.qm_u, 4); + if (!mono) + dmd_bw_put_bits(bw, p->qmatrix_fields.bits.qm_v, 4); + } +} + +/* segmentation_params(),AV1 规范 5.9.14。 */ +static void put_segmentation_params(struct dmd_bitwriter *bw, + const VADecPictureParameterBufferAV1 *p, + int primary_ref_none) +{ + const uint32_t enabled = p->seg_info.segment_info_fields.bits.enabled; + dmd_bw_put_flag(bw, (int)enabled); + if (!enabled) + return; + + /* primary_ref_frame 为 NONE 时 update_map/update_data 恒 1、不写入码流。 */ + if (!primary_ref_none) { + dmd_bw_put_flag(bw, (int)p->seg_info.segment_info_fields.bits.update_map); + if (p->seg_info.segment_info_fields.bits.update_map) + dmd_bw_put_flag(bw, + (int)p->seg_info.segment_info_fields.bits.temporal_update); + dmd_bw_put_flag(bw, (int)p->seg_info.segment_info_fields.bits.update_data); + } + + if (primary_ref_none || p->seg_info.segment_info_fields.bits.update_data) { + /* 逐段逐特征写。feature_mask 的位对应 SEG_LVL_* 特征是否启用, + * feature_data 是值。位宽与是否有符号由规范表 + * Segmentation_Feature_Bits/Signed 决定。 */ + static const int seg_bits[8] = { 8, 6, 6, 6, 6, 3, 0, 0 }; + static const int seg_signed[8] = { 1, 1, 1, 1, 1, 0, 0, 0 }; + for (int i = 0; i < 8; i++) { + for (int j = 0; j < 8; j++) { + const int on = (p->seg_info.feature_mask[i] >> j) & 1; + dmd_bw_put_flag(bw, on); + if (!on) + continue; + if (seg_bits[j] == 0) + continue; /* SEG_LVL_REF_FRAME 等无值特征 */ + if (seg_signed[j]) + dmd_av1_put_su(bw, p->seg_info.feature_data[i][j], + seg_bits[j] + 1); + else + dmd_bw_put_bits(bw, + (uint32_t)p->seg_info.feature_data[i][j], seg_bits[j]); + } + } + } +} + +/* loop_filter_params(),AV1 规范 5.9.11。 */ +static void put_loop_filter_params(struct dmd_bitwriter *bw, + const VADecPictureParameterBufferAV1 *p, + int coded_lossless, int allow_intrabc) +{ + /* lossless 或 allow_intrabc 时整段不写(规范里直接返回默认值)。 */ + if (coded_lossless || allow_intrabc) + return; + + dmd_bw_put_bits(bw, p->filter_level[0], 6); + dmd_bw_put_bits(bw, p->filter_level[1], 6); + if (!p->seq_info_fields.fields.mono_chrome && + (p->filter_level[0] || p->filter_level[1])) { + dmd_bw_put_bits(bw, p->filter_level_u, 6); + dmd_bw_put_bits(bw, p->filter_level_v, 6); + } + dmd_bw_put_bits(bw, p->loop_filter_info_fields.bits.sharpness_level, 3); + + const int delta_enabled = + p->loop_filter_info_fields.bits.mode_ref_delta_enabled; + dmd_bw_put_flag(bw, delta_enabled); + if (delta_enabled) { + const int delta_update = + p->loop_filter_info_fields.bits.mode_ref_delta_update; + dmd_bw_put_flag(bw, delta_update); + if (delta_update) { + for (int i = 0; i < 8; i++) { + /* 逐项写 update 标志 + su(7)。这里对每个非零值写更新, + * 零值写标志 0 —— VA-API 不区分"未更新"与"更新为 0", + * 保守地把非零视为需要更新。 */ + if (p->ref_deltas[i] != 0) { + dmd_bw_put_flag(bw, 1); + dmd_av1_put_su(bw, p->ref_deltas[i], 7); + } else { + dmd_bw_put_flag(bw, 0); + } + } + for (int i = 0; i < 2; i++) { + if (p->mode_deltas[i] != 0) { + dmd_bw_put_flag(bw, 1); + dmd_av1_put_su(bw, p->mode_deltas[i], 7); + } else { + dmd_bw_put_flag(bw, 0); + } + } + } + } +} + +/* cdef_params(),AV1 规范 5.9.19。 */ +static void put_cdef_params(struct dmd_bitwriter *bw, + const VADecPictureParameterBufferAV1 *p, + int coded_lossless, int allow_intrabc) +{ + if (coded_lossless || allow_intrabc || + !p->seq_info_fields.fields.enable_cdef) + return; + + dmd_bw_put_bits(bw, p->cdef_damping_minus_3, 2); + dmd_bw_put_bits(bw, p->cdef_bits, 2); + + const int n = 1 << p->cdef_bits; + for (int i = 0; i < n; i++) { + /* VA-API 把 y/uv strength 打包成 (pri << 2) | sec 的形式, + * 与码流里 4 位 pri + 2 位 sec 的布局一致,可直接拆写。 */ + dmd_bw_put_bits(bw, p->cdef_y_strengths[i] >> 2, 4); + dmd_bw_put_bits(bw, p->cdef_y_strengths[i] & 0x3, 2); + if (!p->seq_info_fields.fields.mono_chrome) { + dmd_bw_put_bits(bw, p->cdef_uv_strengths[i] >> 2, 4); + dmd_bw_put_bits(bw, p->cdef_uv_strengths[i] & 0x3, 2); + } + } +} + +/* lr_params(),AV1 规范 5.9.20。 */ +static void put_lr_params(struct dmd_bitwriter *bw, + const VADecPictureParameterBufferAV1 *p, + int all_lossless, int allow_intrabc) +{ + if (all_lossless || allow_intrabc) + return; + + const uint32_t ry = p->loop_restoration_fields.bits.yframe_restoration_type; + const uint32_t rcb = p->loop_restoration_fields.bits.cbframe_restoration_type; + const uint32_t rcr = p->loop_restoration_fields.bits.crframe_restoration_type; + + /* 序列头 enable_restoration 恒写 1,所以这一段**总要写**—— + * 即使三个 lr_type 全为 0(那正是"本帧不做 restoration"的正规表达)。 + * 早先这里按"全 0 就提前返回",与序列头不一致,导致帧头短 6 位。 */ + + /* lr_type 用 f(2),取值顺序与 VA-API 的 restoration_type 枚举一致 + * (0=NONE, 1=WIENER, 2=SGRPROJ, 3=SWITCHABLE)。 */ + dmd_bw_put_bits(bw, ry, 2); + if (!p->seq_info_fields.fields.mono_chrome) { + dmd_bw_put_bits(bw, rcb, 2); + dmd_bw_put_bits(bw, rcr, 2); + } + + if (ry || rcb || rcr) { + dmd_bw_put_bits(bw, p->loop_restoration_fields.bits.lr_unit_shift, 1); + if (p->seq_info_fields.fields.use_128x128_superblock == 0 && + p->loop_restoration_fields.bits.lr_unit_shift) + dmd_bw_put_bits(bw, 0, 1); /* lr_unit_extra_shift */ + if (p->seq_info_fields.fields.subsampling_x && + p->seq_info_fields.fields.subsampling_y && (rcb || rcr)) + dmd_bw_put_bits(bw, p->loop_restoration_fields.bits.lr_uv_shift, 1); + } +} + +size_t dmd_av1_build_sequence_header(const void *pic_v, + unsigned char *out, size_t out_cap) +{ + const VADecPictureParameterBufferAV1 *p = pic_v; + if (!p || !out || out_cap < 8) + return 0; + + /* payload 先写临时缓冲:obu_size 用 leb128 编码,必须先知道 payload + * 长度才能写头部。序列头很小(实测 20 字节上下),栈上足够。 */ + unsigned char body[128]; + struct dmd_bitwriter bw; + dmd_bw_init(&bw, body, sizeof(body)); + + const uint32_t enable_order_hint = + p->seq_info_fields.fields.enable_order_hint; + + /* ---- sequence_header_obu(),AV1 规范 5.5.1 ---- */ + + dmd_bw_put_bits(&bw, p->profile, 3); /* seq_profile */ + dmd_bw_put_flag(&bw, (int)p->seq_info_fields.fields.still_picture); + dmd_bw_put_flag(&bw, 0); /* reduced_still_picture_header + * 恒 0:置 1 会砍掉后面绝大多数字段,而帧头 + * 解析依赖其中的 enable_* 能力位。 */ + + dmd_bw_put_flag(&bw, 0); /* timing_info_present_flag + * VA-API 不提供 timing_info。时序不影响解码, + * 显示节奏由上层控制。 */ + dmd_bw_put_flag(&bw, 0); /* initial_display_delay_present_flag */ + dmd_bw_put_bits(&bw, 0, 5);/* operating_points_cnt_minus_1 + * 单一 operating point:本驱动不做可扩展层, + * 与 OBU 头 extension_flag 恒 0 相一致。 */ + dmd_bw_put_bits(&bw, 0, 12); /* operating_point_idc[0] */ + /* seq_level_idx[0] = 8(level 4.0)+ seq_tier[0] = 0。 + * + * ⚠️ 曾写 0(level 2.0),实测与真实码流不符:libaom 对 1080p 输出 8。 + * 关键不只是数值 —— seq_level_idx > 7 时**必须紧跟 seq_tier**(f(1)), + * 写 0 会少这一位,导致序列头后续所有字段偏移 1 位。 + * VA-API 不提供 level,取 8 跟随真实码流;MediaCodec 按实际分辨率 + * 分配资源,不用这个字段校验。 */ + dmd_bw_put_bits(&bw, 8, 5); /* seq_level_idx[0] */ + dmd_bw_put_flag(&bw, 0); /* seq_tier[0](因 idx > 7) */ + + /* frame_width_bits 取实际所需位宽而不写死 16 位。 + * frame_width_minus1 按 va_dec_av1.h:332-334 是**上采样后**分辨率, + * 正是 max_frame_width_minus_1 要的语义。 */ + const uint32_t w_m1 = p->frame_width_minus1; + const uint32_t h_m1 = p->frame_height_minus1; + const int wbits = bits_for(w_m1); + const int hbits = bits_for(h_m1); + + dmd_bw_put_bits(&bw, (uint32_t)(wbits - 1), 4); + dmd_bw_put_bits(&bw, (uint32_t)(hbits - 1), 4); + dmd_bw_put_bits(&bw, w_m1, wbits); + dmd_bw_put_bits(&bw, h_m1, hbits); + + dmd_bw_put_flag(&bw, 0); /* frame_id_numbers_present_flag + * 置 0:VA-API 不提供 delta_frame_id,帧头里 + * 对应字段也就不写 —— 两处必须一致。 */ + + dmd_bw_put_flag(&bw, (int)p->seq_info_fields.fields.use_128x128_superblock); + dmd_bw_put_flag(&bw, (int)p->seq_info_fields.fields.enable_filter_intra); + dmd_bw_put_flag(&bw, (int)p->seq_info_fields.fields.enable_intra_edge_filter); + dmd_bw_put_flag(&bw, (int)p->seq_info_fields.fields.enable_interintra_compound); + dmd_bw_put_flag(&bw, (int)p->seq_info_fields.fields.enable_masked_compound); + + /* ⚠️ enable_warped_motion 序列级字段 VA-API **不提供**(全文件 grep + * 确认)。取 1 是安全侧:它只是能力位,帧级 allow_warped_motion(:439) + * 才决定该帧是否真用。若这里置 0 而帧级为 1,解码器会拒绝该帧; + * 置 1 而帧级为 0 则无任何副作用。 */ + dmd_bw_put_flag(&bw, 1); + + dmd_bw_put_flag(&bw, (int)p->seq_info_fields.fields.enable_dual_filter); + dmd_bw_put_flag(&bw, (int)enable_order_hint); + if (enable_order_hint) { + dmd_bw_put_flag(&bw, (int)p->seq_info_fields.fields.enable_jnt_comp); + dmd_bw_put_flag(&bw, 1); /* enable_ref_frame_mvs:同样不提供, + * 同理取安全侧 1(帧级 use_ref_frame_mvs + * 在 :435)。 */ + } + + /* seq_choose_screen_content_tools = 1 时 seq_force_screen_content_tools + * 取 SELECT_SCREEN_CONTENT_TOOLS 且**不占码流位**,语义是"每帧在帧头 + * 自行声明"。这正合需要:VA-API 只给帧级 allow_screen_content_tools + * (:429),在序列级猜一个固定值反而可能与帧冲突。 + * seq_choose_integer_mv 同理(帧级 force_integer_mv 在 :430)。 */ + dmd_bw_put_flag(&bw, 1); /* seq_choose_screen_content_tools */ + dmd_bw_put_flag(&bw, 1); /* seq_choose_integer_mv */ + + if (enable_order_hint) + dmd_bw_put_bits(&bw, p->order_hint_bits_minus_1, 3); + + /* ⚠️ enable_superres / enable_restoration 也不提供,用帧级反推: + * use_superres(:432) + * 三个 *frame_restoration_type(:608-610,非 0 即启用) + * 这两个**必须如实反映**,与 warped_motion 的处理不同 —— 它们会改变 + * 帧头的语法结构(多读或少读字段),置错会直接让帧头错位。 */ + const int use_superres = (int)p->pic_info_fields.bits.use_superres; + + dmd_bw_put_flag(&bw, use_superres); + dmd_bw_put_flag(&bw, (int)p->seq_info_fields.fields.enable_cdef); + /* enable_restoration 恒 1。 + * + * ⚠️ 曾按"三个 frame_restoration_type 是否全为 0"来推导,实测错误: + * trace_headers 显示真实码流 enable_restoration=1,且帧头位 204 起 + * **确实写了 lr_type[0..2] 共 6 位**(值恰好全为 0)。 + * 也就是说"本帧不用 restoration"是通过 lr_type=0 表达的,而不是通过 + * 序列级 enable_restoration=0 —— 后者会让整个 lr_params 段消失, + * 帧头因此短 6 位,tile_group 起始位置随之前移,解码器读到错位数据。 + * + * 取 1 是安全侧:它只是允许,具体每帧仍由 lr_type 决定。 */ + dmd_bw_put_flag(&bw, 1); + + put_color_config(&bw, p); + + dmd_bw_put_flag(&bw, + (int)p->seq_info_fields.fields.film_grain_params_present); + + dmd_av1_trailing_bits(&bw); + + if (bw.overflow) + return 0; + + /* 组装:OBU 头(内含 leb128 的 payload 长度)+ payload。 */ + const size_t body_len = dmd_bw_bytes(&bw); + const size_t hdr = dmd_av1_obu_header(DMD_OBU_SEQUENCE_HEADER, + body_len, out, out_cap); + if (hdr == 0 || hdr + body_len > out_cap) + return 0; + for (size_t i = 0; i < body_len; i++) + out[hdr + i] = body[i]; + return hdr + body_len; +} + +/* 把 uncompressed_header() 写进 bw,不含结尾的 trailing_bits / + * byte_alignment —— 由调用方按封装形式决定: + * OBU_FRAME_HEADER(3) 用 trailing_bits(规范 5.9.1) + * OBU_FRAME(6) 用 byte_alignment(规范 5.10.1) + * 这个区别是实测踩出来的:用错会让 tile_group 起始位置偏移, + * dav1d 报 "Failed to read unit"。 */ +static void put_uncompressed_header(struct dmd_bitwriter *bwp, + const VADecPictureParameterBufferAV1 *p) +{ + /* struct dmd_bitwriter 是纯值结构:buf 指向调用方的缓冲,其余成员 + * 都是计数器。所以"拷入 → 写 → 拷回"是安全的,函数体内得以保留 + * 已与真实码流逐字段对齐过的 `&bw` 写法,不必逐行改动引入笔误。 */ + struct dmd_bitwriter bw = *bwp; + + const uint32_t frame_type = p->pic_info_fields.bits.frame_type; + const int is_key = (frame_type == 0); /* KEY_FRAME */ + const int is_intra_only = (frame_type == 2); /* INTRA_ONLY_FRAME */ + const int intra_only = is_key || is_intra_only; + const uint32_t allow_intrabc = p->pic_info_fields.bits.allow_intrabc; + const uint32_t enable_order_hint = + p->seq_info_fields.fields.enable_order_hint; + const int order_hint_bits = enable_order_hint + ? (int)p->order_hint_bits_minus_1 + 1 : 0; + + /* CodedLossless 的判定(规范 7.12.1):所有段的 qindex 与四个 delta_q + * 全为 0。VA-API 不直接给这个量,按定义算 —— 它决定 loop_filter / + * cdef / lr 三段是否出现在码流里,算错会让帧头结构错位。 */ + const int coded_lossless = + (p->base_qindex == 0 && p->y_dc_delta_q == 0 && + p->u_dc_delta_q == 0 && p->u_ac_delta_q == 0 && + p->v_dc_delta_q == 0 && p->v_ac_delta_q == 0); + /* AllLossless 还要求无 superres 上采样(规范 7.12.1)。 */ + const int all_lossless = + coded_lossless && !p->pic_info_fields.bits.use_superres; + + /* --- uncompressed_header(),AV1 规范 5.9.2 --- */ + + /* show_existing_frame:本驱动逐帧转发真实帧,不复用已解码帧,恒 0。 + * (frame_id_numbers_present=0 时该字段仍存在,只是后续不读 frame_id。) */ + dmd_bw_put_flag(&bw, 0); + + dmd_bw_put_bits(&bw, frame_type, 2); + dmd_bw_put_flag(&bw, (int)p->pic_info_fields.bits.show_frame); + if (!p->pic_info_fields.bits.show_frame) + dmd_bw_put_flag(&bw, (int)p->pic_info_fields.bits.showable_frame); + + /* error_resilient_mode:KEY_FRAME 且 show_frame 时恒 1、不写入。 */ + /* error_resilient_mode(CBS 原文): + * frame_type == SWITCH || (frame_type == KEY && show_frame) + * → infer 1(不写入码流) + * 否则 flag(error_resilient_mode) */ + const int er_inferred = (frame_type == 3) || + (is_key && p->pic_info_fields.bits.show_frame); + if (!er_inferred) + dmd_bw_put_flag(&bw, (int)p->pic_info_fields.bits.error_resilient_mode); + + dmd_bw_put_flag(&bw, (int)p->pic_info_fields.bits.disable_cdf_update); + + /* allow_screen_content_tools:序列头里 seq_choose_screen_content_tools=1 + * → seq_force = SELECT_SCREEN_CONTENT_TOOLS(2),故此处写 f(1)。 */ + dmd_bw_put_flag(&bw, (int)p->pic_info_fields.bits.allow_screen_content_tools); + if (p->pic_info_fields.bits.allow_screen_content_tools) { + /* seq_choose_integer_mv=1 → seq_force_integer_mv = SELECT,写 f(1)。 */ + dmd_bw_put_flag(&bw, (int)p->pic_info_fields.bits.force_integer_mv); + } + + /* frame_id_numbers_present=0(序列头如此写),跳过 current_frame_id。 */ + + /* frame_size_override_flag:恒 0,表示帧尺寸等于序列头里的 + * max_frame_size —— 我们把 max 就写成本帧尺寸,二者一致。 + * KEY_FRAME 之外的帧若尺寸变化,本驱动会重建会话,所以恒等成立。 */ + if (frame_type != 3 /* SWITCH_FRAME 时该标志恒 1 */) + dmd_bw_put_flag(&bw, 0); + + /* order_hint(规范 5.9.2):条件是 enable_order_hint 且**并非** + * "frame_is_intra 同时 refresh_frame_flags == allFrames"。 + * + * ⚠️ 这里踩过两次坑,最后靠解析真实码流定论: + * libaom 生成的 1080p KEY_FRAME(show_frame=1)**确实写了** order_hint + * (值 0,位于 frame_size_override_flag 之后)。所以不能简化成 + * "帧内帧一律不写" —— 那样会少写 order_hint_bits 位。 + * + * 原因:KEY+show 帧的 refresh_frame_flags 字段不出现在码流里,但规范 + * 7.20 说此时 RefreshFrameFlags 取 allFrames 只是**解码器侧的推导值**, + * 而 5.9.2 的判据针对的是**语法变量**。实测 libaom 的行为表明该判据 + * 在此不成立,即照写 order_hint。 */ + if (enable_order_hint) + dmd_bw_put_bits(&bw, p->order_hint, order_hint_bits); + + /* primary_ref_frame:帧内帧或 error_resilient 时不写。 */ + /* err_res 是**生效值**:被 infer 的场合恒 1,否则取 VA-API 给的。 + * 后续 primary_ref_frame / use_ref_frame_mvs / allow_warped_motion + * 的条件都要用这个生效值,用原始字段会判错。 */ + const int err_res = er_inferred + ? 1 : (int)p->pic_info_fields.bits.error_resilient_mode; + const int primary_ref_none = intra_only || err_res || + (p->primary_ref_frame == 7 /* PRIMARY_REF_NONE */); + if (!intra_only && !err_res) + dmd_bw_put_bits(&bw, p->primary_ref_frame, 3); + + /* refresh_frame_flags:KEY_FRAME + show_frame 时恒 0xFF、不写入码流。 + * + * ⚠️ VA-API **不提供**这个字段(全文件 grep 确认:只在 :421 的注释里 + * 被提及,结构体里没有)。它是"本帧要刷新哪些参考槽位"的位掩码。 + * + * 取 0xFF(刷新全部 8 槽):MediaCodec 内部自行管理参考帧生命周期, + * 不依赖码流里的这个掩码来分配缓冲;对它而言只需语法合法。 + * 而 0xFF 是最保守的选择 —— 声称刷新全部,不会出现"解码器以为某槽 + * 还有效、实际已被覆盖"的悬空引用。代价是参考帧管理不够精细, + * 但本驱动逐帧转发、由 MediaCodec 负责重排序,不受影响。 */ + const int refresh_all = (frame_type == 3) || + (is_key && p->pic_info_fields.bits.show_frame); + if (!refresh_all) + dmd_bw_put_bits(&bw, 0xFF, 8); + + /* 参考帧索引:帧间帧才有。 */ + if (!intra_only) { + /* frame_refs_short_signaling 需要 enable_order_hint;置 0 表示 + * 显式给出全部 7 个 ref_frame_idx(VA-API 提供的正是这个数组)。 */ + if (enable_order_hint) + dmd_bw_put_flag(&bw, 0); + for (int i = 0; i < 7; i++) + dmd_bw_put_bits(&bw, p->ref_frame_idx[i], 3); + /* frame_id_numbers_present=0,不写 delta_frame_id。 */ + } + + /* frame_size() / render_size():frame_size_override=0 时帧尺寸由序列头 + * 给出,这里只写 superres 与 render_size(规范 5.9.5/5.9.6/5.9.8)。 */ + /* superres_params()(规范 5.9.8):**仅当序列头 enable_superres=1 时** + * 码流里才有 use_superres 这一位。 + * + * ⚠️ 曾在此多写一位:序列头按 use_superres 写 enable_superres(本帧为 0), + * 解码器于是不来读这个标志,而实现却无条件写了 —— 帧头从此错位 1 位, + * dav1d 报 "trailing_one_bit out of range: 0"。教训:凡"序列头某位决定 + * 帧头是否有此字段"的地方,两处条件必须写成同一个表达式。 */ + if (p->pic_info_fields.bits.use_superres) { + dmd_bw_put_flag(&bw, 1); + /* coded_denom:SUPERRES_DENOM_MIN=9,占 SUPERRES_DENOM_BITS=3 位。 */ + const uint32_t denom = p->superres_scale_denominator; + dmd_bw_put_bits(&bw, (denom >= 9 ? denom - 9 : 0), 3); + } + /* render_and_frame_size_different = 0:显示尺寸等于帧尺寸。 + * VA-API 不提供 render_size,且它只影响显示裁剪、不影响解码。 */ + dmd_bw_put_flag(&bw, 0); + + /* allow_intrabc(规范 5.9.2):条件是 allow_screen_content_tools && + * UpscaledWidth == FrameWidth。以 ffmpeg CBS 的原文为准: + * if (allow_screen_content_tools && upscaled_width == frame_width) + * flag(allow_intrabc); + * else + * infer(allow_intrabc, 0); + * + * upscaled_width == frame_width 等价于"无 superres 上采样"—— + * superres_params 里只有 use_superres 时才把 frame_width 按 denom 缩小。 + * + * ⚠️ 这个条件错过两次:先漏 upscaled 判据,后又把 + * allow_screen_content_tools 整个去掉(误读真实码流某一位所致)。 + * 两个条件**都要**,缺一个就多写或少写 1 位。 */ + /* ⚠️ 这里 CBS 源码与 libaom 的实际输出不一致,以**真实码流**为准。 + * + * CBS(cbs_av1_syntax_template.c)写的是条件读: + * if (allow_screen_content_tools && upscaled_width == frame_width) + * flag(allow_intrabc); else infer 0 + * + * 但用位级解析器逐字段核对 libaom 生成的 1080p KEY_FRAME:该帧 + * allow_screen_content_tools=0,若按 CBS 的条件跳过这一位,整个帧头 + * 会错位、读到末尾 trailing_one_bit=0;无条件读这一位才能得到 + * trailing_one_bit=1(位数精确闭合)。 + * + * 结论:实际编码器无条件写该位。判据是"能否让真实码流闭合", + * 而不是源码怎么写 —— 我们要喂的是真实解码器,不是 CBS。 */ + /* allow_intrabc:以 ffmpeg trace_headers 对真实码流的逐位输出为准。 + * 实测 libaom 生成的 1080p KEY_FRAME(allow_screen_content_tools=0): + * 位 46 render_and_frame_size_different + * 位 47 disable_frame_end_update_cdf ← allow_intrabc **不存在** + * 位 48 uniform_tile_spacing_flag + * 即 CBS 的条件读成立:asct=0 时该位不写入码流。 + * + * ⚠️ 曾据自己写的解析器"位数闭合"推断成无条件写,那是错的 —— + * 解析器本身在此处有偏差,两个错误互相抵消才显得闭合。 + * 教训:验证工具必须先用 trace_headers 这类权威输出校准, + * 不能拿未校准的自制解析器当基准。 */ + if (intra_only && p->pic_info_fields.bits.allow_screen_content_tools && + !p->pic_info_fields.bits.use_superres) + dmd_bw_put_flag(&bw, (int)allow_intrabc); + + if (!intra_only) { + dmd_bw_put_flag(&bw, (int)p->pic_info_fields.bits.allow_high_precision_mv); + /* read_interpolation_filter():is_filter_switchable f(1), + * 为 0 时再写 2 位 interp_filter。VA-API 的 interp_filter 取值 + * 4 = SWITCHABLE。 */ + if (p->interp_filter == 4) { + dmd_bw_put_flag(&bw, 1); + } else { + dmd_bw_put_flag(&bw, 0); + dmd_bw_put_bits(&bw, p->interp_filter, 2); + } + dmd_bw_put_flag(&bw, + (int)p->pic_info_fields.bits.is_motion_mode_switchable); + /* use_ref_frame_mvs 需 enable_ref_frame_mvs(序列头写 1)、 + * 非 error_resilient、且 enable_order_hint。 */ + if (!err_res && enable_order_hint) + dmd_bw_put_flag(&bw, (int)p->pic_info_fields.bits.use_ref_frame_mvs); + } + + /* disable_frame_end_update_cdf:reduced_still_picture_header=0 且 + * disable_cdf_update=0 时出现。 */ + if (!p->pic_info_fields.bits.disable_cdf_update) + dmd_bw_put_flag(&bw, + (int)p->pic_info_fields.bits.disable_frame_end_update_cdf); + + /* MiCols/MiRows:以 4x4 单元计的画面尺寸(规范 5.9.5 的推导)。 + * 2*((width+7)>>3) 等价于向上取整到 8 像素再折半。 */ + const uint32_t width = (uint32_t)p->frame_width_minus1 + 1; + const uint32_t height = (uint32_t)p->frame_height_minus1 + 1; + const uint32_t mi_cols = 2 * ((width + 7) >> 3); + const uint32_t mi_rows = 2 * ((height + 7) >> 3); + + put_tile_info(&bw, p, mi_cols, mi_rows); + put_quantization_params(&bw, p); + put_segmentation_params(&bw, p, primary_ref_none); + + /* delta_q_params()(5.9.17):base_qindex > 0 时才有 delta_q_present。 */ + if (p->base_qindex > 0) + dmd_bw_put_flag(&bw, (int)p->mode_control_fields.bits.delta_q_present_flag); + if (p->mode_control_fields.bits.delta_q_present_flag) { + dmd_bw_put_bits(&bw, p->mode_control_fields.bits.log2_delta_q_res, 2); + + /* delta_lf_params()(5.9.18):仅在 delta_q_present 时出现。 */ + if (!allow_intrabc) { + dmd_bw_put_flag(&bw, + (int)p->mode_control_fields.bits.delta_lf_present_flag); + if (p->mode_control_fields.bits.delta_lf_present_flag) { + dmd_bw_put_bits(&bw, + p->mode_control_fields.bits.log2_delta_lf_res, 2); + dmd_bw_put_flag(&bw, + (int)p->mode_control_fields.bits.delta_lf_multi); + } + } + } + + put_loop_filter_params(&bw, p, coded_lossless, (int)allow_intrabc); + put_cdef_params(&bw, p, coded_lossless, (int)allow_intrabc); + put_lr_params(&bw, p, all_lossless, (int)allow_intrabc); + + /* read_tx_mode()(5.9.21):CodedLossless 时 tx_mode 恒 ONLY_4X4、 + * 不写入;否则写 tx_mode_select f(1)。VA-API 的 tx_mode 取值 + * 2 = TX_MODE_LARGEST, 3 = TX_MODE_SELECT。 */ + /* read_tx_mode(CBS 原文): + * coded_lossless → infer(tx_mode, ONLY_4X4),不写入 + * 否则 increment(tx_mode, TX_MODE_LARGEST=1, TX_MODE_SELECT=2) + * + * ⚠️ 曾误当成 f(1) 标志写 `tx_mode == 3`,两处都错: + * - 编码方式不是单个标志位,而是 increment(range [1,2]) + * - VA-API 的 tx_mode 值域是 [0..2](va_dec_av1.h:560-563), + * 直接就是规范枚举值,不存在 3 + * increment 在 range_max 时写 (max-min)=1 个 1 且无停止位, + * 在 range_min 时只写一个 0。 */ + if (!coded_lossless) { + const uint32_t tm = p->mode_control_fields.bits.tx_mode; + if (tm >= 2) + dmd_bw_put_flag(&bw, 1); /* TX_MODE_SELECT:写 1,无停止位 */ + else + dmd_bw_put_flag(&bw, 0); /* TX_MODE_LARGEST:停止位 */ + } + + /* frame_reference_mode()(5.9.23):帧间帧写 reference_select。 */ + if (!intra_only) + dmd_bw_put_flag(&bw, (int)p->mode_control_fields.bits.reference_select); + + /* skip_mode_params()(5.9.22):skipModeAllowed 的完整推导需要参考帧 + * order hint 比较,VA-API 已给出结论 skip_mode_present,直接用。 + * 帧内帧或 reference_select=0 时 skipModeAllowed=0、不写入。 */ + if (!intra_only && p->mode_control_fields.bits.reference_select) + dmd_bw_put_flag(&bw, (int)p->mode_control_fields.bits.skip_mode_present); + + /* allow_warped_motion:需 is_motion_mode_switchable、非 error_resilient、 + * 且序列级 enable_warped_motion(我们写 1)。 */ + if (!intra_only && + p->pic_info_fields.bits.is_motion_mode_switchable && !err_res) + dmd_bw_put_flag(&bw, (int)p->pic_info_fields.bits.allow_warped_motion); + + dmd_bw_put_flag(&bw, (int)p->mode_control_fields.bits.reduced_tx_set_used); + + /* global_motion_params()(5.9.24):帧间帧逐参考帧写 is_global。 + * VA-API 的 wm[] 提供变换参数,但把它反向编码成码流需要完整的 + * 差分编码与参考帧投影逻辑。此处对所有参考帧写 is_global=0 + * (IDENTITY),代价是丢失全局运动补偿。 + * ⚠️ 这是本实现的已知简化,见文件末尾说明。 */ + if (!intra_only) { + for (int i = 0; i < 7; i++) + dmd_bw_put_flag(&bw, 0); /* is_global[LAST+i] = 0 */ + } + + /* film_grain_params()(5.9.30):序列头里 film_grain_params_present + * 为 0 时整段不出现。我们如实转写该标志,故此处同样条件。 */ + if (p->seq_info_fields.fields.film_grain_params_present && + (p->pic_info_fields.bits.show_frame || + p->pic_info_fields.bits.showable_frame)) + dmd_bw_put_flag(&bw, 0); /* apply_grain = 0 */ + + /* 结尾不写 trailing_bits / byte_alignment —— 交给调用方按封装形式决定。 */ + *bwp = bw; +} + +/* 把帧头 payload 装进指定类型的 OBU。obu_type 决定结尾用哪种对齐: + * DMD_OBU_FRAME_HEADER → trailing_bits(规范 5.9.1) + * DMD_OBU_FRAME → byte_alignment(规范 5.10.1),之后紧跟 tile_group + * 返回写入 out 的字节数(含 OBU 头),失败返回 0。 + * tail_out 回传 payload 的位长度,供 OBU_FRAME 继续拼 tile_group。 */ +static size_t build_frame_header_obu(const VADecPictureParameterBufferAV1 *p, + int obu_type, + unsigned char *body, size_t body_cap, + size_t *body_len_out) +{ + struct dmd_bitwriter bw; + dmd_bw_init(&bw, body, body_cap); + put_uncompressed_header(&bw, p); + + if (obu_type == DMD_OBU_FRAME) + dmd_av1_byte_align(&bw); /* 纯补零,不写标记位 */ + else + dmd_av1_trailing_bits(&bw); /* 写 1 再补零 */ + + if (bw.overflow) + return 0; + *body_len_out = dmd_bw_bytes(&bw); + return *body_len_out; +} + +size_t dmd_av1_build_frame_header(const void *pic_v, + unsigned char *out, size_t out_cap) +{ + const VADecPictureParameterBufferAV1 *p = pic_v; + if (!p || !out || out_cap < 8) + return 0; + + unsigned char body[512]; + size_t body_len = 0; + if (build_frame_header_obu(p, DMD_OBU_FRAME_HEADER, + body, sizeof(body), &body_len) == 0) + return 0; + + const size_t hdr = dmd_av1_obu_header(DMD_OBU_FRAME_HEADER, + body_len, out, out_cap); + if (hdr == 0 || hdr + body_len > out_cap) + return 0; + for (size_t i = 0; i < body_len; i++) + out[hdr + i] = body[i]; + return hdr + body_len; +} + +size_t dmd_av1_build_frame(const void *pic_v, + const struct dmd_av1_tile *tiles, int num_tiles, + unsigned char *out, size_t out_cap) +{ + const VADecPictureParameterBufferAV1 *p = pic_v; + if (!p || !out || !tiles || num_tiles <= 0 || out_cap < 16) + return 0; + + /* 帧头(结尾 byte_alignment,不是 trailing_bits)。 */ + unsigned char fh[512]; + size_t fh_len = 0; + if (build_frame_header_obu(p, DMD_OBU_FRAME, + fh, sizeof(fh), &fh_len) == 0) + return 0; + + /* tile_group_obu()(规范 5.11.1)的 payload: + * NumTiles > 1 时先写 tile_start_and_end_present_flag + * 置 0 表示本 group 覆盖全部 tile(tg_start=0, tg_end=NumTiles-1) + * 随后 byte_alignment,再逐 tile 写 tile_size_minus_1 + 数据 + * 最后一个 tile 不写长度(由 OBU 剩余长度隐含) + * + * tile_size_minus_1 用 le(4),宽度必须与帧头 tile_info 里写的 + * tile_size_bytes_minus_1 = 3 一致 —— 两处不符会从第二个 tile 起全错位。 */ + const uint32_t tile_total = + (uint32_t)p->tile_cols * (uint32_t)p->tile_rows; + + unsigned char tg_hdr[8]; + struct dmd_bitwriter tgw; + dmd_bw_init(&tgw, tg_hdr, sizeof(tg_hdr)); + if (tile_total > 1) + dmd_bw_put_flag(&tgw, 0); /* tile_start_and_end_present_flag */ + dmd_av1_byte_align(&tgw); + if (tgw.overflow) + return 0; + const size_t tg_hdr_len = dmd_bw_bytes(&tgw); + + /* 先算 OBU payload 总长,才能写 leb128 的 obu_size。 */ + size_t payload_len = fh_len + tg_hdr_len; + for (int i = 0; i < num_tiles; i++) { + if (!tiles[i].data && tiles[i].len) + return 0; + payload_len += tiles[i].len; + if (i + 1 < num_tiles) + payload_len += 2; /* tile_size_minus_1,le(2) */ + } + + const size_t hdr = dmd_av1_obu_header(DMD_OBU_FRAME, payload_len, + out, out_cap); + if (hdr == 0 || hdr + payload_len > out_cap) + return 0; + + unsigned char *q = out + hdr; + for (size_t i = 0; i < fh_len; i++) + *q++ = fh[i]; + for (size_t i = 0; i < tg_hdr_len; i++) + *q++ = tg_hdr[i]; + for (int i = 0; i < num_tiles; i++) { + if (i + 1 < num_tiles) { + /* le(2):宽度必须等于帧头 tile_size_bytes_minus_1 + 1 = 2。 + * 单 tile 上限 64KB —— 实测 1080p 最大 tile 约 4KB, + * 而 VA-API 源码流本身就用 2 字节,跟随它即可。 + * ⚠️ 若将来遇到 >64KB 的单 tile,这里和帧头要一起加宽。 */ + const uint32_t v = (uint32_t)(tiles[i].len - 1); + *q++ = (unsigned char)(v & 0xFF); + *q++ = (unsigned char)((v >> 8) & 0xFF); + } + for (size_t k = 0; k < tiles[i].len; k++) + *q++ = tiles[i].data[k]; + } + return hdr + payload_len; +} + +/* ---------------------------------------------------------------- OBU 头 */ + +size_t dmd_av1_obu_header(int obu_type, size_t payload_len, + unsigned char *out, size_t out_cap) +{ + if (obu_type < 0 || obu_type > 15 || out_cap < 1) + return 0; + + /* forbidden(1)=0 | type(4) | extension(1)=0 | has_size(1)=1 | reserved(1)=0 + * + * 即 0x00 | (type << 3) | 0x00 | 0x02 | 0x00 —— has_size 位是 bit1。 + * 举例:SEQUENCE_HEADER(1) → 0x0a,FRAME_HEADER(3) → 0x1a, + * TILE_GROUP(4) → 0x22,TEMPORAL_DELIMITER(2) → 0x12。 + * + * 对照实测的非法值 0xd0 = 1101_0000:forbidden=1(必须 0)、 + * type=10(保留值)—— 一眼就能看出那不是 OBU 头而是裸载荷。 */ + out[0] = (unsigned char)(((obu_type & 0x0f) << 3) | 0x02); + + size_t n = dmd_av1_leb128((uint64_t)payload_len, out + 1, out_cap - 1); + if (n == 0) + return 0; + return 1 + n; +} diff --git a/codec/vaapi/src/av1_bitstream.h b/codec/vaapi/src/av1_bitstream.h new file mode 100644 index 0000000..cbd9463 --- /dev/null +++ b/codec/vaapi/src/av1_bitstream.h @@ -0,0 +1,148 @@ +/* AV1 OBU 反向合成。 + * + * 为什么需要这个文件:VA-API 把 AV1 的解码参数以**结构化字段**交给驱动 + * (VADecPictureParameterBufferAV1),码流侧只给**裸 tile 载荷**—— + * 不含任何 OBU 封装。而下游 MediaCodec 要的是完整 AV1 OBU 流。 + * + * libva 自己把这件事说清楚了(/usr/include/va/va_dec_av1.h:643-645): + * "host decoder is responsible to parse out the per tile information. + * And the bit stream in sent to driver in per tile granularity." + * 同文件 :637-638 还注明 VASliceParameterBufferAV1 "actually means + * VATileParameterBufferAV1"。 + * + * ⚠️ 这与 VP9 的情形完全不同,别照搬。VP9 的 slice data 本身就是完整帧 + * (va_dec_vp9.h:274-284),所以那条路零重建成立;AV1 走同样的路会送出 + * 非法码流——实测首字节 0xd0(forbidden_bit=1、OBU 类型 10 是保留值), + * 解码器报 "No sequence header available",一帧也解不出。 + * + * 位写入原语复用 bitstream.h:AV1 的 f(n) 与 H.264/HEVC 的 u(n) 编码方式 + * 一致(都是 MSB 优先的固定位宽,AV1 规范 4.10.2 对 f(n) 的定义), + * 已核对 dmd_bw_put_bits 的实现确认位序相同。AV1 特有的变长编码 + * (leb128 / uvlc / le)在本文件补齐。 + */ +#ifndef DMD_AV1_BITSTREAM_H +#define DMD_AV1_BITSTREAM_H + +#include +#include + +#include "bitstream.h" + +/* OBU 类型(AV1 规范 6.2.2 表 obu_type)。 */ +enum { + DMD_OBU_SEQUENCE_HEADER = 1, + DMD_OBU_TEMPORAL_DELIMITER = 2, + DMD_OBU_FRAME_HEADER = 3, + DMD_OBU_TILE_GROUP = 4, + DMD_OBU_METADATA = 5, + DMD_OBU_FRAME = 6, + DMD_OBU_REDUNDANT_FRAME_HEADER = 7, + DMD_OBU_TILE_LIST = 8, + DMD_OBU_PADDING = 15, +}; + +/* leb128 最大字节数(AV1 规范 4.10.5:最多 8 字节)。 */ +#define DMD_LEB128_MAX 8 + +/* ---------------------------------------------------------------- 变长编码 */ + +/* leb128(v):小端 7 位分组,每字节高位是"还有后续"标志。 + * 写入 out,返回字节数;out_cap 不足返回 0。 */ +size_t dmd_av1_leb128(uint64_t v, unsigned char *out, size_t out_cap); + +/* leb128 的编码长度,不实际写入——用于先算 obu_size 占几字节。 */ +size_t dmd_av1_leb128_len(uint64_t v); + +/* uvlc():AV1 规范 4.10.3。前导零计数 + 尾数,用于 frame_header 里 + * 少数字段(如 timing_info 的 num_units_in_display_tick 不用它, + * 但 delta_frame_id 之类要)。 */ +void dmd_av1_put_uvlc(struct dmd_bitwriter *bw, uint32_t v); + +/* le(n):AV1 规范 4.10.4。n 字节小端整数,**必须字节对齐时调用**。 */ +void dmd_av1_put_le(struct dmd_bitwriter *bw, uint64_t v, int nbytes); + +/* ns(n):AV1 规范 4.10.7 的非对称二值编码。tile_info 里 + * context_update_tile_id 与 tile 尺寸推导会用到。 */ +void dmd_av1_put_ns(struct dmd_bitwriter *bw, uint32_t v, uint32_t n); + +/* su(n):AV1 规范 4.10.6 的有符号定长。global_motion 等处用。 */ +void dmd_av1_put_su(struct dmd_bitwriter *bw, int32_t v, int nbits); + +/* ------------------------------------------------------------------ 对齐 */ + +/* byte_alignment():AV1 规范 5.3.5。补零至字节边界。 + * ⚠️ 与 H.264 的 rbsp_trailing_bits 不同——AV1 **不写** stop bit, + * 纯补零。用错会让解码器把填充位当语法元素读。 */ +void dmd_av1_byte_align(struct dmd_bitwriter *bw); + +/* trailing_bits():AV1 规范 5.3.4。写一个 1 再补零至字节边界。 + * 用于 OBU **payload 结尾**(sequence_header_obu 与 + * frame_header_obu 结尾要,tile_group_obu 结尾不要)。 */ +void dmd_av1_trailing_bits(struct dmd_bitwriter *bw); + +/* ---------------------------------------------------------------- OBU 头 */ + +/* ------------------------------------------------------- 序列头合成(2/4) */ + +/* 从 VADecPictureParameterBufferAV1 合成一个完整的 OBU_SEQUENCE_HEADER + * (含 OBU 头 + payload + trailing_bits)。 + * + * pic 是 const void* 而非具体类型:本头文件刻意不 include va_dec_av1.h, + * 免得把 libva 依赖扩散到只需要比特原语的调用方。实现里转型。 + * + * 写入 out,返回总字节数;容量不足或参数非法返回 0。 */ +size_t dmd_av1_build_sequence_header(const void *pic, + unsigned char *out, size_t out_cap); + +/* --------------------------------------------- OBU_FRAME 组装(3/4 + 4/4) */ + +/* 一个 tile 的位置与长度描述,供 dmd_av1_build_frame() 组装 tile_group。 */ +struct dmd_av1_tile { + const unsigned char *data; + size_t len; +}; + +/* 合成一个完整的 OBU_FRAME(6):帧头 + byte_alignment + tile_group。 + * + * ⚠️ 为什么用 OBU_FRAME 而不是分离的 FRAME_HEADER(3) + TILE_GROUP(4): + * 实测 dav1d 对分离形式报 "Failed to read unit 0 (type 3)",而合并形式 + * 直接通过。libaom 生成的真实码流用的也是 OBU_FRAME。 + * + * ⚠️ 关键差别:OBU_FRAME 内的帧头结尾用 **byte_alignment(纯补零)**, + * 而不是 trailing_bits(写 1 再补零)—— 规范 5.10.1 frame_obu() 里 + * frame_header_obu() 之后紧跟 byte_alignment()。用错会让 tile_group + * 的起始位置偏移,dav1d 就是这么报错的。 + * + * tiles 按 tile_row-major 顺序给出,数量必须等于 tile_cols*tile_rows。 + * 写入 out,返回总字节数;容量不足或参数非法返回 0。 */ +size_t dmd_av1_build_frame(const void *pic, + const struct dmd_av1_tile *tiles, int num_tiles, + unsigned char *out, size_t out_cap); + +/* ------------------------------------------------------- 帧头合成(3/4) */ + +/* 从 VADecPictureParameterBufferAV1 合成一个完整的 OBU_FRAME_HEADER + * (含 OBU 头 + payload + trailing_bits)。 + * + * tile_cols/tile_rows 取自 pic 参数;tile_size_bytes 固定 4 字节, + * 与第 4 步 tile_group 里写 tile_size_minus_1 的宽度必须一致。 + * + * 写入 out,返回总字节数;容量不足或参数非法返回 0。 */ +size_t dmd_av1_build_frame_header(const void *pic, + unsigned char *out, size_t out_cap); + +/* obu_header() + obu_size(AV1 规范 5.3.1/5.3.2)。 + * + * 位布局(共 1 字节,无 extension 时): + * obu_forbidden_bit f(1) 必须 0 + * obu_type f(4) + * obu_extension_flag f(1) 本驱动恒 0(不用可扩展层) + * obu_has_size_field f(1) 本驱动恒 1(low-overhead 格式需要) + * obu_reserved_1bit f(1) 必须 0 + * + * 写入 out(头 1 字节 + leb128 编码的 payload_len),返回总字节数; + * out_cap 不足返回 0。调用方随后把 payload 追加在返回位置之后。 */ +size_t dmd_av1_obu_header(int obu_type, size_t payload_len, + unsigned char *out, size_t out_cap); + +#endif diff --git a/codec/vaapi/src/bitstream.c b/codec/vaapi/src/bitstream.c new file mode 100644 index 0000000..f1b96da --- /dev/null +++ b/codec/vaapi/src/bitstream.c @@ -0,0 +1,119 @@ +/* H.264/HEVC 共用的比特流写入原语实现。见 bitstream.h。 */ + +#include + +#include "bitstream.h" + + +void dmd_bw_init(struct dmd_bitwriter *bw, unsigned char *buf, size_t cap) +{ + bw->buf = buf; + bw->cap = cap; + bw->byte_pos = 0; + bw->bit_pos = 0; + bw->overflow = 0; + if (cap > 0) + buf[0] = 0; +} + +void dmd_bw_put_bits(struct dmd_bitwriter *bw, uint32_t value, int nbits) +{ + if (nbits <= 0 || nbits > 32) { + bw->overflow = 1; + return; + } + for (int i = nbits - 1; i >= 0; i--) { + if (bw->byte_pos >= bw->cap) { + bw->overflow = 1; + return; + } + unsigned int bit = (value >> i) & 1u; + bw->buf[bw->byte_pos] |= (unsigned char)(bit << (7 - bw->bit_pos)); + bw->bit_pos++; + if (bw->bit_pos == 8) { + bw->bit_pos = 0; + bw->byte_pos++; + if (bw->byte_pos < bw->cap) + bw->buf[bw->byte_pos] = 0; + } + } +} + +void dmd_bw_put_flag(struct dmd_bitwriter *bw, int v) +{ + dmd_bw_put_bits(bw, v ? 1u : 0u, 1); +} + +/* ue(v):Exp-Golomb 无符号。写法是 (leadingZeros) 1 (info), + * 其中 codeNum+1 的二进制长度决定前导零个数。 */ +void dmd_bw_put_ue(struct dmd_bitwriter *bw, uint32_t v) +{ + if (v == 0xFFFFFFFFu) { /* v+1 会回绕 */ + bw->overflow = 1; + return; + } + uint32_t val = v + 1; + int nbits = 0; + while ((val >> nbits) != 0) + nbits++; + /* nbits-1 个前导零,然后 val 的 nbits 位(最高位那个 1 就是分隔符)。 + * v==0 时 nbits==1,前导零个数为 0 —— 不能调 dmd_bw_put_bits(.,.,0), + * 它会把 nbits<=0 判成溢出。 */ + if (nbits > 1) + dmd_bw_put_bits(bw, 0, nbits - 1); + dmd_bw_put_bits(bw, val, nbits); +} + +/* se(v):Exp-Golomb 有符号。映射 0,1,-1,2,-2,... → 0,1,2,3,4,... */ +void dmd_bw_put_se(struct dmd_bitwriter *bw, int32_t v) +{ + uint32_t code; + if (v <= 0) + code = (uint32_t)(-2 * (int64_t)v); + else + code = (uint32_t)(2 * (int64_t)v - 1); + dmd_bw_put_ue(bw, code); +} + +/* rbsp_trailing_bits:一个 1 位,然后补零到字节边界。 */ +void dmd_bw_rbsp_trailing(struct dmd_bitwriter *bw) +{ + dmd_bw_put_flag(bw, 1); + while (bw->bit_pos != 0) + dmd_bw_put_flag(bw, 0); +} + +/* 已写出的字节数(必须在 rbsp_trailing 之后调用,此时已对齐)。 */ +size_t dmd_bw_bytes(const struct dmd_bitwriter *bw) +{ + return bw->bit_pos == 0 ? bw->byte_pos : bw->byte_pos + 1; +} + +/* ------------------------------------------------- emulation prevention 转义 */ + +/* 把 RBSP 转成 SODB/EBSP:每遇到 00 00 0x(x <= 3)就插入一个 03。 + * MediaCodec 收到的是完整 NALU,必须是转义后的形式,否则解析器会把 + * 数据里偶然出现的 00 00 01 当成起始码。 */ +size_t dmd_rbsp_escape(const unsigned char *rbsp, size_t len, + unsigned char *out, size_t out_cap) +{ + size_t o = 0; + int zeros = 0; + + for (size_t i = 0; i < len; i++) { + if (zeros >= 2 && rbsp[i] <= 0x03) { + if (o >= out_cap) + return 0; + out[o++] = 0x03; + zeros = 0; + } + if (o >= out_cap) + return 0; + out[o++] = rbsp[i]; + if (rbsp[i] == 0x00) + zeros++; + else + zeros = 0; + } + return o; +} diff --git a/codec/vaapi/src/bitstream.h b/codec/vaapi/src/bitstream.h new file mode 100644 index 0000000..f47ab67 --- /dev/null +++ b/codec/vaapi/src/bitstream.h @@ -0,0 +1,34 @@ +/* H.264/HEVC 共用的比特流写入原语。 + * + * 两种编码的语法元素编码方式完全一致(u(n)/ue(v)/se(v)/rbsp_trailing_bits + * 与 emulation prevention),所以从 h264_bitstream.c 里提出来共享, + * 避免 HEVC 再抄一份。 + */ +#ifndef DMD_BITSTREAM_H +#define DMD_BITSTREAM_H + +#include +#include + +struct dmd_bitwriter { + unsigned char *buf; + size_t cap; + size_t byte_pos; + int bit_pos; /* 0..7,当前字节内已写的位数 */ + int overflow; /* 置位后所有写入都是空操作,调用方检查这个字段 */ +}; + +void dmd_bw_init(struct dmd_bitwriter *bw, unsigned char *buf, size_t cap); +void dmd_bw_put_bits(struct dmd_bitwriter *bw, uint32_t value, int nbits); +void dmd_bw_put_flag(struct dmd_bitwriter *bw, int v); +void dmd_bw_put_ue(struct dmd_bitwriter *bw, uint32_t v); +void dmd_bw_put_se(struct dmd_bitwriter *bw, int32_t v); +void dmd_bw_rbsp_trailing(struct dmd_bitwriter *bw); +size_t dmd_bw_bytes(const struct dmd_bitwriter *bw); + +/* RBSP → EBSP:每遇 00 00 0x(x<=3)插入一个 03。 + * MediaCodec 收到的必须是转义后的形式。返回写入 out 的字节数,0 = 容量不足。 */ +size_t dmd_rbsp_escape(const unsigned char *rbsp, size_t len, + unsigned char *out, size_t out_cap); + +#endif diff --git a/codec/vaapi/src/decode.c b/codec/vaapi/src/decode.c new file mode 100644 index 0000000..e267914 --- /dev/null +++ b/codec/vaapi/src/decode.c @@ -0,0 +1,2648 @@ +/* 解码数据路径:surface / context / buffer 对象表 + 帧提交与取回 + * + * ── 语义错配是这里的核心难点 ────────────────────────────────── + * VA-API:一次 BeginPicture/EndPicture = 解一帧到**指定** surface, + * 显示顺序由客户端安排,surface 之间无隐含顺序。 + * MediaCodec(经 daemon):流式 in/out,输出按**解码顺序**吐出, + * 没有"这一帧属于哪个 surface"的概念。 + * + * 桥接办法:context 维护一个 FIFO 待解码队列 pending[]。EndPicture 把 + * 本帧码流送给 daemon 并把 render_target 入队;从 daemon 取回的第 k 帧 + * 就填给队列里的第 k 个 surface。这要求 **N 次提交 ⇔ N 个输出帧**: + * - VP9/VP8:每个数据单元恰好一帧(含 invisible 帧,show_frame==0 也产 + * output buffer),天然 1:1 + * - H.264/HEVC:SPS/PPS 等参数集 NALU 不产帧,所以送参数集时**不入队** + * 这个不变式一旦破坏,画面会整体错位一帧且再也追不回来。 + * + * IO 与锁:所有 daemon 收发都在放锁之后做,靠 io_busy[] 串行化同一 context + * 上的 IO。持锁做阻塞 IO 会让其他线程的 CreateBuffer 一起卡死。 + */ + +#include +#include +#include +#include +#include +#include +#include + +/* surface 分配在 msm_drm 的 dumb buffer 里,为的是能导出 dmabuf + * (Firefox 取帧的唯一途径,见 export.c)。 */ +#include + +#include "driver.h" +#include "av1_bitstream.h" + +/* 前置声明:DestroyContext 需要排空在飞的帧,而这两个辅助定义在下方的 + * 解码路径小节里(放在那里更贴近使用现场)。 */ +static VASurfaceID dmd_pending_take_locked(struct dmd_context *c, + uint32_t unit_seq); +static void surface_store_frame_locked(struct dmd_surface *s, + const struct dmd_frame *f); + +unsigned int dmd_align_up(unsigned int v, unsigned int align) +{ + if (align == 0) + return v; + return (v + align - 1) / align * align; +} + +/* ================================ 对象查找 ================================ */ + +struct dmd_surface *dmd_find_surface_locked(struct dmd_driver *drv, + VASurfaceID id) +{ + if (id == VA_INVALID_ID) + return NULL; + for (int i = 0; i < DMD_MAX_SURFACES; i++) { + if (drv->surfaces[i].in_use && drv->surfaces[i].id == id) + return &drv->surfaces[i]; + } + return NULL; +} + +struct dmd_context *dmd_find_context_locked(struct dmd_driver *drv, + VAContextID id) +{ + if (id == VA_INVALID_ID) + return NULL; + for (int i = 0; i < DMD_MAX_CONTEXTS; i++) { + if (drv->contexts[i].in_use && drv->contexts[i].id == id) + return &drv->contexts[i]; + } + return NULL; +} + +struct dmd_buffer *dmd_find_buffer_locked(struct dmd_driver *drv, VABufferID id) +{ + if (id == VA_INVALID_ID) + return NULL; + for (int i = 0; i < DMD_MAX_BUFFERS; i++) { + if (drv->buffers[i].in_use && drv->buffers[i].id == id) + return &drv->buffers[i]; + } + return NULL; +} + +void dmd_surface_reset_locked(struct dmd_surface *s) +{ + if (s->exportable) { + /* dumb buffer:先 munmap 再销毁 handle,顺序不能颠倒。 */ + if (s->data) + munmap(s->data, s->dumb_size); + if (s->dumb_handle && s->dumb_drm_fd >= 0) { + struct drm_mode_destroy_dumb dreq; + memset(&dreq, 0, sizeof(dreq)); + dreq.handle = s->dumb_handle; + ioctl(s->dumb_drm_fd, DRM_IOCTL_MODE_DESTROY_DUMB, &dreq); + } + } else { + free(s->data); + } + memset(s, 0, sizeof(*s)); + s->id = VA_INVALID_ID; + s->context = VA_INVALID_ID; +} + +void dmd_context_reset_locked(struct dmd_context *c) +{ + /* session_destroy 会 close socket。它不阻塞(close 不等对端), + * 所以在这里做是安全的。 */ + if (c->session) + dmd_session_destroy(c->session); + free(c->slice_data); + memset(c, 0, sizeof(*c)); + c->id = VA_INVALID_ID; + c->current_target = VA_INVALID_ID; +} + +/* ================================ surface ================================ */ + +/* 按显示尺寸分配一个 surface 的 NV12 缓冲。 + * + * 几何:宽对齐 128、高对齐 32(Venus 的真机行为,1080p → 1920x1088)。 + * 预先按对齐尺寸分配,这样 daemon 回来的帧一定装得下 —— 否则要等收到 + * 格式块才知道该分配多大,而 ffmpeg 在建 context 之前就要 surface。 + */ +/* 用 msm_drm 的 dumb buffer 分配一块**可导出为 dmabuf** 的内存。 + * + * 为什么需要:Firefox 拿帧走 vaExportSurfaceHandle → DRM_PRIME_2, + * 失败就整条流回落软解,且**没有拷贝回退路径** + * (FFmpegVideoDecoder.cpp:1632 GetVAAPISurfaceDescriptor)。 + * 所以帧必须落在能导出 fd 的内存里。 + * + * 注意这**不是**零拷贝:MediaCodec 那块内存我们仍然拿不到 fd + * (容器 ION 不可用、无 /dev/dma_heap、NDK 也不给输出缓冲的 fd)。 + * 这里是自己分配可导出内存,让 daemon 回传的帧直接落进来 —— + * 拷贝次数与原来的 calloc 方案相同,但多了"可被合成器导入"这个能力。 + * + * 失败返回 -1,调用方回落到普通 heap(ffmpeg 的 hwdownload 路径不需要导出)。 + */ +static int surface_alloc_dumb(struct dmd_surface *s, int drm_fd, + unsigned int bw, unsigned int bh, size_t size) +{ + if (drm_fd < 0) + return -1; + + struct drm_mode_create_dumb creq; + memset(&creq, 0, sizeof(creq)); + creq.width = bw; + /* NV12 总行数 = Y 的 bh 再加 UV 的 bh/2。按 8bpp 单平面申请, + * 我们自己按 offset 切分 Y/UV。 */ + creq.height = bh * 3 / 2; + creq.bpp = 8; + if (ioctl(drm_fd, DRM_IOCTL_MODE_CREATE_DUMB, &creq) != 0) + return -1; + + /* pitch 必须正好是我们期望的 stride,否则几何对不上 daemon 的帧。 */ + if (creq.pitch != bw || creq.size < size) { + struct drm_mode_destroy_dumb dreq; + memset(&dreq, 0, sizeof(dreq)); + dreq.handle = creq.handle; + ioctl(drm_fd, DRM_IOCTL_MODE_DESTROY_DUMB, &dreq); + dmd_log("dumb buffer 几何不符:pitch=%u 期望 %u,size=%llu 需要 %zu\n", + creq.pitch, bw, (unsigned long long)creq.size, size); + return -1; + } + + struct drm_mode_map_dumb mreq; + memset(&mreq, 0, sizeof(mreq)); + mreq.handle = creq.handle; + if (ioctl(drm_fd, DRM_IOCTL_MODE_MAP_DUMB, &mreq) != 0) { + struct drm_mode_destroy_dumb dreq; + memset(&dreq, 0, sizeof(dreq)); + dreq.handle = creq.handle; + ioctl(drm_fd, DRM_IOCTL_MODE_DESTROY_DUMB, &dreq); + return -1; + } + + void *map = mmap(NULL, creq.size, PROT_READ | PROT_WRITE, MAP_SHARED, + drm_fd, (off_t)mreq.offset); + if (map == MAP_FAILED) { + struct drm_mode_destroy_dumb dreq; + memset(&dreq, 0, sizeof(dreq)); + dreq.handle = creq.handle; + ioctl(drm_fd, DRM_IOCTL_MODE_DESTROY_DUMB, &dreq); + return -1; + } + memset(map, 0, creq.size); + + s->dumb_handle = creq.handle; + s->dumb_size = creq.size; + s->dumb_drm_fd = drm_fd; + s->data = (unsigned char *)map; + s->data_size = creq.size; + s->exportable = 1; + return 0; +} + +static VAStatus surface_alloc_locked(struct dmd_surface *s, VASurfaceID id, + unsigned int width, unsigned int height, + unsigned int format, int drm_fd) +{ + unsigned int bw = dmd_align_up(width, DMD_WIDTH_ALIGN); + unsigned int bh = dmd_align_up(height, DMD_HEIGHT_ALIGN); + /* NV12:Y 平面 stride*slice_height,UV 平面是它的一半 */ + size_t size = (size_t)bw * bh * 3 / 2; + + memset(s, 0, sizeof(*s)); + + /* 优先用可导出的 dumb buffer;不支持就退回普通 heap。 */ + if (surface_alloc_dumb(s, drm_fd, bw, bh, size) != 0) { + unsigned char *data = calloc(1, size); + if (!data) + return VA_STATUS_ERROR_ALLOCATION_FAILED; + s->data = data; + s->data_size = size; + s->exportable = 0; + s->dumb_handle = 0; + } + + s->in_use = 1; + s->id = id; + s->width = width; + s->height = height; + s->buf_width = bw; + s->buf_height = bh; + s->stride = bw; + s->slice_height = bh; + s->format = format; + s->state = DMD_SURFACE_IDLE; + s->decode_status = VA_STATUS_SUCCESS; + s->context = VA_INVALID_ID; + return VA_STATUS_SUCCESS; +} + +static VAStatus create_surfaces_common(VADriverContextP ctx, + unsigned int format, unsigned int width, + unsigned int height, + VASurfaceID *surfaces, + unsigned int num_surfaces) +{ + struct dmd_driver *drv = dmd_get_driver(ctx); + + if (!drv || !surfaces) + return VA_STATUS_ERROR_INVALID_PARAMETER; + if (num_surfaces == 0) + return VA_STATUS_ERROR_INVALID_PARAMETER; + if (width < DMD_MIN_WIDTH || height < DMD_MIN_HEIGHT || + width > DMD_MAX_WIDTH || height > DMD_MAX_HEIGHT) + return VA_STATUS_ERROR_RESOLUTION_NOT_SUPPORTED; + /* 只支持 8-bit 4:2:0。谎报会让消费者选中我们然后拿到花屏。 */ + if (format != VA_RT_FORMAT_YUV420) + return VA_STATUS_ERROR_UNSUPPORTED_RT_FORMAT; + + VAStatus status = VA_STATUS_SUCCESS; + unsigned int created = 0; + + pthread_mutex_lock(&drv->lock); + for (unsigned int n = 0; n < num_surfaces; n++) { + struct dmd_surface *slot = NULL; + for (int i = 0; i < DMD_MAX_SURFACES; i++) { + if (!drv->surfaces[i].in_use) { + slot = &drv->surfaces[i]; + break; + } + } + if (!slot) { + status = VA_STATUS_ERROR_ALLOCATION_FAILED; + break; + } + + VASurfaceID id = (VASurfaceID)(drv->next_surface_id++); + status = surface_alloc_locked(slot, id, width, height, format, + drv->drm_fd); + if (status != VA_STATUS_SUCCESS) + break; + + surfaces[n] = id; + created++; + } + + /* 部分失败要回滚:VA-API 语义是全成或全败,留下半个数组会让 + * 消费者把未初始化的 ID 当合法 surface 用。 */ + if (status != VA_STATUS_SUCCESS) { + for (unsigned int n = 0; n < created; n++) { + struct dmd_surface *s = dmd_find_surface_locked(drv, surfaces[n]); + if (s) + dmd_surface_reset_locked(s); + surfaces[n] = VA_INVALID_ID; + } + } + pthread_mutex_unlock(&drv->lock); + + if (status == VA_STATUS_SUCCESS) + dmd_log("CreateSurfaces: %ux%u fourcc=NV12 n=%u -> id %u..\n", width, + height, num_surfaces, (unsigned)surfaces[0]); + else + dmd_log("CreateSurfaces: 失败 status=0x%x(已创建 %u 个,已回滚)\n", + status, created); + + return status; +} + +VAStatus dmd_CreateSurfaces(VADriverContextP ctx, int width, int height, + int format, int num_surfaces, VASurfaceID *surfaces) +{ + if (width <= 0 || height <= 0 || num_surfaces <= 0) + return VA_STATUS_ERROR_INVALID_PARAMETER; + return create_surfaces_common(ctx, (unsigned int)format, + (unsigned int)width, (unsigned int)height, + surfaces, (unsigned int)num_surfaces); +} + +VAStatus dmd_CreateSurfaces2(VADriverContextP ctx, unsigned int format, + unsigned int width, unsigned int height, + VASurfaceID *surfaces, unsigned int num_surfaces, + VASurfaceAttrib *attrib_list, + unsigned int num_attribs) +{ + /* attrib_list 里 ffmpeg 只可能传 PixelFormat(要 NV12)与 + * MemoryType(要 VA 内部,我们不支持外部内存导入)。 + * 我们唯一支持的组合就是默认组合,因此校验后忽略。 */ + if (num_attribs > 0 && !attrib_list) + return VA_STATUS_ERROR_INVALID_PARAMETER; + + for (unsigned int i = 0; i < num_attribs; i++) { + if (attrib_list[i].type == VASurfaceAttribPixelFormat) { + if (attrib_list[i].value.type != VAGenericValueTypeInteger) + return VA_STATUS_ERROR_INVALID_PARAMETER; + if ((unsigned int)attrib_list[i].value.value.i != VA_FOURCC_NV12) + return VA_STATUS_ERROR_UNSUPPORTED_RT_FORMAT; + } else if (attrib_list[i].type == VASurfaceAttribMemoryType) { + /* 只支持驱动自己分配的内存。dmabuf/用户指针导入这条路 + * 在容器里走不通(ION 不可用、无 /dev/dma_heap)。 */ + if (attrib_list[i].value.type != VAGenericValueTypeInteger) + return VA_STATUS_ERROR_INVALID_PARAMETER; + if (!(attrib_list[i].value.value.i & + VA_SURFACE_ATTRIB_MEM_TYPE_VA)) + return VA_STATUS_ERROR_UNSUPPORTED_MEMORY_TYPE; + } else if (attrib_list[i].type == VASurfaceAttribExternalBufferDescriptor) { + return VA_STATUS_ERROR_UNSUPPORTED_MEMORY_TYPE; + } + /* 其余属性(Usage hint 等)无害,忽略。 */ + } + + return create_surfaces_common(ctx, format, width, height, surfaces, + num_surfaces); +} + +VAStatus dmd_DestroySurfaces(VADriverContextP ctx, VASurfaceID *surface_list, + int num_surfaces) +{ + struct dmd_driver *drv = dmd_get_driver(ctx); + + if (!drv || !surface_list || num_surfaces <= 0) + return VA_STATUS_ERROR_INVALID_PARAMETER; + + VAStatus status = VA_STATUS_SUCCESS; + + pthread_mutex_lock(&drv->lock); + for (int i = 0; i < num_surfaces; i++) { + struct dmd_surface *s = dmd_find_surface_locked(drv, surface_list[i]); + if (!s) { + /* 继续销毁其余的:半途返回会泄漏后面那些。 + * 但仍要把错误报上去,调用方有 bug 该知道。 */ + status = VA_STATUS_ERROR_INVALID_SURFACE; + continue; + } + dmd_surface_reset_locked(s); + } + pthread_mutex_unlock(&drv->lock); + + return status; +} + +/* ================================ context ================================ */ + +/* 建 daemon 会话。调用方**不得持锁** —— connect 与握手是阻塞 IO。 */ +static struct dmd_session *session_open(int codec, unsigned int width, + unsigned int height) +{ + struct dmd_session_config cfg; + struct dmd_error err; + + dmd_session_config_init(&cfg); + cfg.codec = codec; + cfg.width = (int)width; + cfg.height = (int)height; + cfg.io_timeout_ms = DMD_FRAME_TIMEOUT_MS; + + /* 端点选择:Unix socket 优先,TCP 兜底。 + * + * DMD_ENDPOINT 可显式指定: + * unix:/run/dmd.sock 连该路径的 Unix socket + * tcp:20003 连 127.0.0.1 的该端口 + * 不设时按 DMD_DEFAULT_SOCK → TCP 的顺序自动探测。 + * + * 为什么 Unix socket 优先:它**不属于 net namespace**,平台把宿主上的 + * socket 文件 bind mount 进容器即可,两类容器都通;而 TCP 127.0.0.1 + * 只在共享 net namespace 时可达 —— 实测 DroidSpaces 的 NAT 型容器 + * netns 独立(4026535650 vs 宿主 4026531937),TCP loopback 与 + * abstract socket 都不通,只有路径式 Unix socket 这条路。 + * + * ⚠️ 勘误:这里一度写着"能连上 Unix socket 就意味着 SCM_RIGHTS 可用, + * 于是可以请求 SHM 传输"。**那个推论是错的。** + * + * SHM 的 memfd 交接并不走这条控制通道,而是 daemon 另开一个 + * **abstract** socket(decode-daemon.c 里 sun_path[0] = 0 那处), + * 驱动再去连它。abstract socket 属于 net namespace —— + * 于是 NAT 型容器(netns 独立)根本连不上那个交接通道, + * 请求 SHM 在那里必然交接失败再降级,每建一次会话白等一次超时。 + * 这正是下方 want_shm 判定要用 `use_sock ? ... : 0` 的原因 —— + * 只有走上路径式 Unix socket(即 host 型容器)才请求 SHM。 + * + * 换句话说:**控制通道跨 netns 的能力,不等于 SHM 交接通道也跨得过去。** + * 要让零拷贝在 NAT 容器可用,得把 memfd 交接也改走这条路径式 + * Unix socket(同一个连接上传 SCM_RIGHTS 即可,不必另开 socket), + * 那是一项独立改动,尚未做。 */ + const char *ep = getenv("DMD_ENDPOINT"); + char sockbuf[256]; + const char *use_sock = NULL; + + if (ep && strncmp(ep, "unix:", 5) == 0) { + snprintf(sockbuf, sizeof(sockbuf), "%s", ep + 5); + use_sock = sockbuf; + } else if (ep && strncmp(ep, "tcp:", 4) == 0) { + int p = atoi(ep + 4); + if (p > 0 && p < 65536) + cfg.port = (uint16_t)p; + } else if (!ep) { + /* 未显式指定:默认路径存在且是 socket 就用它 */ + struct stat st; + if (stat(DMD_DEFAULT_SOCK, &st) == 0 && S_ISSOCK(st.st_mode)) + use_sock = DMD_DEFAULT_SOCK; + } + + cfg.sock_path = use_sock; + /* SHM(memfd 零拷贝)在 Unix socket 模式下**默认开启**(2026-08-26 起)。 + * 设 DMD_WANT_SHM=0 可显式关闭(排查用)。 + * + * 端到端实测依据:驱动被 dlopen 进 ffmpeg 进程、走 /run/dmd/decode.sock, + * daemon 侧日志确认 + * 共享内存已交接: 8 槽 x 3133440 字节 (共 25067520) + * 握手成功: video/hevc 1280x720 帧回传=SHM + * (槽位数 v0.3.7 由 4 改为 8,见 src/decode-daemon.c 的 SHM_SLOTS; + * 上面这条 hevc 日志是当时的取证样例,HEVC 路径本身尚未系统验证。) + * 且解码结果与内联模式一致(150/150 帧)。 + * + * 收益(固定 1500 帧工作量,三组交替对照,daemon 侧 CPU jiffies): + * 内联 493 / 500 / 489 中位数 493 + * SHM 400 / 367 / 410 中位数 400 → 降低约 19% + * 省下的正是每帧 1.38MB(720p) 经 socket 的那次拷贝。 + * + * ⚠️ 注意"零拷贝"只描述 memfd → 消费者进程这一段。MediaCodec 的输出 + * 缓冲由 gralloc 分配,daemon 只能 getOutputBuffer 拿到 CPU 指针后 + * memcpy 进 memfd(decode-daemon.c 的 send_frame_shm)。解码器到 memfd + * 那次拷贝仍在,消除它要走 dmabuf,而那条路因需依赖私有符号已被否决。 + * + * 保守的部分:只在 use_sock 时请求 —— SHM 交接走 abstract socket + * (属 net namespace),所以**NAT 型容器必然降级**。daemon 侧交接失败 + * 会自动退回内联,因此默认开启没有硬失败风险。 + * + * ── 以下是历史顾虑,均已被实测解决,保留供参考 ── + * + * 曾长期默认关闭(cfg.want_shm 硬编码为 0),理由是这条路"驱动侧从未 + * 真正启用过":只有 tests/test_dmd_client.c 走过,那是独立测试程序, + * 不是驱动被 dlopen 进消费者进程的真实环境。这个顾虑本身是对的 —— + * 文档一度据那组数字声称 SHM 有 +17% 吞吐,而真实路径从未执行过。 + * 教训:判断某能力是否生效,要先确认它的开关是开的。 + * + * 曾担心浏览器沙箱收不了 SCM_RIGHTS(Firefox RDD / Chrome GPU 都有 + * seccomp 过滤)。实测可行。本项目在这类判断上有先例 —— 一份源码级结论 + * 说 RDD 沙箱对 SYS_SOCKET 一律返回 EACCES,实测却跑通了 713 帧。 + * 这类事只能靠实测,读源码推不出来。 + * + * ⚠️ 勘误:此处一度写着"SHM 帧交付路径有 bug、daemon 在 memfd 交接后 + * 不再服务、根因未定位"。**那个归因是错的**。那些 0 帧现象的真实原因是 + * SELinux domain 权限 —— daemon 以 runcon u:r:droidspacesd:s0 启动时能建 + * socket,但无权访问 hwservicemanager/Codec2,于是在 CCodec::allocate 处 + * SIGABRT(tombstone 栈顶 Codec2Client::GetServiceNames, + * "Hardware service manager is not running")。与 SHM 无关 —— + * 当时日志里的传输模式其实是 TCP。三组对照实验: + * u:r:ksu:s0 + TCP → 正常解码(但该 domain 无权 bind) + * u:r:droidspacesd:s0 + TCP → 同样 SIGABRT(与传输方式无关) + * u:r:droidspacesd:s0 + Unix socket + SELinux permissive → 正常解码 + * 结论:Unix socket 通道本身是正确的,缺的只是一条 allow 规则。 */ + const char *wantshm = getenv("DMD_WANT_SHM"); + cfg.want_shm = use_sock ? (wantshm ? (*wantshm == '1') : 1) : 0; + + memset(&err, 0, sizeof(err)); + struct dmd_session *s = dmd_session_create(&cfg, &err); + + /* Unix socket 连不上就退回 TCP —— 平台没挂载时仍能工作。 */ + if (!s && use_sock) { + dmd_log("Unix socket %s 连接失败(%s),退回 TCP\n", + use_sock, err.msg); + cfg.sock_path = NULL; + cfg.want_shm = 0; + memset(&err, 0, sizeof(err)); + s = dmd_session_create(&cfg, &err); + } + + if (!s) + dmd_log("会话建立失败: code=%d handshake=%d %s\n", err.code, + err.handshake_status, err.msg); + else + dmd_log("会话已建立: codec=%d %ux%u 端点=%s xfer=%d\n", codec, + width, height, + cfg.sock_path ? cfg.sock_path : "tcp/127.0.0.1", + dmd_session_xfer_mode(s)); + return s; +} + +/* flush 过的会话已不能再送数据,透明换一条新的。 + * + * ⚠️ **重建会摧毁参考帧链,代价不是"慢"而是"画面坏"。** + * + * 曾有一份探针(tools/probe_rebuild.c)报告"从非 IDR 帧续传也能立刻出帧 + * (续传 12 个 VCL 出 9 帧),所以不会有可见花屏"—— 那个结论**是错的**: + * 它只数了帧数,没看画面,那些帧全是纯黑(Y=16)。探针文件开头已标注 + * 自身不可信,不要再引用它的结论。 + * + * 真相:任何丢弃解码器状态的操作(flush 或重建)都会摧毁参考帧链, + * 而 P/B 帧必须依赖它。从非 IDR 位置重新开始,要一直黑到下一个 IDR + * (本测试流每 30 帧一个,故最多连黑 29 帧)。这正是"浏览器播放时 + * 画面一闪一闪"的根因 —— 实测 135/708 帧纯黑。 + * + * 所以重建**必须尽量避免**,而不是"可以放心用"。真要重建, + * 正确做法是从最近的 IDR 重放并丢弃重放出的帧(见 tools/probe_replay.c)。 + * 当前实现的策略是把触发条件收紧到几乎不发生(见 wait_is_futile 的判据)。 + * + * 调用方必须持锁;本函数内部会临时放锁做阻塞 IO(connect + 握手)。 + * 返回 0 成功,-1 失败(失败时 c->session 置空,由调用方走失败路径)。 + */ +static int session_rebuild_locked(struct dmd_driver *drv, struct dmd_context *c, + int idx) +{ + struct dmd_session *old = c->session; + int codec = c->codec; + unsigned int w = c->picture_width; + unsigned int h = c->picture_height; + + /* 先摘下旧会话,避免放锁期间别的线程还往里写。 */ + c->session = NULL; + + drv->io_busy[idx] = 1; + pthread_mutex_unlock(&drv->lock); + if (old) + dmd_session_destroy(old); + struct dmd_session *ns = session_open(codec, w, h); + pthread_mutex_lock(&drv->lock); + drv->io_busy[idx] = 0; + pthread_cond_broadcast(&drv->io_done); + + if (!ns) { + dmd_log("会话重建失败\n"); + c->session_failed = 1; + return -1; + } + + c->session = ns; + c->input_finished = 0; + /* 新会话的 daemon 侧 vcl_in 从 1 重新开始,这里必须同步归零, + * 否则提交序号与回传的 PTS 错位,配对会持续走"无匹配"回退路径。 + * ⚠️ 队列里残留的旧序号必须一并作废,否则新会话发出的号会与它们撞车: + * 实测 test1080 出现两次 unit 5、35 次"无匹配"回退、70/150 帧错位。 + * 置 0 表示"该项无有效序号",不会匹配任何回传的 PTS, + * 只能由回退推断按顺序配掉 —— 这正是需要的语义。 */ + c->units_submitted = 0; + for (int k = 0; k < c->pending_count; k++) { + int idx = (c->pending_head + k) % DMD_MAX_SURFACES; + c->pending_unit[idx] = 0; + } + /* 参数集属于旧会话的状态,新会话必须重送 —— 清掉"已送"标记, + * 下一次 EndPicture 的既有逻辑就会重新合成并发送 SPS/PPS。 */ + c->param_sets_sent = 0; + dmd_log("会话已重建(codec=%d %ux%u),参数集将重送\n", codec, w, h); + return 0; +} + +VAStatus dmd_CreateContext(VADriverContextP ctx, VAConfigID config_id, + int picture_width, int picture_height, int flag, + VASurfaceID *render_targets, int num_render_targets, + VAContextID *context) +{ + struct dmd_driver *drv = dmd_get_driver(ctx); + + if (!drv || !context) + return VA_STATUS_ERROR_INVALID_PARAMETER; + if (num_render_targets < 0 || + (num_render_targets > 0 && !render_targets)) + return VA_STATUS_ERROR_INVALID_PARAMETER; + if (num_render_targets > DMD_MAX_SURFACES) + return VA_STATUS_ERROR_INVALID_PARAMETER; + if (picture_width < DMD_MIN_WIDTH || picture_height < DMD_MIN_HEIGHT || + picture_width > DMD_MAX_WIDTH || picture_height > DMD_MAX_HEIGHT) + return VA_STATUS_ERROR_RESOLUTION_NOT_SUPPORTED; + + *context = VA_INVALID_ID; + + VAProfile profile; + int codec; + int slot_idx = -1; + + pthread_mutex_lock(&drv->lock); + + /* config 必须有效,并从它推导 codec。 */ + struct dmd_config *cfg = NULL; + for (int i = 0; i < DMD_MAX_CONFIGS; i++) { + if (drv->configs[i].in_use && drv->configs[i].id == config_id) { + cfg = &drv->configs[i]; + break; + } + } + if (!cfg) { + pthread_mutex_unlock(&drv->lock); + return VA_STATUS_ERROR_INVALID_CONFIG; + } + profile = cfg->profile; + codec = dmd_profile_to_codec(profile); + if (codec < 0) { + pthread_mutex_unlock(&drv->lock); + return VA_STATUS_ERROR_UNSUPPORTED_PROFILE; + } + + /* render target 必须都是已存在的 surface。 */ + for (int i = 0; i < num_render_targets; i++) { + if (!dmd_find_surface_locked(drv, render_targets[i])) { + pthread_mutex_unlock(&drv->lock); + return VA_STATUS_ERROR_INVALID_SURFACE; + } + } + + for (int i = 0; i < DMD_MAX_CONTEXTS; i++) { + if (!drv->contexts[i].in_use) { + slot_idx = i; + break; + } + } + if (slot_idx < 0) { + pthread_mutex_unlock(&drv->lock); + dmd_log("CreateContext: 槽位耗尽(上限 %d)\n", DMD_MAX_CONTEXTS); + return VA_STATUS_ERROR_ALLOCATION_FAILED; + } + + struct dmd_context *c = &drv->contexts[slot_idx]; + memset(c, 0, sizeof(*c)); + c->in_use = 1; + c->id = (VAContextID)(drv->next_context_id++); + c->config_id = config_id; + c->profile = profile; + c->codec = codec; + c->picture_width = (unsigned int)picture_width; + c->picture_height = (unsigned int)picture_height; + c->flag = flag; + c->current_target = VA_INVALID_ID; + + VAContextID new_id = c->id; + pthread_mutex_unlock(&drv->lock); + + /* 会话建立在放锁后做 —— connect + 握手是阻塞 IO,持锁做会卡住 + * 其他线程的所有对象操作。 */ + struct dmd_session *sess = + session_open(codec, (unsigned int)picture_width, + (unsigned int)picture_height); + + pthread_mutex_lock(&drv->lock); + /* 重新查找:理论上没人能销毁一个还没交给调用方的 context, + * 但按 ID 复查比缓存指针更耐并发。 */ + c = dmd_find_context_locked(drv, new_id); + if (!c) { + pthread_mutex_unlock(&drv->lock); + if (sess) + dmd_session_destroy(sess); + return VA_STATUS_ERROR_OPERATION_FAILED; + } + c->session = sess; + /* 会话建不起来不让 CreateContext 失败:daemon 可能只是暂时不可用, + * 首次 EndPicture 会重试。失败时报的错更贴近真实原因。 */ + c->session_failed = sess ? 0 : 1; + pthread_mutex_unlock(&drv->lock); + + *context = new_id; + dmd_log("CreateContext: config=%u profile=%d %dx%d -> context=%u%s\n", + (unsigned)config_id, (int)profile, picture_width, picture_height, + (unsigned)new_id, sess ? "" : "(会话待重试)"); + + return VA_STATUS_SUCCESS; +} + +VAStatus dmd_DestroyContext(VADriverContextP ctx, VAContextID context) +{ + struct dmd_driver *drv = dmd_get_driver(ctx); + + if (!drv) + return VA_STATUS_ERROR_INVALID_PARAMETER; + + pthread_mutex_lock(&drv->lock); + struct dmd_context *c = dmd_find_context_locked(drv, context); + if (!c) { + pthread_mutex_unlock(&drv->lock); + return VA_STATUS_ERROR_INVALID_CONTEXT; + } + + /* 有 IO 在飞时不能拆:等它结束。带超时避免死等 —— 宁可泄漏一个 + * 会话也不能挂死宿主进程的 Terminate 路径。 */ + int idx = (int)(c - drv->contexts); + int waited = 0; + while (drv->io_busy[idx] && waited < DMD_FRAME_TIMEOUT_MS) { + struct timespec ts; + clock_gettime(CLOCK_REALTIME, &ts); + ts.tv_nsec += 50 * 1000 * 1000; + if (ts.tv_nsec >= 1000000000L) { + ts.tv_sec++; + ts.tv_nsec -= 1000000000L; + } + pthread_cond_timedwait(&drv->io_done, &drv->lock, &ts); + waited += 50; + c = dmd_find_context_locked(drv, context); + if (!c) { + pthread_mutex_unlock(&drv->lock); + return VA_STATUS_SUCCESS; + } + } + + /* 归还所有属于本 context 的 buffer:ffmpeg 正常会自己 Destroy, + * 但异常路径下可能漏,driver 不能因此泄漏。 */ + for (int i = 0; i < DMD_MAX_BUFFERS; i++) { + struct dmd_buffer *b = &drv->buffers[i]; + if (b->in_use && b->context == context) { + free(b->data); + memset(b, 0, sizeof(*b)); + } + } + + /* 先把解码器里还在飞的帧排空,再考虑放弃剩下的。 + * + * 为什么必需:ffmpeg 在**流内分辨率变化**时会先 DestroyContext 再建新的, + * 但它**之后仍会 vaSyncSurface 旧 context 的 surface**(那些帧属于前一段 + * 分辨率,它还要取走)。实测 switch.h264 在此处送入 62 单元只取回 44 帧 + * —— 若直接把余下 18 个 surface 标成失败,ffmpeg 就会收到 + * "1 (operation failed)",整条流解不下去。 + * + * 这些帧并没有错,只是还攥在 MediaCodec 里:和流末尾一样,需要关掉写端 + * 才会吐出来。所以这里做一次和 SyncSurface 相同的 flush + 取帧循环。 + * 上面已经等过 io_busy,此刻没有别的线程在这个 context 上做 IO。 */ + if (c->session && c->pending_count > 0) { + struct dmd_session *fs = c->session; + if (!c->input_finished) { + c->input_finished = 1; + drv->io_busy[idx] = 1; + pthread_mutex_unlock(&drv->lock); + dmd_session_finish_input(fs); + pthread_mutex_lock(&drv->lock); + drv->io_busy[idx] = 0; + pthread_cond_broadcast(&drv->io_done); + c = dmd_find_context_locked(drv, context); + if (!c) { + pthread_mutex_unlock(&drv->lock); + return VA_STATUS_SUCCESS; + } + } + + int drained = 0; + int budget = DMD_FRAME_TIMEOUT_MS; + while (c->pending_count > 0 && budget > 0) { + struct dmd_frame frame; + memset(&frame, 0, sizeof(frame)); + drv->io_busy[idx] = 1; + pthread_mutex_unlock(&drv->lock); + int frc = dmd_session_next_frame(fs, &frame, 100); + pthread_mutex_lock(&drv->lock); + drv->io_busy[idx] = 0; + pthread_cond_broadcast(&drv->io_done); + budget -= 100; + + c = dmd_find_context_locked(drv, context); + if (!c) { + if (frc == DMD_OK) + dmd_session_release_frame(fs, &frame); + pthread_mutex_unlock(&drv->lock); + return VA_STATUS_SUCCESS; + } + if (frc == DMD_ERR_TIMEOUT) + continue; + if (frc != DMD_OK) + break; /* EOS 或真错误:剩下的确实取不到了 */ + + VASurfaceID id = dmd_pending_take_locked(c, frame.unit_seq); + struct dmd_surface *ds = dmd_find_surface_locked(drv, id); + if (ds) { + surface_store_frame_locked(ds, &frame); + ds->state = DMD_SURFACE_READY; + drained++; + } + dmd_session_release_frame(fs, &frame); + } + if (drained) + dmd_log("DestroyContext: 排空补齐 %d 帧\n", drained); + } + + /* 仍未就绪的 surface 状态要复位,否则它们永远停在 PENDING, + * 后续 SyncSurface 会等一个永不到来的帧。 + * 注意保留 context 归属与 READY 状态:上面排空填好的帧 ffmpeg 还要取。 */ + for (int i = 0; i < DMD_MAX_SURFACES; i++) { + struct dmd_surface *s = &drv->surfaces[i]; + if (s->in_use && s->context == context && + s->state == DMD_SURFACE_PENDING) { + s->state = DMD_SURFACE_IDLE; + s->decode_status = VA_STATUS_ERROR_OPERATION_FAILED; + s->context = VA_INVALID_ID; + } + } + + dmd_log("DestroyContext: context=%u(送入 %llu 单元,取回 %llu 帧)\n", + (unsigned)context, + c->session ? (unsigned long long)dmd_session_units_sent(c->session) + : 0ULL, + c->session + ? (unsigned long long)dmd_session_frames_received(c->session) + : 0ULL); + + dmd_context_reset_locked(c); + pthread_mutex_unlock(&drv->lock); + + return VA_STATUS_SUCCESS; +} + +/* ================================ buffer ================================ */ + +VAStatus dmd_CreateBuffer(VADriverContextP ctx, VAContextID context, + VABufferType type, unsigned int size, + unsigned int num_elements, void *data, + VABufferID *buf_id) +{ + struct dmd_driver *drv = dmd_get_driver(ctx); + + if (!drv || !buf_id) + return VA_STATUS_ERROR_INVALID_PARAMETER; + if (size == 0 || num_elements == 0) + return VA_STATUS_ERROR_INVALID_PARAMETER; + /* 溢出检查:size 与 num_elements 都是 unsigned int,乘积可能回绕。 */ + if ((size_t)size * num_elements > DMD_MAX_FRAME_BYTES) + return VA_STATUS_ERROR_ALLOCATION_FAILED; + + *buf_id = VA_INVALID_ID; + size_t total = (size_t)size * num_elements; + + /* 分配放在锁外:大块 calloc 可能触发 mmap 与页错误。 */ + void *mem = calloc(1, total); + if (!mem) + return VA_STATUS_ERROR_ALLOCATION_FAILED; + if (data) + memcpy(mem, data, total); + + pthread_mutex_lock(&drv->lock); + + /* context 必须有效。VA-API 允许 VA_INVALID_ID 建"无 context" buffer, + * 但解码路径里 ffmpeg 总是带 context,所以只接受有效 context。 */ + if (!dmd_find_context_locked(drv, context)) { + pthread_mutex_unlock(&drv->lock); + free(mem); + return VA_STATUS_ERROR_INVALID_CONTEXT; + } + + struct dmd_buffer *slot = NULL; + for (int i = 0; i < DMD_MAX_BUFFERS; i++) { + if (!drv->buffers[i].in_use) { + slot = &drv->buffers[i]; + break; + } + } + if (!slot) { + pthread_mutex_unlock(&drv->lock); + free(mem); + dmd_log("CreateBuffer: 槽位耗尽(上限 %d)\n", DMD_MAX_BUFFERS); + return VA_STATUS_ERROR_ALLOCATION_FAILED; + } + + memset(slot, 0, sizeof(*slot)); + slot->in_use = 1; + slot->id = (VABufferID)(drv->next_buffer_id++); + slot->context = context; + slot->type = type; + slot->element_size = size; + slot->num_elements = num_elements; + slot->size = total; + slot->data = mem; + + *buf_id = slot->id; + pthread_mutex_unlock(&drv->lock); + + return VA_STATUS_SUCCESS; +} + +VAStatus dmd_BufferSetNumElements(VADriverContextP ctx, VABufferID buf_id, + unsigned int num_elements) +{ + struct dmd_driver *drv = dmd_get_driver(ctx); + + if (!drv || num_elements == 0) + return VA_STATUS_ERROR_INVALID_PARAMETER; + + pthread_mutex_lock(&drv->lock); + struct dmd_buffer *b = dmd_find_buffer_locked(drv, buf_id); + if (!b) { + pthread_mutex_unlock(&drv->lock); + return VA_STATUS_ERROR_INVALID_BUFFER; + } + if (b->mapped) { + /* 映射中改大小会让调用方手上的指针失效。 */ + pthread_mutex_unlock(&drv->lock); + return VA_STATUS_ERROR_OPERATION_FAILED; + } + + size_t total = (size_t)b->element_size * num_elements; + if (total > DMD_MAX_FRAME_BYTES) { + pthread_mutex_unlock(&drv->lock); + return VA_STATUS_ERROR_ALLOCATION_FAILED; + } + + VAStatus status = VA_STATUS_SUCCESS; + if (total > b->size) { + void *mem = realloc(b->data, total); + if (!mem) { + status = VA_STATUS_ERROR_ALLOCATION_FAILED; + } else { + memset((unsigned char *)mem + b->size, 0, total - b->size); + b->data = mem; + } + } + if (status == VA_STATUS_SUCCESS) { + b->num_elements = num_elements; + b->size = total; + } + pthread_mutex_unlock(&drv->lock); + + return status; +} + +VAStatus dmd_MapBuffer(VADriverContextP ctx, VABufferID buf_id, void **pbuf) +{ + struct dmd_driver *drv = dmd_get_driver(ctx); + + if (!drv || !pbuf) + return VA_STATUS_ERROR_INVALID_PARAMETER; + + *pbuf = NULL; + + pthread_mutex_lock(&drv->lock); + struct dmd_buffer *b = dmd_find_buffer_locked(drv, buf_id); + if (b) { + b->mapped++; + *pbuf = b->data; + pthread_mutex_unlock(&drv->lock); + return VA_STATUS_SUCCESS; + } + + /* VAImage 的后备存储也通过 vaMapBuffer 访问(image.buf 是个 buffer ID)。 + * ffmpeg 的回读路径正是这么取像素的。 */ + struct dmd_image *img = NULL; + for (int i = 0; i < DMD_MAX_IMAGES; i++) { + if (drv->images[i].in_use && drv->images[i].buf_id == buf_id) { + img = &drv->images[i]; + break; + } + } + if (!img) { + pthread_mutex_unlock(&drv->lock); + return VA_STATUS_ERROR_INVALID_BUFFER; + } + img->mapped++; + *pbuf = img->data; + pthread_mutex_unlock(&drv->lock); + + return VA_STATUS_SUCCESS; +} + +/* vaMapBuffer2 = vaMapBuffer + 读写意图提示。 + * + * ⚠️ 必须实现,不能留桩:libva 只在**槽位为 NULL** 时才回落到 vaMapBuffer + * (va.c 的 vaMapBuffer2),而我们为了通过 CHECK_VTABLE 把所有槽位都填了桩, + * 于是 ffmpeg 的 vaapi_map_frame(hwcontext_vaapi.c:928)拿到 UNIMPLEMENTED + * 就直接失败,永远走不到 vaMapBuffer 那条兼容分支。 + * 这是"填满 vtable"与"libva 靠 NULL 判断能力"之间的一个真实冲突。 + * + * flags 对我们无意义:后备存储是普通 heap 内存,读写都是直接访问。 */ +VAStatus dmd_MapBuffer2(VADriverContextP ctx, VABufferID buf_id, void **pbuf, + uint32_t flags) +{ + (void)flags; + return dmd_MapBuffer(ctx, buf_id, pbuf); +} + +VAStatus dmd_UnmapBuffer(VADriverContextP ctx, VABufferID buf_id) +{ + struct dmd_driver *drv = dmd_get_driver(ctx); + + if (!drv) + return VA_STATUS_ERROR_INVALID_PARAMETER; + + pthread_mutex_lock(&drv->lock); + struct dmd_buffer *b = dmd_find_buffer_locked(drv, buf_id); + if (b) { + if (b->mapped > 0) + b->mapped--; + pthread_mutex_unlock(&drv->lock); + return VA_STATUS_SUCCESS; + } + + for (int i = 0; i < DMD_MAX_IMAGES; i++) { + struct dmd_image *img = &drv->images[i]; + if (img->in_use && img->buf_id == buf_id) { + if (img->mapped > 0) + img->mapped--; + pthread_mutex_unlock(&drv->lock); + return VA_STATUS_SUCCESS; + } + } + pthread_mutex_unlock(&drv->lock); + + return VA_STATUS_ERROR_INVALID_BUFFER; +} + +VAStatus dmd_DestroyBuffer(VADriverContextP ctx, VABufferID buffer_id) +{ + struct dmd_driver *drv = dmd_get_driver(ctx); + + if (!drv) + return VA_STATUS_ERROR_INVALID_PARAMETER; + + pthread_mutex_lock(&drv->lock); + struct dmd_buffer *b = dmd_find_buffer_locked(drv, buffer_id); + if (!b) { + pthread_mutex_unlock(&drv->lock); + return VA_STATUS_ERROR_INVALID_BUFFER; + } + void *mem = b->data; + memset(b, 0, sizeof(*b)); + pthread_mutex_unlock(&drv->lock); + + free(mem); + return VA_STATUS_SUCCESS; +} + +VAStatus dmd_BufferInfo(VADriverContextP ctx, VABufferID buf_id, + VABufferType *type, unsigned int *size, + unsigned int *num_elements) +{ + struct dmd_driver *drv = dmd_get_driver(ctx); + + if (!drv || !type || !size || !num_elements) + return VA_STATUS_ERROR_INVALID_PARAMETER; + + pthread_mutex_lock(&drv->lock); + struct dmd_buffer *b = dmd_find_buffer_locked(drv, buf_id); + if (b) { + *type = b->type; + *size = b->element_size; + *num_elements = b->num_elements; + pthread_mutex_unlock(&drv->lock); + return VA_STATUS_SUCCESS; + } + + for (int i = 0; i < DMD_MAX_IMAGES; i++) { + struct dmd_image *img = &drv->images[i]; + if (img->in_use && img->buf_id == buf_id) { + *type = VAImageBufferType; + *size = (unsigned int)img->data_size; + *num_elements = 1; + pthread_mutex_unlock(&drv->lock); + return VA_STATUS_SUCCESS; + } + } + pthread_mutex_unlock(&drv->lock); + + return VA_STATUS_ERROR_INVALID_BUFFER; +} + +/* ============================ 帧提交(码流组装) ============================ */ + +/* 往 context 的本帧码流缓冲追加数据。调用方持锁。 */ +static int slice_append_locked(struct dmd_context *c, const void *data, + size_t len) +{ + if (len == 0) + return 0; + if (c->slice_len + len > DMD_MAX_UNIT_BYTES) + return -1; /* 超过 daemon 的 8MB 上限,送过去只会被判非法长度 */ + + if (c->slice_len + len > c->slice_cap) { + size_t cap = c->slice_cap ? c->slice_cap * 2 : 65536; + while (cap < c->slice_len + len) + cap *= 2; + unsigned char *mem = realloc(c->slice_data, cap); + if (!mem) + return -1; + c->slice_data = mem; + c->slice_cap = cap; + } + memcpy(c->slice_data + c->slice_len, data, len); + c->slice_len += len; + + return 0; +} + +VAStatus dmd_BeginPicture(VADriverContextP ctx, VAContextID context, + VASurfaceID render_target) +{ + struct dmd_driver *drv = dmd_get_driver(ctx); + + if (!drv) + return VA_STATUS_ERROR_INVALID_PARAMETER; + + pthread_mutex_lock(&drv->lock); + struct dmd_context *c = dmd_find_context_locked(drv, context); + if (!c) { + pthread_mutex_unlock(&drv->lock); + return VA_STATUS_ERROR_INVALID_CONTEXT; + } + struct dmd_surface *s = dmd_find_surface_locked(drv, render_target); + if (!s) { + pthread_mutex_unlock(&drv->lock); + return VA_STATUS_ERROR_INVALID_SURFACE; + } + + /* 上一帧没 EndPicture 就又 Begin:丢掉残留数据,否则会拼进新帧。 */ + if (c->current_target != VA_INVALID_ID) + dmd_log("BeginPicture: 上一帧未 EndPicture,丢弃 %zu 字节残留\n", + c->slice_len); + + c->current_target = render_target; + c->slice_len = 0; + c->av1_tile_count = 0; /* tile 边界随帧重置,与 slice_len 同生命周期 */ + c->have_vp8_slice_param = 0; + c->have_vp8_pic_param = 0; + + s->state = DMD_SURFACE_PENDING; + s->decode_status = VA_STATUS_SUCCESS; + s->context = context; + + pthread_mutex_unlock(&drv->lock); + return VA_STATUS_SUCCESS; +} + +VAStatus dmd_RenderPicture(VADriverContextP ctx, VAContextID context, + VABufferID *buffers, int num_buffers) +{ + struct dmd_driver *drv = dmd_get_driver(ctx); + + if (!drv || (num_buffers > 0 && !buffers)) + return VA_STATUS_ERROR_INVALID_PARAMETER; + if (num_buffers < 0) + return VA_STATUS_ERROR_INVALID_PARAMETER; + + pthread_mutex_lock(&drv->lock); + struct dmd_context *c = dmd_find_context_locked(drv, context); + if (!c) { + pthread_mutex_unlock(&drv->lock); + return VA_STATUS_ERROR_INVALID_CONTEXT; + } + if (c->current_target == VA_INVALID_ID) { + pthread_mutex_unlock(&drv->lock); + return VA_STATUS_ERROR_INVALID_CONTEXT; /* 没 BeginPicture */ + } + + VAStatus status = VA_STATUS_SUCCESS; + + for (int i = 0; i < num_buffers; i++) { + struct dmd_buffer *b = dmd_find_buffer_locked(drv, buffers[i]); + if (!b) { + status = VA_STATUS_ERROR_INVALID_BUFFER; + break; + } + + switch (b->type) { + case VASliceDataBufferType: + /* 这里是真正的码流。 + * VP9:整帧(含 uncompressed header,从 frame_marker 起),原样转发 + * VP8:partition 0 起,缺 RFC 6386 §9.1 的 uncompressed chunk + * H.264/HEVC:slice NALU 的**载荷**,不含起始码 */ + if (slice_append_locked(c, b->data, b->size) != 0) { + status = VA_STATUS_ERROR_ALLOCATION_FAILED; + } + break; + + case VASliceParameterBufferType: + /* AV1:每个 tile 一份 slice param(va_dec_av1.h:635), + * 它是 tile 边界的唯一可靠来源 —— slice data 可能整帧打包在 + * 一个 buffer 里,数追加次数会得到 1 而非真实 tile 数。 + * 一个 buffer 可携带多个元素(num_elements),要全部收下。 */ + if (c->codec == DMD_CODEC_AV1 && + b->element_size >= sizeof(VASliceParameterBufferAV1)) { + const int cap = (int)(sizeof(c->av1_tile_param) / + sizeof(c->av1_tile_param[0])); + for (unsigned int k = 0; k < b->num_elements; k++) { + if (c->av1_tile_count >= cap) + break; + const unsigned char *src = + (const unsigned char *)b->data + + (size_t)k * b->element_size; + memcpy(&c->av1_tile_param[c->av1_tile_count++], src, + sizeof(VASliceParameterBufferAV1)); + } + break; + } + /* VP8 需要 partition_size[0] 与 macroblock_offset 来推导 + * first_part_size,其余 codec 当前不需要 slice 参数。 */ + if (c->codec == DMD_CODEC_VP8 && + b->size >= sizeof(VASliceParameterBufferVP8)) { + memcpy(&c->vp8_slice_param, b->data, + sizeof(VASliceParameterBufferVP8)); + c->have_vp8_slice_param = 1; + } else if (c->codec == DMD_CODEC_H264 && + b->size >= sizeof(VASliceParameterBufferH264)) { + /* 留存备用。注意 PPS 的 num_ref_idx_default 不能取自这里: + * 参数集要在首个 VCL 之前发,那时只有 IDR 的 slice param, + * 而 I slice 的 num_ref_idx 恒为 0(详见 h264_bitstream.c)。 */ + memcpy(&c->h264_slice_param, b->data, + sizeof(VASliceParameterBufferH264)); + c->have_h264_slice_param = 1; + } + break; + + case VAPictureParameterBufferType: + /* AV1:序列头与帧头的全部字段都在这里,是合成 OBU 的唯一来源。 */ + if (c->codec == DMD_CODEC_AV1 && + b->size >= sizeof(VADecPictureParameterBufferAV1)) { + memcpy(&c->av1_pic_param, b->data, + sizeof(VADecPictureParameterBufferAV1)); + c->have_av1_pic_param = 1; + break; + } + /* VP8 的 key_frame / version / show_frame 相关位在这里。 */ + if (c->codec == DMD_CODEC_VP8 && + b->size >= sizeof(VAPictureParameterBufferVP8)) { + memcpy(&c->vp8_pic_param, b->data, + sizeof(VAPictureParameterBufferVP8)); + c->have_vp8_pic_param = 1; + } else if (c->codec == DMD_CODEC_HEVC && + b->size >= sizeof(VAPictureParameterBufferHEVC)) { + /* 用途同 H.264:合成 VPS/SPS/PPS,并取 POC 供配对回退路径用。 + * CurrPic.pic_order_cnt 是已解包的完整 POC,可直接比大小。 */ + memcpy(&c->hevc_pic_param, b->data, + sizeof(VAPictureParameterBufferHEVC)); + c->hevc_pic_param_valid = 1; + c->current_poc = c->hevc_pic_param.CurrPic.pic_order_cnt; + /* HEVC 没有 frame_num;用 IRAP 判定新序列: + * IDR 会把 POC 重置,配对时必须按 seq 分段。 */ + c->current_frame_num = + c->hevc_pic_param.slice_parsing_fields.bits.IdrPicFlag ? 0 : 1; + c->have_current_poc = 1; + } else if (c->codec == DMD_CODEC_H264 && + b->size >= sizeof(VAPictureParameterBufferH264)) { + /* 两个用途: + * 1) 反向合成 SPS/PPS —— ffmpeg 自己消费掉了参数集 NALU + * (h264dec.c:699/:717),driver 只能从这些字段重建 + * 2) 取本帧 POC(显示顺序)用于配对 —— MediaCodec 按显示序 + * 吐帧而 ffmpeg 按解码序提交,只有 POC 能把两者对上。 + * ffmpeg 填的是已解包的 field_poc[0](vaapi_h264.c:74), + * 不是码流里会回绕的 6 bit poc_lsb,可直接比较大小。 */ + memcpy(&c->h264_pic_param, b->data, + sizeof(VAPictureParameterBufferH264)); + c->have_h264_pic_param = 1; + c->current_poc = c->h264_pic_param.CurrPic.TopFieldOrderCnt; + c->current_frame_num = c->h264_pic_param.frame_num; + c->have_current_poc = 1; + } + break; + + case VAIQMatrixBufferType: + case VAProbabilityBufferType: + case VAHuffmanTableBufferType: + /* daemon 侧是完整解码器(MediaCodec),这些表都在码流里, + * 不需要我们转发。接受但忽略。 */ + break; + + default: + /* 未知类型不报错:某些消费者会附带我们不关心的 buffer, + * 拒绝会让整帧失败。 */ + break; + } + } + pthread_mutex_unlock(&drv->lock); + + return status; +} + +/* ---- VP8:合成 RFC 6386 §9.1 的 uncompressed data chunk ---- + * + * VA-API 的 slice data 从 partition 0(压缩帧头)开始,缺开头 3 字节 + * frame tag(key frame 再加 7 字节的 start code + 尺寸)。MediaCodec 要的是 + * 完整帧,所以必须补回来。 + * + * frame tag(3 字节,小端 19 位 + 尺寸): + * bit0 frame_type(0=key) + * bit1-3 version + * bit4 show_frame + * bit5-23 first_part_size + * first_part_size 的推导(关键):VA-API 的 partition_size[0] 是"应用解析后 + * 剩余的控制分区字节数",加上已被解析掉的头部字节 (macroblock_offset+7)/8 + * 才是 RFC 定义的 first_part_size。 + * show_frame 在 VA-API 里没有对应字段,只能假定 1 —— VP8 极少用 invisible 帧。 + */ +static size_t vp8_build_frame(struct dmd_context *c, unsigned char *out, + size_t out_cap) +{ + if (!c->have_vp8_slice_param || !c->have_vp8_pic_param) + return 0; + + const VASliceParameterBufferVP8 *sp = &c->vp8_slice_param; + const VAPictureParameterBufferVP8 *pp = &c->vp8_pic_param; + + unsigned int key_frame = pp->pic_fields.bits.key_frame ? 0 : 1; + /* VA-API 注释:"0 means a key frame",与 RFC 的 frame_type 同义 + * (RFC: 0=key frame)。这里 key_frame 变量表示"是关键帧"。 */ + key_frame = pp->pic_fields.bits.key_frame == 0 ? 1 : 0; + unsigned int version = pp->pic_fields.bits.version & 0x7; + unsigned int header_bytes = (sp->macroblock_offset + 7) / 8; + unsigned int first_part_size = sp->partition_size[0] + header_bytes; + if (first_part_size > 0x7FFFF) + return 0; /* 19 位装不下,码流异常 */ + + size_t tag_len = key_frame ? 10 : 3; + if (out_cap < tag_len + c->slice_len) + return 0; + + /* frame tag:3 字节小端位域 */ + uint32_t tag = (key_frame ? 0u : 1u) | (version << 1) | + (1u << 4) /* show_frame:VA-API 无此字段,假定可见 */ + | (first_part_size << 5); + out[0] = (unsigned char)(tag & 0xFF); + out[1] = (unsigned char)((tag >> 8) & 0xFF); + out[2] = (unsigned char)((tag >> 16) & 0xFF); + + if (key_frame) { + /* key frame 额外 7 字节:3 字节 start code 9D 01 2A + 2+2 字节尺寸。 + * 尺寸的高 2 bit 是 scaling,我们不缩放,填 0。 */ + out[3] = 0x9D; + out[4] = 0x01; + out[5] = 0x2A; + unsigned int w = pp->frame_width & 0x3FFF; + unsigned int h = pp->frame_height & 0x3FFF; + out[6] = (unsigned char)(w & 0xFF); + out[7] = (unsigned char)((w >> 8) & 0x3F); + out[8] = (unsigned char)(h & 0xFF); + out[9] = (unsigned char)((h >> 8) & 0x3F); + } + + memcpy(out + tag_len, c->slice_data, c->slice_len); + return tag_len + c->slice_len; +} + +/* 组装最终要送给 daemon 的数据单元。 + * 返回要送的缓冲(可能就是 c->slice_data 本身)与长度;失败返回 NULL。 + * scratch 由调用方提供并负责释放。 */ +static const unsigned char *build_unit(struct dmd_context *c, + unsigned char **scratch, size_t *out_len) +{ + *scratch = NULL; + + if (c->slice_len == 0) + return NULL; + + switch (c->codec) { + case DMD_CODEC_VP9: + /* 零 header 重建:VASliceDataBufferType 里就是完整的 VP9 frame + * (va_dec_vp9.h:274-284 的规范注释:slice data 含整帧, + * slice_data_size 实际就是 frame_data_size)。 */ + *out_len = c->slice_len; + return c->slice_data; + + case DMD_CODEC_AV1: { + /* AV1 必须反向合成 OBU —— 不能像 VP9 那样直接转发。 + * + * 为什么:VASliceDataBufferType 里只有 tile 的**载荷**,不含任何 + * OBU 封装(va_dec_av1.h:643-645 明确说"host decoder 负责解析出 + * per-tile 信息,码流按 per-tile 粒度送入驱动")。序列头与帧头 + * 只存在于 VADecPictureParameterBufferAV1 的结构化字段里。 + * + * 曾以为可以零重建,实测证伪:原样转发时首字节是 0xd0 + * (forbidden_bit=1、OBU 类型 10 保留值),ffprobe 报 + * "Failed to read obu / No sequence header available", + * MediaCodec 送入 1 单元取回 0 帧。VP9 的情形不同——它的 + * slice data 本身就是完整帧(va_dec_vp9.h:274-284)。 + * + * 组装出的 temporal unit: + * OBU_TEMPORAL_DELIMITER + * OBU_SEQUENCE_HEADER (仅关键帧,序列参数不会帧间变化) + * OBU_FRAME (帧头 + byte_alignment + tile_group) + * + * 用 OBU_FRAME(6) 而非分离的 FRAME_HEADER(3)+TILE_GROUP(4): + * 实测 dav1d 对分离形式报 "Failed to read unit",libaom 生成的 + * 真实码流用的也是 OBU_FRAME。 */ + if (!c->have_av1_pic_param || c->av1_tile_count <= 0) { + dmd_log("EndPicture: AV1 缺少 %s,无法合成 OBU", + c->have_av1_pic_param ? "tile 数据" : "pic param"); + return NULL; + } + + const VADecPictureParameterBufferAV1 *pp = &c->av1_pic_param; + const uint32_t want_tiles = + (uint32_t)pp->tile_cols * (uint32_t)pp->tile_rows; + if (want_tiles == 0 || (uint32_t)c->av1_tile_count != want_tiles) { + /* tile 数量与帧头声明不符会让解码器从第二个 tile 起全部错位, + * 与其送出去让 MediaCodec 解出花屏,不如干净回落软解。 */ + dmd_log("EndPicture: AV1 tile 数不符(收到 %d,帧头声明 %u),放弃硬解", + c->av1_tile_count, want_tiles); + return NULL; + } + + /* tile 描述表:用每个 tile 自己的 slice_data_offset/slice_data_size + * 在累积缓冲里定位(va_dec_av1.h:649-658)。不能靠"追加次数"—— + * 实机上 ffmpeg 把整帧 8 个 tile 打包在一个 slice data buffer 里。 */ + struct dmd_av1_tile tiles[512]; + for (int i = 0; i < c->av1_tile_count; i++) { + const VASliceParameterBufferAV1 *tp = &c->av1_tile_param[i]; + const size_t off = tp->slice_data_offset; + const size_t len = tp->slice_data_size; + if (len == 0 || off > c->slice_len || off + len > c->slice_len) { + dmd_log("EndPicture: AV1 tile[%d] 越界(off=%zu len=%zu," + "缓冲 %zu),放弃硬解", i, off, len, c->slice_len); + return NULL; + } + tiles[i].data = c->slice_data + off; + tiles[i].len = len; + } + + /* 输出缓冲:tile 载荷实际总长 + 每 tile 4 字节 tile_size + 头部余量。 + * 用 tile 长度之和而非 slice_len —— 两者可能不等(buffer 里允许有 + * 未被任何 tile 引用的间隙)。 */ + size_t tile_bytes = 0; + for (int i = 0; i < c->av1_tile_count; i++) + tile_bytes += tiles[i].len; + const size_t cap = tile_bytes + (size_t)c->av1_tile_count * 4 + 1024; + unsigned char *buf = malloc(cap); + if (!buf) + return NULL; + + size_t n = 0; + n += dmd_av1_obu_header(DMD_OBU_TEMPORAL_DELIMITER, 0, buf + n, cap - n); + + /* 序列头只在关键帧前发:AV1 允许重复发送,但每帧都发是浪费; + * 而序列级参数(尺寸、profile、能力位)在一个 session 内不变, + * 变了本驱动会重建 session。 */ + const uint32_t ft = pp->pic_info_fields.bits.frame_type; + if (ft == 0 /* KEY_FRAME */) { + const size_t sn = dmd_av1_build_sequence_header(pp, buf + n, cap - n); + if (sn == 0) { + dmd_log("EndPicture: AV1 序列头合成失败"); + free(buf); + return NULL; + } + n += sn; + } + + const size_t fn = dmd_av1_build_frame(pp, tiles, c->av1_tile_count, + buf + n, cap - n); + if (fn == 0) { + dmd_log("EndPicture: AV1 OBU_FRAME 合成失败(tile=%d, 载荷=%zu)", + c->av1_tile_count, tile_bytes); + free(buf); + return NULL; + } + n += fn; + + dmd_log("EndPicture: AV1 合成 %zu 字节(%s%d tile,载荷 %zu)", + n, ft == 0 ? "含序列头," : "", c->av1_tile_count, tile_bytes); + + /* DMD_AV1_DUMP=<路径>:把首帧合成结果落盘,供离线校验。 + * + * 这是本模块的主要验证手段,值得长期保留:合成正确性无法在设备上 + * 直接判断(MediaCodec 只会"不出帧",不告诉你哪一位错了),必须把 + * 字节取回来交给权威工具。实测有效的判据是 + * ffmpeg -f obu -i <落盘文件> -f null - (能否解出帧) + * ffmpeg -bsf:v trace_headers ... (逐字段比对位偏移) + * 后者是定位单个错误比特的唯一可行手段 —— 自制解析器不可靠, + * 曾因其自身偏差与实现错误互相抵消而误判"已对齐"。 + * + * 只落首帧:帧头字段最全(含序列头),且避免刷爆磁盘。 */ + if (getenv("DMD_AV1_DUMP")) { + static int dumped = 0; + if (!dumped) { + FILE *df = fopen(getenv("DMD_AV1_DUMP"), "wb"); + if (df) { fwrite(buf, 1, n, df); fclose(df); dumped = 1; + dmd_log("已落盘 %zu 字节到 %s", n, getenv("DMD_AV1_DUMP")); } + } + } + + /* 走既有的 scratch 机制:调用方在发送后 free。这与 H264/HEVC/VP8 + * 分支是同一套所有权约定(本函数头注释:scratch 由调用方提供并 + * 负责释放),不必新增字段。 */ + *scratch = buf; + *out_len = n; + return buf; + } + + case DMD_CODEC_VP8: { + size_t cap = c->slice_len + 16; + unsigned char *buf = malloc(cap); + if (!buf) + return NULL; + size_t n = vp8_build_frame(c, buf, cap); + if (n == 0) { + free(buf); + return NULL; + } + *scratch = buf; + *out_len = n; + return buf; + } + + case DMD_CODEC_H264: { + /* slice data 是**完整原始 NALU**(含 NAL header 与 slice header), + * 只缺起始码。已核实:h264dec.c:674 传 nal->raw_data/raw_size, + * h2645_parse.c:92/145 的 raw_data 指向起始码之后且保留转义字节, + * h2645_parse.c:448-456 从 gb 读 NAL header 反证 header 在 buffer 内, + * vaapi_h264.c:386-388 原样进 slice data buffer。 + * 所以这里只补 4 字节 00 00 00 01,不做任何 slice header 重建 —— + * 重排序与 MMCO 命令本来就还在原始字节里,MediaCodec 自己解析。 */ + size_t cap = c->slice_len + 4; + unsigned char *buf = malloc(cap); + if (!buf) + return NULL; + buf[0] = 0x00; + buf[1] = 0x00; + buf[2] = 0x00; + buf[3] = 0x01; + memcpy(buf + 4, c->slice_data, c->slice_len); + *scratch = buf; + *out_len = cap; + return buf; + } + + case DMD_CODEC_HEVC: { + /* 与 H.264 完全同构:VASliceParameterBufferHEVC 里有 + * slice_data_byte_offset,说明 slice header 原样在 buffer 里, + * 所以只需前置 4 字节起始码转发,不必重建 slice header + * (那要反推参考列表重排序,是欠定问题)。 */ + size_t cap = 4 + c->slice_len; + unsigned char *buf = malloc(cap); + if (!buf) + return NULL; + buf[0] = 0; buf[1] = 0; buf[2] = 0; buf[3] = 1; + memcpy(buf + 4, c->slice_data, c->slice_len); + *scratch = buf; + *out_len = cap; + return buf; + } + + default: + return NULL; + } +} + +/* HEVC:在首个 slice 之前把合成的 VPS/SPS/PPS 送给 daemon。 + * + * 与 H.264 的区别是三个参数集而非两个,且必须按 VPS→SPS→PPS 顺序 —— + * SPS 引用 VPS 的 id,PPS 引用 SPS 的 id。 + * 每个都作为独立数据单元发送(daemon 靠 nal_unit_header 识别并累积为 CSD)。 + * + * 调用方不得持锁(这里会做阻塞发送)。返回 0 成功。 */ +static int hevc_send_param_sets(struct dmd_session *sess, + const VAPictureParameterBufferHEVC *pp, + VAProfile profile) +{ + unsigned char nalu[600]; + + size_t n = dmd_hevc_build_vps_nalu(pp, profile, nalu, sizeof(nalu)); + if (n == 0) { + dmd_log("HEVC: VPS 合成失败\n"); + return -1; + } + if (dmd_session_send_unit(sess, nalu, n) != DMD_OK) { + dmd_log("HEVC: VPS 发送失败: %s\n", dmd_session_last_error(sess)); + return -1; + } + dmd_log("HEVC: 已送 VPS %zu 字节\n", n); + + n = dmd_hevc_build_sps_nalu(pp, profile, nalu, sizeof(nalu)); + if (n == 0) { + dmd_log("HEVC: SPS 合成失败\n"); + return -1; + } + if (dmd_session_send_unit(sess, nalu, n) != DMD_OK) { + dmd_log("HEVC: SPS 发送失败: %s\n", dmd_session_last_error(sess)); + return -1; + } + dmd_log("HEVC: 已送 SPS %zu 字节\n", n); + + n = dmd_hevc_build_pps_nalu(pp, nalu, sizeof(nalu)); + if (n == 0) { + dmd_log("HEVC: PPS 合成失败\n"); + return -1; + } + if (dmd_session_send_unit(sess, nalu, n) != DMD_OK) { + dmd_log("HEVC: PPS 发送失败: %s\n", dmd_session_last_error(sess)); + return -1; + } + dmd_log("HEVC: 已送 PPS %zu 字节\n", n); + + return 0; +} + +/* H.264:在首个 slice 之前把合成的 SPS/PPS 送给 daemon。 + * + * daemon 靠起始码定位 nal_unit_header 识别参数集并累积为 codec config + * (decode-daemon.c 的 input 线程),遇到第一个非参数集才以 + * FLAG_CODEC_CONFIG 送出。所以 SPS 与 PPS 必须**各自作为独立的数据单元** + * 先送,且必须在第一个 VCL NALU 之前。 + * + * 调用方不得持锁(这里会做阻塞发送)。返回 0 成功。 */ +static int h264_send_param_sets(struct dmd_session *sess, + const VAPictureParameterBufferH264 *pp, + const VAIQMatrixBufferH264 *iq, int have_iq, + const VASliceParameterBufferH264 *sp, + unsigned int def_l0, unsigned int def_l1, + VAProfile profile, unsigned int disp_width, + unsigned int disp_height) +{ + unsigned char nalu[512]; + + size_t n = dmd_h264_build_sps_nalu(pp, profile, disp_width, disp_height, + nalu, sizeof(nalu)); + if (n == 0) { + dmd_log("H.264: SPS 合成失败\n"); + return -1; + } + if (dmd_session_send_unit(sess, nalu, n) != DMD_OK) { + dmd_log("H.264: SPS 发送失败: %s\n", dmd_session_last_error(sess)); + return -1; + } + dmd_log("H.264: 已送 SPS %zu 字节\n", n); + + n = dmd_h264_build_pps_nalu(pp, iq, have_iq, sp, def_l0, def_l1, + nalu, sizeof(nalu)); + if (n == 0) { + dmd_log("H.264: PPS 合成失败\n"); + return -1; + } + if (dmd_session_send_unit(sess, nalu, n) != DMD_OK) { + dmd_log("H.264: PPS 发送失败: %s\n", dmd_session_last_error(sess)); + return -1; + } + dmd_log("H.264: 已送 PPS %zu 字节\n", n); + + return 0; +} + +VAStatus dmd_EndPicture(VADriverContextP ctx, VAContextID context) +{ + struct dmd_driver *drv = dmd_get_driver(ctx); + + if (!drv) + return VA_STATUS_ERROR_INVALID_PARAMETER; + + pthread_mutex_lock(&drv->lock); + struct dmd_context *c = dmd_find_context_locked(drv, context); + if (!c) { + pthread_mutex_unlock(&drv->lock); + return VA_STATUS_ERROR_INVALID_CONTEXT; + } + if (c->current_target == VA_INVALID_ID) { + pthread_mutex_unlock(&drv->lock); + return VA_STATUS_ERROR_INVALID_CONTEXT; + } + + VASurfaceID target = c->current_target; + int idx = (int)(c - drv->contexts); + + /* 组装码流(持锁做,纯内存操作)。 */ + unsigned char *scratch = NULL; + size_t unit_len = 0; + const unsigned char *unit = build_unit(c, &scratch, &unit_len); + + if (!unit) { + struct dmd_surface *s = dmd_find_surface_locked(drv, target); + if (s) { + s->state = DMD_SURFACE_IDLE; + s->decode_status = VA_STATUS_ERROR_UNIMPLEMENTED; + } + c->current_target = VA_INVALID_ID; + c->slice_len = 0; + c->av1_tile_count = 0; + int codec = c->codec; + pthread_mutex_unlock(&drv->lock); + free(scratch); + dmd_log("EndPicture: codec=%d 尚未支持码流重建,帧被丢弃\n", codec); + return VA_STATUS_ERROR_UNIMPLEMENTED; + } + + /* 会话写端已关(flush 过),但上游又送料了 —— 透明换一条新会话。 + * + * 这条路径覆盖的是 **seek**:daemon 没有连接内 reset,flush 又是不可逆的 + * shutdown(SHUT_WR),所以播放器跳转后要继续解码只能重建会话。 + * ⚠️ 曾据 tools/probe_rebuild.c 认为"从非 IDR 帧续传也能立刻出帧, + * 不会有可见花屏"—— 那个结论**是错的**(探针只数帧数没看画面, + * 那些帧全是纯黑 Y=16,探针开头已自我标注不可信)。 + * 实际上重建摧毁参考帧链,续传后要黑到下一个 IDR。 + * seek 场景下这个代价通常可接受(播放器跳转后本就期待画面刷新), + * 但**不要**把它当成"重建无害"的依据。 + * + * 注意:Firefox 的正常播放**不会**走到这里 —— 实测它一旦在 + * vaSyncSurface 上卡住就直接 DestroyContext,不再调 EndPicture。 + * 那个死锁是靠 DMD_FLUSH_AFTER_MS + DMD_PIPELINE_DEPTH 从根上避免的, + * 本路径只是 seek/异常场景的兜底,尚未被真实 seek 端到端验证过。 */ + if (c->session && c->input_finished) { + dmd_log("EndPicture: 会话写端已关闭但仍有新输入,重建会话\n"); + if (session_rebuild_locked(drv, c, idx) < 0) { + c = dmd_find_context_locked(drv, context); + if (!c) { + pthread_mutex_unlock(&drv->lock); + free(scratch); + return VA_STATUS_ERROR_INVALID_CONTEXT; + } + } else { + /* 重建期间放过锁,对象可能已被销毁,重新定位。 */ + c = dmd_find_context_locked(drv, context); + if (!c) { + pthread_mutex_unlock(&drv->lock); + free(scratch); + return VA_STATUS_ERROR_INVALID_CONTEXT; + } + } + } + + /* 会话惰性重试:CreateContext 时 daemon 可能还没起来。 */ + if (!c->session && !c->session_failed) { + /* 不可能:session_failed 与 session 互补。保守处理。 */ + c->session_failed = 1; + } + + struct dmd_session *sess = c->session; + int codec = c->codec; + unsigned int pw = c->picture_width; + unsigned int ph = c->picture_height; + + if (!sess) { + /* 放锁重试建会话,避免持锁做 connect。 */ + drv->io_busy[idx] = 1; + pthread_mutex_unlock(&drv->lock); + struct dmd_session *retry = session_open(codec, pw, ph); + pthread_mutex_lock(&drv->lock); + drv->io_busy[idx] = 0; + pthread_cond_broadcast(&drv->io_done); + c = dmd_find_context_locked(drv, context); + if (!c) { + pthread_mutex_unlock(&drv->lock); + if (retry) + dmd_session_destroy(retry); + free(scratch); + return VA_STATUS_ERROR_INVALID_CONTEXT; + } + if (!c->session) { + c->session = retry; + c->session_failed = retry ? 0 : 1; + } else if (retry) { + dmd_session_destroy(retry); /* 别的线程先建好了 */ + } + sess = c->session; + if (!sess) { + struct dmd_surface *s = dmd_find_surface_locked(drv, target); + if (s) { + s->state = DMD_SURFACE_IDLE; + s->decode_status = VA_STATUS_ERROR_OPERATION_FAILED; + } + c->current_target = VA_INVALID_ID; + c->slice_len = 0; + c->av1_tile_count = 0; + pthread_mutex_unlock(&drv->lock); + free(scratch); + return VA_STATUS_ERROR_OPERATION_FAILED; + } + } + + /* 入队:**在放锁发送之前**入队,保证队列顺序严格等于提交顺序。 + * 若发送失败再出队回滚。 */ + /* 队列满时收**一帧**腾出空位,而不是直接失败。 + * + * ⚠️ 这里曾直接返回 OPERATION_FAILED,那是 Chrome 硬解不可用的根因: + * + * Chrome 不像 ffmpeg / Firefox 那样调 vaSyncSurface 逐帧同步,而是 + * 大批提交后靠 vaExportSurfaceHandle 拿 dmabuf。于是队列很快填满, + * EndPicture 报错 → Chrome 收到 "operation failed" → 判定硬解不可用 + * → 断开连接(daemon 侧看到的 Broken pipe / Connection reset 是结果)。 + * + * 实测时间线可以确证:队列满那一刻 Chrome 立刻报 vaEndPicture failed, + * 而全部 50 次配对都发生在**失败之后的 DestroyContext 排空阶段** —— + * 也就是说帧在播放期间从没被及时消费,形成死锁: + * Chrome 等 surface 就绪 → 就绪需要收帧 → 收帧被队列满堵住。 + * + * 队列满是**背压**不是错误:帧还在路上,收回来就有空间。 + * + * ⚠️ 只收一帧,收够就走。曾试过在这里循环收光,那会替消费者把帧全 + * 收走(实测配对 1651 次而 Chrome 只导出 24 帧,帧率反跌到 1 fps)。 + * 也试过把队列放大到 256,只是把症状推后(送入 67 → 259)而未解决。 */ + if (c->pending_count >= DMD_MAX_SURFACES) { + struct dmd_session *bp_sess = c->session; + int bp_idx = (int)(c - drv->contexts); + + if (bp_sess && !drv->io_busy[bp_idx]) { + drv->io_busy[bp_idx] = 1; + pthread_mutex_unlock(&drv->lock); + + struct dmd_frame bp_frame; + memset(&bp_frame, 0, sizeof(bp_frame)); + int bp_rc = dmd_session_next_frame(bp_sess, &bp_frame, + DMD_BACKPRESSURE_MS); + + pthread_mutex_lock(&drv->lock); + drv->io_busy[bp_idx] = 0; + pthread_cond_broadcast(&drv->io_done); + + c = dmd_find_context_locked(drv, context); + if (!c) { + if (bp_rc == DMD_OK) + dmd_session_release_frame(bp_sess, &bp_frame); + pthread_mutex_unlock(&drv->lock); + free(scratch); + return VA_STATUS_ERROR_INVALID_CONTEXT; + } + + if (bp_rc == DMD_OK) { + VASurfaceID bp_head = dmd_pending_take_locked(c, + bp_frame.unit_seq); + struct dmd_surface *bp_hs = dmd_find_surface_locked(drv, + bp_head); + if (bp_hs) { + surface_store_frame_locked(bp_hs, &bp_frame); + bp_hs->state = DMD_SURFACE_READY; + } + dmd_session_release_frame(bp_sess, &bp_frame); + } + } + + if (c->pending_count >= DMD_MAX_SURFACES) { + pthread_mutex_unlock(&drv->lock); + free(scratch); + dmd_log("EndPicture: 待解码队列已满(%d),收帧后仍无空位\n", + DMD_MAX_SURFACES); + return VA_STATUS_ERROR_OPERATION_FAILED; + } + } + int qpos = (c->pending_head + c->pending_count) % DMD_MAX_SURFACES; + c->pending[qpos] = target; + /* 记下本帧 POC 供按显示序配对,并带上"序列号"。 + * + * ⚠️ POC 只在**同一个 coded video sequence 内**单调,每个 IDR 都会把它 + * 重置回起点。实测第 2 个 IDR 处 POC 从 65562 跳回 65536 —— 若只按 POC + * 全局取最小,新序列的帧会抢在旧序列未配对的帧之前,导致同一个 surface + * 被配对两次、画面从该 IDR 起错乱。 + * 所以先按 seq 再按 POC 排序:只有同序列内才比 POC 大小。 */ + if (c->have_current_poc) { + /* 判定是否进入新序列。 + * + * ⚠️ 不能用"POC 比上一帧小"来判断 —— 提交顺序是**解码序**, + * 同一个 GOP 内 POC 本来就上下起伏(实测 65536, 65544, 65540, 65538), + * 那样会把每个 B 帧都误判成新序列。 + * + * 用 frame_num:它在每个 IDR 处归零(H.264 规范 7.4.3), + * 而 GOP 内是递增的,所以"frame_num 归零且不是首帧"就是 IDR。 + * VA-API 在 VAPictureParameterBufferH264.frame_num 提供它(va.h:3618)。 */ + if (c->have_last_poc && c->current_frame_num == 0 && + c->last_frame_num != 0) + c->last_seq++; + c->last_poc = c->current_poc; + c->last_frame_num = c->current_frame_num; + c->have_last_poc = 1; + } + c->pending_seq[qpos] = c->last_seq; + c->pending_poc[qpos] = c->have_current_poc ? c->current_poc : INT32_MAX; + /* 发提交序号:daemon 会把它当 PTS 原样回传,配对时据此精确匹配。 + * 与 daemon 的 vcl_in 对齐 —— 两侧都从 1 开始、每个数据单元加 1。 + * 注意只有真正送出数据单元的提交才占号,参数集不占(daemon 侧同理: + * is_param_set 的单元走 CSD 路径,不递增 vcl_in)。 */ + c->pending_unit[qpos] = ++c->units_submitted; + c->pending_count++; + c->have_current_poc = 0; + c->current_target = VA_INVALID_ID; + + /* 拷一份码流到局部缓冲:放锁后 c->slice_data 可能被别的线程复用。 */ + unsigned char *tx = scratch; + if (!tx) { + tx = malloc(unit_len); + if (!tx) { + c->pending_count--; + pthread_mutex_unlock(&drv->lock); + return VA_STATUS_ERROR_ALLOCATION_FAILED; + } + memcpy(tx, unit, unit_len); + } + c->slice_len = 0; + c->av1_tile_count = 0; + + /* 串行化同 context 的 IO。 */ + while (drv->io_busy[idx]) { + struct timespec ts; + clock_gettime(CLOCK_REALTIME, &ts); + ts.tv_sec += DMD_FRAME_TIMEOUT_MS / 1000; + if (pthread_cond_timedwait(&drv->io_done, &drv->lock, &ts) == ETIMEDOUT) + break; + } + /* H.264:参数集必须在首个 VCL 之前送。先在持锁时快照所需数据, + * 放锁后再发(发送是阻塞 IO,不能持锁做)。 */ + int need_param_sets = 0; + VAPictureParameterBufferH264 pp_snap; + VAIQMatrixBufferH264 iq_snap; + VASliceParameterBufferH264 sp_snap; + int have_iq_snap = 0; + int have_sp_snap = 0; + VAProfile profile_snap = c->profile; + unsigned int mbs_wide = 0, mbs_high = 0; + VAPictureParameterBufferHEVC hevc_snap; + int need_hevc_params = 0; + /* 锁内快照:下面发送时已解锁,不能再读 c->pending_l0/l1。 */ + unsigned int l0_snap = 0, l1_snap = 0; + + if (codec == DMD_CODEC_H264 && c->have_h264_pic_param) { + mbs_wide = (unsigned int)c->h264_pic_param.picture_width_in_mbs_minus1 + 1; + mbs_high = (unsigned int)c->h264_pic_param.picture_height_in_mbs_minus1 + 1; + /* 重发条件:首次、流内几何变化、或 PPS 的 num_ref_idx 默认值变化。 + * + * 最后一条是必需的:PPS 默认值必须照抄**当前帧**的生效值 + * (详见 h264_bitstream.c 的说明),而不同帧的生效值会变。 + * MediaCodec 接受流中反复出现的 PPS,每次只多几字节。 */ + /* l0 取见过的**最大**、l1 取见过的**最小**。 + * + * VA-API 给的是每个 slice 的生效值,而带 override_flag 的 slice + * 其生效值与 PPS 默认值无关 —— 直接照抄会写出错误的默认值, + * 被其他非 override slice 用上就解出黑屏(详见 h264_bitstream.c + * 的实测记录:真实 PPS 恒为 l0=2 l1=0,而照抄会产生 5 种变体)。 + * + * l0 可以偏大、l1 一位都不能偏大(单变量实测),所以分别取 + * 最大与最小,几帧之内就收敛到唯一一份正确的 PPS。 */ + unsigned int l0_now = c->have_h264_slice_param + ? c->h264_slice_param.num_ref_idx_l0_active_minus1 + : 0; + unsigned int l1_now = c->have_h264_slice_param + ? c->h264_slice_param.num_ref_idx_l1_active_minus1 + : 0; + /* l0/l1 直接用 slice param 报的生效值。 + * + * ⚠️ 曾尝试"消除 PPS 振荡":改用 SPS 的 num_ref_frames-1 推导 l0、 + * 用观测最小值收敛 l1,让每个会话只送 1 份 PPS(685 次 → 1 次)。 + * 那是一次**回归**:long3000.h264 只解出 15/1323 帧后卡死在等帧超时。 + * + * 原因是重送次数本身在承担纠错作用 —— 正常版本对该流发出 4 种变体 + * 共 2735 次,其中包含真值 68ebe3cb22c0;收敛成单一份之后送出的是 + * 68e938f2c8b0,解码器再没有机会收到正确的那份。 + * + * 换句话说:振荡看着丑,但它覆盖了真值;固定成一份就赌错了。 + * 要真正消除振荡,得先能在**首个 slice 之前**确定真实的默认值, + * 而 VA-API 只给每个 slice 的生效值(override 的与默认值无关), + * 目前没有可靠推导途径。保持现状。 */ + unsigned int l0 = l0_now; + unsigned int l1 = l1_now; + if (!c->param_sets_sent || c->sent_mbs_wide != mbs_wide || + c->sent_mbs_high != mbs_high || c->sent_l0 != l0 || + c->sent_l1 != l1) { + c->pending_l0 = l0; + c->pending_l1 = l1; + l0_snap = l0; + l1_snap = l1; + need_param_sets = 1; + pp_snap = c->h264_pic_param; + iq_snap = c->h264_iq_matrix; + have_iq_snap = c->have_h264_iq_matrix; + sp_snap = c->h264_slice_param; + have_sp_snap = c->have_h264_slice_param; + } + } + + if (codec == DMD_CODEC_HEVC && c->hevc_pic_param_valid) { + /* 重发条件比 H.264 简单:HEVC 的 PPS 不含随帧变化的字段 + * (num_ref_idx 默认值在 PPS 里是真正的默认值,slice header 会覆盖), + * 所以只在首次与分辨率变化时重发。 */ + unsigned int w = c->hevc_pic_param.pic_width_in_luma_samples; + unsigned int h = c->hevc_pic_param.pic_height_in_luma_samples; + /* VA-API 缺少复现某些码流所需的信息(见 dmd_hevc_can_build)。 + * 这种情况必须失败,让上层回落软解 —— 合成一个不匹配的 SPS + * 会解出坏画面,比直接失败糟得多。 */ + if (!dmd_hevc_can_build(&c->hevc_pic_param)) { + dmd_log("HEVC: 该码流无法合成参数集" + "(num_short_term_ref_pic_sets=%u),拒绝\n", + c->hevc_pic_param.num_short_term_ref_pic_sets); + /* tx 在上面已分配(scratch 为空时 malloc),这条早退路径必须 + * 释放它 —— 否则每帧泄漏 unit_len 字节。函数正常路径在下面 + * 统一 free(tx),走不到这里。 + * + * 注意 tx 可能就是 scratch(所有权已转移给 tx),所以只 free + * 一次、不要另外 free(scratch)。 */ + free(tx); + c->pending_count--; + pthread_mutex_unlock(&drv->lock); + return VA_STATUS_ERROR_UNIMPLEMENTED; + } + if (!c->param_sets_sent || c->sent_mbs_wide != w || + c->sent_mbs_high != h) { + need_param_sets = 1; + need_hevc_params = 1; + hevc_snap = c->hevc_pic_param; + /* 借用这两个字段记分辨率(HEVC 无宏块概念,存的是像素) */ + mbs_wide = w; + mbs_high = h; + } + } + + drv->io_busy[idx] = 1; + pthread_mutex_unlock(&drv->lock); + + int rc = DMD_OK; + if (need_hevc_params) { + if (hevc_send_param_sets(sess, &hevc_snap, profile_snap) != 0) + rc = DMD_ERR_PROTOCOL; + } else if (need_param_sets) { + if (h264_send_param_sets(sess, &pp_snap, &iq_snap, have_iq_snap, + have_sp_snap ? &sp_snap : NULL, + l0_snap, l1_snap, profile_snap, + pw, ph) != 0) + rc = DMD_ERR_PROTOCOL; + } + if (rc == DMD_OK) + rc = dmd_session_send_unit(sess, tx, unit_len); + free(tx); + + pthread_mutex_lock(&drv->lock); + drv->io_busy[idx] = 0; + pthread_cond_broadcast(&drv->io_done); + + c = dmd_find_context_locked(drv, context); + if (!c) { + pthread_mutex_unlock(&drv->lock); + return VA_STATUS_ERROR_INVALID_CONTEXT; + } + + if (rc != DMD_OK) { + /* 回滚入队:这一帧永远不会有对应输出。从队尾摘掉。 */ + if (c->pending_count > 0) + c->pending_count--; + struct dmd_surface *s = dmd_find_surface_locked(drv, target); + if (s) { + s->state = DMD_SURFACE_IDLE; + s->decode_status = VA_STATUS_ERROR_DECODING_ERROR; + } + const char *msg = dmd_session_last_error(sess); + pthread_mutex_unlock(&drv->lock); + dmd_log("EndPicture: 送单元失败 rc=%d: %s\n", rc, msg); + return VA_STATUS_ERROR_DECODING_ERROR; + } + + if (need_param_sets) { + c->param_sets_sent = 1; + c->sent_mbs_wide = mbs_wide; + c->sent_mbs_high = mbs_high; + c->sent_l0 = c->pending_l0; + c->sent_l1 = c->pending_l1; + } + pthread_mutex_unlock(&drv->lock); + + return VA_STATUS_SUCCESS; +} + +/* ============================ 帧取回(Sync 路径) ============================ */ + +/* 把 daemon 回来的一帧拷进 surface 缓冲。调用方持锁。 + * + * 几何:daemon 的帧按 fmt.stride / fmt.slice_height 布局,UV 起点 = + * stride*slice_height。surface 按对齐尺寸预分配,两者通常一致; + * 不一致时(解码器给了不同对齐)按行拷贝,绝不整块 memcpy —— 那会错位。 + */ +/* 从待解码队列里取出"下一个该被填充"的 surface 并摘除它。 + * 队列空返回 VA_INVALID_ID。调用方持锁。 + * + * 谁该先填由 codec 决定: + * - VP9/VP8:无帧重排,提交序 == 出帧序,取队首 + * - H.264/HEVC:ffmpeg 按解码序提交、MediaCodec 按显示序出帧, + * 必须取 (seq, POC) 最小者,否则从第 2 帧起全部错位 + * + * 用线性扫描而非堆:队列最多 64 项且实测重排深度只有 2-3, + * 每帧一次 O(n) 扫描的代价可以忽略。 + */ +static VASurfaceID dmd_pending_take_locked(struct dmd_context *c, + uint32_t unit_seq) +{ + if (c->pending_count <= 0) + return VA_INVALID_ID; + + int pick = c->pending_head; + + /* 首选:按提交序号精确配对。 + * + * daemon 把每个输入单元的序号当 PTS 送给 MediaCodec,解码器原样回传到 + * 对应的输出帧上(tools/probe_negotiate.c 实测未被改写),于是这一帧 + * 究竟属于哪次提交是**已知事实**,不需要推断。 + * + * 这样配对就与解码器的出帧顺序完全解耦:显示序、跟随输入序、 + * 甚至将来换个平台换个顺序,都不影响正确性。此前靠 (seq,POC) 排序 + * 隐含假设了"输出是显示序",一旦假设不成立就画面错位而且不报错 + * (实测 105/150 帧错位)。 + * + * unit_seq == 0 表示 daemon 不支持该能力(旧版本),回退到下面的推断。 */ + if (unit_seq != 0) { + /* 观测到一次就记住:daemon 支持精确配对。这同时意味着它开了 + * 跟随输入序输出(两者在 daemon 里同一版本引入),滞后为 1, + * 于是不需要排空 —— wait_is_futile 用这个标志做判断。 */ + c->daemon_has_unit_seq = 1; + for (int k = 0; k < c->pending_count; k++) { + int idx = (c->pending_head + k) % DMD_MAX_SURFACES; + /* 序号 0 = 已作废(会话重建前的残留项),不参与精确匹配 */ + if (c->pending_unit[idx] != 0 && + c->pending_unit[idx] == (uint64_t)unit_seq) { + pick = idx; + goto found; + } + } + /* 没匹配上:多半是排空/重建导致 daemon 侧序号重新计数, + * 或收到了上一个会话的残留帧。退回顺序推断,不要丢帧。 */ + dmd_log("配对: unit_seq=%u 无匹配项,回退顺序推断(队列 %d)\n", + unit_seq, c->pending_count); + } + /* daemon 开了 vendor.qti-ext-dec-picture-order.enable 时解码器按**解码序** + * 输出,而 ffmpeg 也是按解码序提交的 —— 于是提交序 == 出帧序, + * 所有 codec 都退化成取队首,不需要 POC 重排。 + * + * 这么做的目的是根治黑帧:默认(显示序输出)下解码器有 B 帧时要收到 + * 第 4 个输入单元才吐首帧,而浏览器稳态只在飞 3 帧,双方互等, + * 只能靠 EOS 逼出帧 —— 而那会摧毁参考帧链,导致约 9 成帧纯黑 + * (tools/probe_black.c)。解码序输出把滞后降到 1,互等消失, + * 排空/重建/重放统统不再需要(tools/probe_keys.c 实测)。 */ + /* 回退路径:daemon 未提供 unit_seq(旧版本)时只能按 (seq, POC) 推断。 + * + * 这条路依赖"输出是显示序"这个假设,而假设是否成立取决于 daemon 的 + * 解码器配置 —— 驱动无法自行知道。这正是要用 unit_seq 精确配对的原因: + * 有它就不必猜。VP8/VP9 无帧重排,提交序 == 出帧序,取队首即可。 */ + if (c->codec == DMD_CODEC_H264 || c->codec == DMD_CODEC_HEVC) { + unsigned int bseq = c->pending_seq[pick]; + int32_t best = c->pending_poc[pick]; + for (int k = 1; k < c->pending_count; k++) { + int idx2 = (c->pending_head + k) % DMD_MAX_SURFACES; + /* 先比序列号:旧序列必须先配完,否则新序列(IDR 后 POC 重置回 + * 小值)会抢占旧序列尚未配对的帧。 */ + if (c->pending_seq[idx2] < bseq || + (c->pending_seq[idx2] == bseq && c->pending_poc[idx2] < best)) { + bseq = c->pending_seq[idx2]; + best = c->pending_poc[idx2]; + pick = idx2; + } + } + } + +found: + VASurfaceID head = c->pending[pick]; + dmd_log("配对: 帧 -> surface %u (unit %llu seq %u POC %d, 队列剩 %d)\n", + (unsigned)head, (unsigned long long)c->pending_unit[pick], + c->pending_seq[pick], (int)c->pending_poc[pick], + c->pending_count - 1); + + /* 摘除 pick:把它之前的项整体后移一格,再收缩队首。 + * + * ⚠️ 不能用"拿队首填补空位"的省事写法 —— 那会把队首元素挪到队列中间, + * **破坏剩余项与提交顺序的对应关系**,后续找最小 POC 时就会选错 + * (实测表现为部分帧对、部分帧错)。 */ + for (int k = pick; k != c->pending_head;) { + int prev = (k - 1 + DMD_MAX_SURFACES) % DMD_MAX_SURFACES; + c->pending[k] = c->pending[prev]; + c->pending_poc[k] = c->pending_poc[prev]; + c->pending_seq[k] = c->pending_seq[prev]; + /* pending_unit 必须一起搬。漏了它会让序号与 surface 错位, + * 同一个号被重复匹配 —— 实测 unit 5 与 unit 9 各出现两次、 + * 序号 2 和 6 凭空消失、70/150 帧错位。 */ + c->pending_unit[k] = c->pending_unit[prev]; + k = prev; + } + c->pending_head = (c->pending_head + 1) % DMD_MAX_SURFACES; + c->pending_count--; + return head; +} + +static void surface_store_frame_locked(struct dmd_surface *s, + const struct dmd_frame *f) +{ + /* 诊断:daemon 送来的帧本身是不是黑的? + * 与 export.c 里的同名探测配对使用,用来区分 + * "解码器就输出了黑帧" 和 "拷进 surface 后才变黑"。 + * DMD_VA_LUMA=1 才启用。 */ + if (getenv("DMD_VA_LUMA") && f->data && f->size > 100000) { + double sum = 0; int cnt = 0; + for (size_t k = 0; k < f->size && k < 2000000; k += 1499) { + sum += f->data[k]; cnt++; + } + double m = cnt ? sum / cnt : 0; + dmd_log("入帧亮度: unit=%u 均值 %.1f%s\n", + f->unit_seq, m, m < 20.0 ? " ← daemon 送来就是黑的!" : ""); + } + + unsigned int src_stride = f->stride > 0 ? (unsigned int)f->stride + : (unsigned int)f->width; + unsigned int src_slice = f->slice_height > 0 + ? (unsigned int)f->slice_height + : (unsigned int)f->height; + + /* 以解码器给的几何为准更新 surface:VAImage 的 offsets[1] 必须 + * 用 slice_height(1088)而不是显示高(1080),否则色度平面错位。 */ + s->stride = src_stride; + s->slice_height = src_slice; + s->buf_width = (unsigned int)f->width; + s->buf_height = (unsigned int)f->height; + + size_t need = (size_t)src_stride * src_slice * 3 / 2; + if (need > s->data_size) { + /* 解码器给的缓冲比预分配的大(流内分辨率变大)。扩容而不是截断。 */ + unsigned char *mem = realloc(s->data, need); + if (!mem) { + s->decode_status = VA_STATUS_ERROR_ALLOCATION_FAILED; + return; + } + s->data = mem; + s->data_size = need; + } + + size_t copy = f->size < need ? f->size : need; + memcpy(s->data, f->data, copy); + if (copy < need) + memset(s->data + copy, 0, need - copy); + + s->decode_status = VA_STATUS_SUCCESS; +} + +/* 从 daemon 取帧直到目标 surface 就绪或超时。 + * + * 这是 VA-API 乱序语义与 MediaCodec 流式语义的配对点。目标 surface 通常 + * 不在"该被填"的位置 —— 那就一直取,把该先填的填掉,直到轮到目标。 + * 谁该先填由 codec 决定:VP9/VP8 是队首,H.264/HEVC 是 (seq, POC) 最小者。 + */ +static VAStatus sync_surface_locked(struct dmd_driver *drv, VAContextID context, + VASurfaceID target, int timeout_ms) +{ + int idx; + struct dmd_context *c = dmd_find_context_locked(drv, context); + if (!c) + return VA_STATUS_ERROR_INVALID_CONTEXT; + idx = (int)(c - drv->contexts); + + int spent = 0; + /* 本次等待是否已经排空过一次。可逆排空不会改变队列深度, + * 不加这个闸就会在同一次等待里反复排空(忙循环)。 */ + int drained_once = 0; + /* 单次等待用较小的片,这样能周期性回到锁内检查状态。 */ + const int slice_ms = 100; + /* 等这么久还没帧就认为解码器在攥尾部帧,主动 flush。 + * + * ⚠️ 不能取 timeout_ms/2:调用方的超时不是"流是否结束"的证据。 + * Firefox 用很短的超时轮询 vaSyncSurface(还会在解码前先 DeriveImage + * 探一次),timeout_ms/2 于是变得极小 —— 才送 3 帧就误判成流结束、 + * 执行不可逆的 shutdown(SHUT_WR),会话作废,浏览器永久回落软解。 + * 命令行 ffmpeg 用大超时,所以从没暴露这个问题。 + * + * flush 是"上游不再送料"才该做的事,与单次等待的耐心无关, + * 因此这里用固定阈值,且必须显著大于解码器填满流水线所需的时间。 */ + const int flush_after_ms = DMD_FLUSH_AFTER_MS; + + for (;;) { + struct dmd_surface *s = dmd_find_surface_locked(drv, target); + if (!s) + return VA_STATUS_ERROR_INVALID_SURFACE; + if (s->state != DMD_SURFACE_PENDING) + return s->decode_status; + + c = dmd_find_context_locked(drv, context); + if (!c) + return VA_STATUS_ERROR_INVALID_CONTEXT; + if (!c->session) + return VA_STATUS_ERROR_OPERATION_FAILED; + if (c->pending_count <= 0) { + /* PENDING 但队列空:提交失败过。不能等,会永远等不到。 */ + s->state = DMD_SURFACE_IDLE; + return VA_STATUS_ERROR_DECODING_ERROR; + } + + /* 久等不到帧:解码器可能正攥着尾部帧等更多输入或 EOS。 + * + * MediaCodec 稳态滞后 2-3 个单元(实测送 1/2/3 个 VCL 后等 4000ms + * 都不出帧,第 4 个才出),所以流末尾最后几帧必须关掉写端才能取出来。 + * 而 ffmpeg 此刻正阻塞在 vaSyncSurface 上,不会再送新数据 —— 双方 + * 互等,只能由我们主动 flush 打破。 + * + * ⚠️ finish_input 是不可逆的 shutdown(SHUT_WR):一旦关闭,本会话 + * 再也不能送数据。所以只在"等了足够久、确实卡住"时才做,且只做一次。 + * + * flush 之后本会话即成一次性资源,但**不等于 context 报废**: + * 见下方 session_rebuild_locked —— 下一次 EndPicture 会透明重建 + * 会话并重送参数集,上层察觉不到。这对浏览器是必需的: + * 浏览器里 ffmpeg 稳态只保持 3 帧在飞,而 MediaCodec 有 B 帧时 + * 滞后 4 帧(实测 probe_lag:有 B 帧 4,无 B 帧 1),双方差一帧 + * 必然触发这里的 flush。若 flush 即报废,浏览器拿到 I/O error + * 后会永久回落软解(实测 Firefox 140 只硬解 1 帧就掉回软解)。 */ + /* 何时该 flush:判据是"再等下去也不可能有帧",不是"等够久了"。 + * + * 消费者送料深度低于解码器出帧所需深度时,双方必然互等: + * 消费者要先拿到帧才肯送下一个单元,解码器要再收一个单元才肯出帧。 + * 这时继续等是徒劳的 —— 队列深度不会自己变化。 + * + * 实测 Firefox 的循环正是这样:"送 3 帧 → 等第 1 帧",而 MediaCodec + * 有 B 帧时要第 4 个单元才出首帧(tools/probe_lag.c 量得;daemon 侧 + * 的 low-latency 也降不下来,那是解码器固有的流水线深度)。 + * 若按耐心阈值等满 2000ms 再 flush,每帧就要 2 秒,播放等于卡死; + * 立刻 flush 则马上出帧。 + * + * ⚠️ 这里曾写着"flush 的代价已由透明重建消掉,上层察觉不到 + * (probe_rebuild.c 验证过)"—— **那是错的**。那份探针只数帧数 + * 没看画面(帧全是纯黑 Y=16),它自己开头已标注结论不可信。 + * + * flush 的真实代价是**参考帧链被摧毁**,续传后要黑到下一个 IDR。 + * 上层不但察觉得到,用户会直接看到"画面一闪一闪" + * (实测 135/708 帧纯黑)。所以 flush 绝不是廉价操作。 + * + * 队列够深时仍按耐心阈值等 —— 那种情况下帧确实在路上, + * 提前 flush 会白白打断一个正常会话。 + * + * ⚠️ 可逆排空必须"每次等待只做一次"。它不像 finish_input 会置 + * input_finished 把自己挡住 —— 排空后队列深度不变,条件依旧成立, + * 不加闸就会变成忙循环(实测触发 133 万次、只出 1 帧)。 */ + /* 只有"再等也不可能出帧"时才排空 —— 排空会摧毁参考帧链,是黑帧根因。 + * + * daemon 支持 unit_seq 时同时也开了跟随输入序输出,滞后只有 1, + * 帧几乎立刻就来,永远不该判定徒劳(否则会 0 ms 就排空, + * 实测误触发 383 次)。旧 daemon 才有滞后 4 与消费者在飞 3 帧的互等。 + * + * ⚠️ `daemon_has_unit_seq` 是**收到第一帧才置位**的运行时观测, + * 所以会话刚建立、首帧还没回来时它必然为 0。若此时只看它, + * 就会在 0 ms 判定徒劳并立刻排空 —— 而排空 = EOS + flush, + * 参考帧链被毁,之后的 P/B 帧全黑到下一个 IDR。 + * + * 实测(浏览器循环播放 5 轮):每轮会话开头各触发 1 次 0 ms 排空, + * 共 5 次,与 5 段黑帧簇一一对应;每段黑 25~27 帧(unit 4..30, + * 恰好是首个 IDR 之后到下一个 IDR 之前),总计 135/708 帧纯黑。 + * 日志原文是"等了 0 ms 仍无帧,可逆排空(队列 3)"—— 队列明明是满的 + * (在飞 3 帧),帧就在路上,等一下就有,根本不该排空。 + * + * 所以再加一个条件:**至少收到过一帧**才允许判定徒劳。 + * 一帧都还没收到时,无法区分"互等"与"首帧还在路上", + * 此时应当耐心等到 flush_after_ms 阈值,而不是立刻毁掉会话状态。 */ + int wait_is_futile = dmd_session_frames_received(c->session) > 0 && + !c->daemon_has_unit_seq && + (c->pending_count < DMD_PIPELINE_DEPTH); + + if (!c->input_finished && !drained_once && + (wait_is_futile || spent >= flush_after_ms)) { + struct dmd_session *fs = c->session; + /* 优先用可逆排空:daemon 送 EOS 催出帧后 flush 复位并重送 CSD, + * 会话仍可用 —— 于是不必重建,省掉 connect+握手+configure。 + * 只有排空失败(老 daemon 不认长度 0)才退回不可逆的 finish_input。 */ + drv->io_busy[idx] = 1; + pthread_mutex_unlock(&drv->lock); + int frc = dmd_session_drain(fs); + int reversible = (frc == DMD_OK); + if (!reversible) + frc = dmd_session_finish_input(fs); + pthread_mutex_lock(&drv->lock); + drv->io_busy[idx] = 0; + pthread_cond_broadcast(&drv->io_done); + c = dmd_find_context_locked(drv, context); + if (!c) { + pthread_mutex_unlock(&drv->lock); + return VA_STATUS_ERROR_INVALID_CONTEXT; + } + if (reversible) + drained_once = 1; + else + c->input_finished = 1; + dmd_log("SyncSurface: 等了 %d ms 仍无帧,%s(rc=%d," + "阈值 %d ms,队列 %d)\n", + spent, reversible ? "可逆排空" : "flush 输入", + frc, flush_after_ms, c->pending_count); + /* 重新查找:放锁期间对象可能被销毁。 */ + continue; + } + + if (spent >= timeout_ms) { + dmd_log("SyncSurface: 等帧超时 %d ms(surface=%u 队列 %d)\n", + timeout_ms, (unsigned)target, c->pending_count); + return VA_STATUS_ERROR_TIMEDOUT; + } + + struct dmd_session *sess = c->session; + + /* 串行化 IO,然后放锁收帧。 */ + while (drv->io_busy[idx]) { + struct timespec ts; + clock_gettime(CLOCK_REALTIME, &ts); + ts.tv_nsec += 20 * 1000 * 1000; + if (ts.tv_nsec >= 1000000000L) { + ts.tv_sec++; + ts.tv_nsec -= 1000000000L; + } + pthread_cond_timedwait(&drv->io_done, &drv->lock, &ts); + spent += 20; + if (spent >= timeout_ms) + return VA_STATUS_ERROR_TIMEDOUT; + /* 别的线程可能已经把我们的帧填好了 */ + s = dmd_find_surface_locked(drv, target); + if (!s) + return VA_STATUS_ERROR_INVALID_SURFACE; + if (s->state != DMD_SURFACE_PENDING) + return s->decode_status; + } + drv->io_busy[idx] = 1; + pthread_mutex_unlock(&drv->lock); + + struct dmd_frame frame; + memset(&frame, 0, sizeof(frame)); + int rc = dmd_session_next_frame(sess, &frame, slice_ms); + + pthread_mutex_lock(&drv->lock); + drv->io_busy[idx] = 0; + pthread_cond_broadcast(&drv->io_done); + spent += slice_ms; + + c = dmd_find_context_locked(drv, context); + if (!c) { + if (rc == DMD_OK) + dmd_session_release_frame(sess, &frame); + return VA_STATUS_ERROR_INVALID_CONTEXT; + } + + if (rc == DMD_OK) { + VASurfaceID head = dmd_pending_take_locked(c, frame.unit_seq); + struct dmd_surface *hs = dmd_find_surface_locked(drv, head); + if (hs) { + surface_store_frame_locked(hs, &frame); + hs->state = DMD_SURFACE_READY; + } else { + dmd_log("SyncSurface: 待配对 surface %u 已销毁,帧被丢弃\n", + (unsigned)head); + } + /* release 不做阻塞 IO(TCP 模式只是标记缓冲可复用)。 */ + dmd_session_release_frame(sess, &frame); + continue; + } + + if (rc == DMD_ERR_TIMEOUT) { + /* 帧还没出来。daemon 未开 low-latency,解码器会攒几帧, + * 这是正常现象 —— 继续等到总超时。 */ + continue; + } + + if (rc == DMD_EOS) { + /* 流已结束但我们还在等帧:说明送入单元数与输出帧数不匹配。 */ + struct dmd_surface *s2 = dmd_find_surface_locked(drv, target); + if (s2 && s2->state == DMD_SURFACE_PENDING) { + s2->state = DMD_SURFACE_IDLE; + s2->decode_status = VA_STATUS_ERROR_DECODING_ERROR; + } + dmd_log("SyncSurface: 流已结束但仍有 %d 帧待配对\n", + c->pending_count); + return VA_STATUS_ERROR_DECODING_ERROR; + } + + /* 真错误 */ + dmd_log("SyncSurface: 取帧失败 rc=%d: %s\n", rc, + dmd_session_last_error(sess)); + struct dmd_surface *s3 = dmd_find_surface_locked(drv, target); + if (s3 && s3->state == DMD_SURFACE_PENDING) { + s3->state = DMD_SURFACE_IDLE; + s3->decode_status = VA_STATUS_ERROR_DECODING_ERROR; + } + return VA_STATUS_ERROR_DECODING_ERROR; + } +} + +/* 找到 surface 所属 context(用于 Sync)。调用方持锁。 */ +static VAContextID surface_context_locked(struct dmd_driver *drv, + VASurfaceID id) +{ + struct dmd_surface *s = dmd_find_surface_locked(drv, id); + return s ? s->context : VA_INVALID_ID; +} + +/* 供 image.c 做隐式同步:GetImage 时 surface 还没解出来就先等它。 + * 调用方持锁;本函数内部会临时放锁做 IO,返回时仍持锁, + * 因此调用方必须重新查找它缓存的对象指针。 */ +VAStatus dmd_surface_sync_locked(struct dmd_driver *drv, VASurfaceID surface, + int timeout_ms) +{ + struct dmd_surface *s = dmd_find_surface_locked(drv, surface); + if (!s) + return VA_STATUS_ERROR_INVALID_SURFACE; + if (s->state != DMD_SURFACE_PENDING) + return s->decode_status; + + VAContextID context = surface_context_locked(drv, surface); + if (context == VA_INVALID_ID) + return VA_STATUS_ERROR_INVALID_CONTEXT; + + return sync_surface_locked(drv, context, surface, timeout_ms); +} + +VAStatus dmd_SyncSurface(VADriverContextP ctx, VASurfaceID render_target) +{ + return dmd_SyncSurface2(ctx, render_target, + (uint64_t)DMD_FRAME_TIMEOUT_MS * 1000000ULL); +} + +VAStatus dmd_SyncSurface2(VADriverContextP ctx, VASurfaceID surface, + uint64_t timeout_ns) +{ + struct dmd_driver *drv = dmd_get_driver(ctx); + + if (!drv) + return VA_STATUS_ERROR_INVALID_PARAMETER; + + /* VA_TIMEOUT_INFINITE 也要给上限:driver 挂死会拖死宿主进程。 */ + int timeout_ms; + if (timeout_ns == VA_TIMEOUT_INFINITE || + timeout_ns / 1000000ULL > (uint64_t)DMD_FRAME_TIMEOUT_MS) + timeout_ms = DMD_FRAME_TIMEOUT_MS; + else + timeout_ms = (int)(timeout_ns / 1000000ULL); + if (timeout_ms <= 0) + timeout_ms = 1; + + pthread_mutex_lock(&drv->lock); + struct dmd_surface *s = dmd_find_surface_locked(drv, surface); + if (!s) { + pthread_mutex_unlock(&drv->lock); + return VA_STATUS_ERROR_INVALID_SURFACE; + } + if (s->state != DMD_SURFACE_PENDING) { + VAStatus st = s->decode_status; + pthread_mutex_unlock(&drv->lock); + return st; + } + VAContextID context = surface_context_locked(drv, surface); + if (context == VA_INVALID_ID) { + pthread_mutex_unlock(&drv->lock); + return VA_STATUS_ERROR_INVALID_CONTEXT; + } + + struct dmd_context *sc = dmd_find_context_locked(drv, context); + int c_pending = sc ? sc->pending_count : 0; + + /* 放行是有额度的:只在"在飞帧数还不足以喂饱解码器流水线"时才放行。 + * + * 无条件放行会把死锁换成队列无界增长 —— 实测 pending 一路涨到 + * DMD_MAX_SURFACES 溢出,ffmpeg 报 "Failed to end picture decode + * issue: 23"。因为消费者是"能送就送"的:不挡它,它就一直送, + * 而取像素(DeriveImage)要等到它自己攒够帧才做。 + * + * 所以额度取实测的滞后深度 DMD_PIPELINE_DEPTH: + * 在飞帧数低于它时放行(让流水线填满,这是打破死锁的必要条件), + * 达到之后就老实阻塞等帧 —— 此刻解码器已经不欠料,等得到, + * 于是队列被排空,形成稳定的背压。 */ + dmd_log("Sync: surface=%u pending=%d timeout=%dms %s\n", + (unsigned)surface, c_pending, timeout_ms, + c_pending >= DMD_PIPELINE_DEPTH ? "阻塞等帧" : "放行"); + + if (c_pending >= DMD_PIPELINE_DEPTH) { + VAStatus st = sync_surface_locked(drv, context, surface, timeout_ms); + pthread_mutex_unlock(&drv->lock); + return st; + } + + /* ⚠️ 这里**不能**一直等到帧真的到手,否则与 MediaCodec 的流水线深度死锁。 + * + * 实测的时序矛盾(probe_lag 直连 daemon 量得,与驱动无关): + * MediaCodec 有 B 帧时滞后 4 个输入单元才吐首帧(无 B 帧时滞后 1) + * 而浏览器里的 ffmpeg 稳态只保持 3 帧在飞(H.264 重排深度决定), + * 送完第 3 帧就阻塞在 vaSyncSurface 等第 1 帧。 + * 双方差正好一帧:谁都不动 → 我们的兜底 flush 触发(不可逆 + * shutdown(SHUT_WR))→ 会话作废 → 浏览器拿到 I/O error 后永久回落软解。 + * 实测 Firefox 140 因此只硬解出 1 帧,EndPicture 只被调用 3 次 + * 就直接 DestroyContext。 + * + * 已否决的两条路(都实测过): + * · daemon 开 low-latency:滞后仍是 4,无效(改动已保留,对交互有价值) + * · 合成 SPS 里写 max_num_reorder_frames:真实码流的 SPS 本来就带 VUI, + * 滞后照旧 4 —— 说明这是高通解码器固有的流水线深度,signal 不掉。 + * + * 所以阻塞点必须挪走:VA-API 允许像素在 map 时才真正就绪 + * (消费者取像素走 DeriveImage + MapBuffer,实测 Firefox/ffmpeg 都如此)。 + * 这里只做"短暂尝试",没到就报成功放 ffmpeg 走 —— 它于是提交第 4 帧, + * 正好把 MediaCodec 的流水线推过阈值,帧随即流出。 + * 真正的等待落在 MapBuffer/DeriveImage(见 image.c 的 dmd_surface_wait)。 */ + const int probe_ms = 30; + VAStatus status = sync_surface_locked(drv, context, surface, + timeout_ms < probe_ms ? timeout_ms + : probe_ms); + if (status == VA_STATUS_ERROR_TIMEDOUT) { + /* 帧还在解码器里排队,这不是错误。报成功让上游继续送料, + * 像素在 map 时保证就绪。 */ + status = VA_STATUS_SUCCESS; + } + pthread_mutex_unlock(&drv->lock); + + return status; +} + +/* 等到 surface 的像素真的就绪。供 image.c 在 map 前调用。 + * + * 这是 SyncSurface 让路之后真正的阻塞点:此刻消费者已经把后续帧送进去了, + * MediaCodec 的流水线不再欠料,所以这里等得到。 */ +VAStatus dmd_surface_wait(struct dmd_driver *drv, VASurfaceID surface) +{ + pthread_mutex_lock(&drv->lock); + struct dmd_surface *s = dmd_find_surface_locked(drv, surface); + if (!s) { + pthread_mutex_unlock(&drv->lock); + return VA_STATUS_ERROR_INVALID_SURFACE; + } + if (s->state != DMD_SURFACE_PENDING) { + VAStatus st = s->decode_status; + pthread_mutex_unlock(&drv->lock); + return st; + } + VAContextID context = surface_context_locked(drv, surface); + if (context == VA_INVALID_ID) { + pthread_mutex_unlock(&drv->lock); + return VA_STATUS_ERROR_INVALID_CONTEXT; + } + VAStatus status = sync_surface_locked(drv, context, surface, + DMD_FRAME_TIMEOUT_MS); + pthread_mutex_unlock(&drv->lock); + return status; +} + +VAStatus dmd_QuerySurfaceStatus(VADriverContextP ctx, + VASurfaceID render_target, + VASurfaceStatus *status) +{ + struct dmd_driver *drv = dmd_get_driver(ctx); + + if (!drv || !status) + return VA_STATUS_ERROR_INVALID_PARAMETER; + + pthread_mutex_lock(&drv->lock); + struct dmd_surface *s = dmd_find_surface_locked(drv, render_target); + if (!s) { + pthread_mutex_unlock(&drv->lock); + return VA_STATUS_ERROR_INVALID_SURFACE; + } + /* 不在这里做 IO:QuerySurfaceStatus 的语义是"立即返回当前状态", + * 阻塞取帧是 SyncSurface 的活。 */ + *status = (s->state == DMD_SURFACE_PENDING) ? VASurfaceRendering + : VASurfaceReady; + pthread_mutex_unlock(&drv->lock); + + return VA_STATUS_SUCCESS; +} diff --git a/codec/vaapi/src/dmd_client.c b/codec/vaapi/src/dmd_client.c new file mode 100644 index 0000000..cbee987 --- /dev/null +++ b/codec/vaapi/src/dmd_client.c @@ -0,0 +1,1168 @@ +/* + * dmd_client.c - decode-daemon 客户端库实现 + * + * 设计要点见 dmd_client.h 的头注释。这里只记录实现层面的决策: + * + * 1) 全部 fd 非阻塞 + poll:宿主是浏览器,任何无上限阻塞都等于挂死整个进程。 + * connect 也走非阻塞 + POLLOUT + SO_ERROR 取结果。 + * 2) recv/send 一律循环到收满/发满,处理 EINTR 与短读短写;send 带 MSG_NOSIGNAL。 + * 3) SHM 只是意向:daemon 在 memfd 交接**之前**就发出握手响应 + * (decode-daemon.c:404 发响应,:409 才 shm_handoff),交接超时 3 秒后 + * daemon 静默退回 TCP 帧格式。因此这里领取失败不算错误,只降级, + * 继续按 TCP 帧格式解析 —— 这是必须自带的 fallback。 + * 4) 错误传递:所有失败路径都经 set_err() 记录 code + 可读原因(含 strerror), + * 调用方用 dmd_session_last_error() 取。永不 exit/abort/assert。 + * 5) 无全局可变状态:日志开关也存在会话里(每个会话各自读一次环境变量)。 + * 唯一的全局是 const 字符串字面量。 + */ +#ifndef _GNU_SOURCE +#define _GNU_SOURCE /* MSG_CMSG_CLOEXEC / SOCK_CLOEXEC;Makefile 已传,此处兜底 */ +#endif +#include "dmd_client.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +/* ---- 协议常量,必须与 src/decode-daemon.c 保持一致 ---- */ +#define DMD_HELLO_MAGIC 0x444D4400u +#define DMD_HELLO_VERSION 3u /* v3: 响应可携带 endpoint dev/ino 扩展 */ +#define DMD_FMTDESC_SENTINEL 0xFFFFFFFFu +/* 格式描述块头部第 2 个字的能力标志(旧 daemon 恒为 0)。 + * CAP_FRAME_PTS:帧头带额外的 PTS 字段 = 该帧对应的输入单元序号, + * 驱动用它精确配对 surface,无需知道解码器的出帧顺序。 */ +#define DMD_CAP_FRAME_PTS 0x00000001u +#define DMD_SHMFRAME_SENTINEL 0xFFFFFFFEu +#define DMD_FMTDESC_WORDS 8 +#define DMD_SHM_CTRL_BYTES 4096 +#define DMD_DEFAULT_PORT 20003 + +#define DMD_DEF_CONNECT_MS 2000 +#define DMD_DEF_IO_MS 5000 +/* 领取 memfd 的窗口。daemon 那边 select 等 3 秒(decode-daemon.c:606), + * 这里取 1.5 秒:要在 daemon 放弃之前就完成或放弃,避免两边认知不一致。 */ +#define DMD_SHM_ATTACH_MS 1500 + +struct dmd_session { + int fd; /* daemon TCP 连接,非阻塞 */ + int log; /* 日志开关,来自 DMD_VA_LOG */ + + int codec; + int io_timeout_ms; + + char ep_path[108]; /* 路径式 unix 模式下记录 connect 所用路径, + * 握手后对它 stat 与 daemon 上报的 dev/ino 对账。 + * TCP / 抽象命名空间模式为空串。 */ + + int xfer; /* 实际生效的传输模式 */ + int input_finished; /* 已 shutdown(SHUT_WR) */ + int eos; /* 读到对端关闭 */ + int tx_broken; /* 上行流已损坏(发送中途超时,写出了半个单元) */ + + struct dmd_format fmt; + struct dmd_error err; + + /* TCP 模式的接收缓冲(复用,按需增长) */ + uint8_t *rbuf; + size_t rbuf_size; + int rbuf_busy; /* 1 = 有一帧未 release,正指向 rbuf */ + + /* SHM 池 */ + uint8_t *shm_base; + size_t shm_slot_bytes; + size_t shm_total; + int shm_slots; + int shm_held; /* 当前未归还的槽位数,用于诊断 */ + + uint64_t units_sent; + uint64_t frames_recv; + uint64_t drains_sent; /* 发出的可逆排空请求数(诊断用) */ + uint32_t caps; /* daemon 能力位(来自格式描述块,0 = 旧 daemon) */ + uint32_t last_pts; /* 最近一帧的输入单元序号,0 = 不可用 */ +}; + +/* ------------------------------------------------------------ 日志 */ +/* + * 默认静默,DMD_VA_LOG=1 打开,只写 stderr。 + * driver 里有同名机制,但这里刻意自带一份:库不依赖 driver 的符号, + * 才能被测试程序单独链接。 + */ +static void dmd_c_log(const struct dmd_session *s, const char *fmt, ...) + __attribute__((format(printf, 2, 3))); + +static void dmd_c_log(const struct dmd_session *s, const char *fmt, ...) +{ + if (!s || !s->log) + return; + va_list ap; + va_start(ap, fmt); + fputs("[dmd-client] ", stderr); + vfprintf(stderr, fmt, ap); + fputc('\n', stderr); + va_end(ap); +} + +static int dmd_log_wanted(void) +{ + const char *env = getenv("DMD_VA_LOG"); + return (env && env[0] == '1') ? 1 : 0; +} + +/* ------------------------------------------------------------ 错误记录 */ +static void err_set(struct dmd_error *e, int code, int hs_status, + const char *what, int use_errno) +{ + if (!e) + return; + e->code = code; + e->handshake_status = hs_status; + if (use_errno) { + int sv = errno; + snprintf(e->msg, sizeof(e->msg), "%s: %s", what, strerror(sv)); + errno = sv; + } else { + snprintf(e->msg, sizeof(e->msg), "%s", what); + } +} + +/* 记录到会话,并把同一份内容抄给可选的外部 err 出参 */ +static int sess_err(struct dmd_session *s, int code, const char *what, + int use_errno) +{ + err_set(&s->err, code, 0, what, use_errno); + if (s->log) + dmd_c_log(s, "错误(%d): %s", code, s->err.msg); + return code; +} + +/* ------------------------------------------------------------ fd 工具 */ +/* 所有 socket 都用 SOCK_CLOEXEC | SOCK_NONBLOCK 一次创建好, + * 不留 fcntl 补设的窗口(fork 竞态会泄漏 fd 给宿主进程的子进程)。 */ + +/* 等 fd 可读/可写。返回 1 就绪,0 超时,-1 出错(errno 有效)。 + * timeout_ms < 0 视为 0(不等待)以避免无限阻塞 —— 库里没有无限等待。 */ +static int wait_fd(int fd, short events, int timeout_ms) +{ + if (timeout_ms < 0) + timeout_ms = 0; + struct pollfd p; + p.fd = fd; + p.events = events; + for (;;) { + p.revents = 0; + int r = poll(&p, 1, timeout_ms); + if (r < 0) { + if (errno == EINTR) + continue; /* 简化:EINTR 时按原超时重试,最坏情况延长等待 */ + return -1; + } + if (r == 0) + return 0; + return 1; + } +} + +/* + * 循环收满 len 字节。 + * first_timeout_ms:等第一个字节的超时(可以很短,用于"有没有帧"的探测) + * rest_timeout_ms: 收到首字节之后每次等待的超时(不能太短,否则留半帧) + * 返回 DMD_OK / DMD_EOS(一个字节都没读到就对端关闭)/ DMD_ERR_*。 + * 帧中途对端关闭算 DMD_ERR_PROTOCOL:那是被截断的消息,不是干净的流结束。 + */ +static int recv_exact(struct dmd_session *s, void *buf, size_t len, + int first_timeout_ms, int rest_timeout_ms) +{ + uint8_t *p = buf; + size_t got = 0; + + while (got < len) { + int to = (got == 0) ? first_timeout_ms : rest_timeout_ms; + int r = wait_fd(s->fd, POLLIN, to); + if (r < 0) + return sess_err(s, DMD_ERR_IO, "poll 等待可读失败", 1); + if (r == 0) { + if (got == 0) + return DMD_ERR_TIMEOUT; /* 干净的"暂时没数据",不污染 last_error */ + return sess_err(s, DMD_ERR_TIMEOUT, "消息中途接收超时", 0); + } + + ssize_t n = recv(s->fd, p + got, len - got, 0); + if (n < 0) { + if (errno == EINTR || errno == EAGAIN || errno == EWOULDBLOCK) + continue; + return sess_err(s, DMD_ERR_IO, "recv 失败", 1); + } + if (n == 0) { + if (got == 0) { + s->eos = 1; + return DMD_EOS; + } + return sess_err(s, DMD_ERR_PROTOCOL, + "对端在消息中途关闭连接(消息被截断)", 0); + } + got += (size_t)n; + } + return DMD_OK; +} + +/* 循环发满 len 字节,MSG_NOSIGNAL 防 SIGPIPE 杀宿主进程 */ +static int send_exact(struct dmd_session *s, const void *buf, size_t len, + int timeout_ms) +{ + const uint8_t *p = buf; + size_t sent = 0; + + while (sent < len) { + ssize_t n = send(s->fd, p + sent, len - sent, MSG_NOSIGNAL); + if (n < 0) { + if (errno == EINTR) + continue; + if (errno == EAGAIN || errno == EWOULDBLOCK) { + int r = wait_fd(s->fd, POLLOUT, timeout_ms); + if (r < 0) + return sess_err(s, DMD_ERR_IO, "poll 等待可写失败", 1); + if (r == 0) + return sess_err(s, DMD_ERR_TIMEOUT, "发送超时", 0); + continue; + } + if (errno == EPIPE || errno == ECONNRESET) + return sess_err(s, DMD_ERR_IO, "连接已被 daemon 关闭", 1); + return sess_err(s, DMD_ERR_IO, "send 失败", 1); + } + sent += (size_t)n; + } + return DMD_OK; +} + +/* ------------------------------------------------------------ 共享内存 */ +static volatile uint32_t *shm_state_word(struct dmd_session *s, int idx) +{ + return (volatile uint32_t *)(s->shm_base + (size_t)idx * sizeof(uint32_t)); +} + +/* + * 连 daemon 指定的 abstract socket,用 SCM_RIGHTS 领 memfd 并 mmap。 + * 失败返回 -1(调用方降级为 TCP,不是致命错误)。 + * + * abstract socket 地址构造:sun_path[0] = 0,名字从 sun_path+1 起, + * addrlen = offsetof(sun_path) + 1 + strlen(name)(不含结尾 NUL)—— + * 与 daemon 的 bind 完全对称(decode-daemon.c:574-580)。 + */ +static int shm_attach(struct dmd_session *s, const char *name) +{ + int sock = socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0); + if (sock < 0) { + dmd_c_log(s, "abstract socket 创建失败: %s", strerror(errno)); + return -1; + } + + struct sockaddr_un ua; + memset(&ua, 0, sizeof(ua)); + ua.sun_family = AF_UNIX; + size_t nl = strlen(name); + if (nl > sizeof(ua.sun_path) - 2) { + dmd_c_log(s, "共享内存名字过长: %zu", nl); + close(sock); + return -1; + } + ua.sun_path[0] = 0; + memcpy(ua.sun_path + 1, name, nl); + socklen_t ulen = (socklen_t)(offsetof(struct sockaddr_un, sun_path) + 1 + nl); + + if (connect(sock, (struct sockaddr *)&ua, ulen) < 0) { + if (errno != EINPROGRESS) { + dmd_c_log(s, "连接 @%s 失败: %s", name, strerror(errno)); + close(sock); + return -1; + } + if (wait_fd(sock, POLLOUT, DMD_SHM_ATTACH_MS) != 1) { + dmd_c_log(s, "连接 @%s 超时", name); + close(sock); + return -1; + } + int se = 0; + socklen_t sl = sizeof(se); + if (getsockopt(sock, SOL_SOCKET, SO_ERROR, &se, &sl) < 0 || se != 0) { + dmd_c_log(s, "连接 @%s 失败: %s", name, strerror(se ? se : errno)); + close(sock); + return -1; + } + } + + /* 12 字节 [槽位数][单槽字节数][池总字节数] + SCM_RIGHTS 里的 memfd。 + * daemon 一次 sendmsg 发出,辅助数据不会跨消息拆分, + * 但仍要等它可读(非阻塞 fd 下 recvmsg 可能先 EAGAIN)。 */ + uint32_t meta[3]; + struct iovec io; + io.iov_base = meta; + io.iov_len = sizeof(meta); + char cbuf[CMSG_SPACE(sizeof(int))]; + struct msghdr mh; + ssize_t n; + + for (;;) { + if (wait_fd(sock, POLLIN, DMD_SHM_ATTACH_MS) != 1) { + dmd_c_log(s, "等待 memfd 超时"); + close(sock); + return -1; + } + memset(cbuf, 0, sizeof(cbuf)); + memset(&mh, 0, sizeof(mh)); + mh.msg_iov = &io; + mh.msg_iovlen = 1; + mh.msg_control = cbuf; + mh.msg_controllen = sizeof(cbuf); + n = recvmsg(sock, &mh, MSG_CMSG_CLOEXEC); + if (n < 0 && (errno == EINTR || errno == EAGAIN || errno == EWOULDBLOCK)) + continue; + break; + } + + if (n != (ssize_t)sizeof(meta)) { + dmd_c_log(s, "领取共享内存参数失败: n=%zd (%s)", n, + n < 0 ? strerror(errno) : "长度不符"); + close(sock); + return -1; + } + + int mfd = -1; + for (struct cmsghdr *cm = CMSG_FIRSTHDR(&mh); cm; cm = CMSG_NXTHDR(&mh, cm)) { + if (cm->cmsg_level == SOL_SOCKET && cm->cmsg_type == SCM_RIGHTS && + cm->cmsg_len == CMSG_LEN(sizeof(int))) { + memcpy(&mfd, CMSG_DATA(cm), sizeof(int)); + break; + } + } + close(sock); + if (mfd < 0) { + dmd_c_log(s, "响应里没有 memfd"); + return -1; + } + + int slots = (int)ntohl(meta[0]); + size_t slot_sz = (size_t)ntohl(meta[1]); + size_t total = (size_t)ntohl(meta[2]); + + /* 自校验:布局必须自洽,否则宁可降级也不要按错误偏移读共享内存 */ + if (slots <= 0 || slots > 64 || slot_sz == 0 || + total < DMD_SHM_CTRL_BYTES + slot_sz * (size_t)slots || + (size_t)slots * sizeof(uint32_t) > DMD_SHM_CTRL_BYTES) { + dmd_c_log(s, "共享内存参数不自洽: slots=%d slot=%zu total=%zu", + slots, slot_sz, total); + close(mfd); + return -1; + } + + void *base = mmap(NULL, total, PROT_READ | PROT_WRITE, MAP_SHARED, mfd, 0); + close(mfd); /* mmap 之后 fd 不再需要,不泄漏给宿主 */ + if (base == MAP_FAILED) { + dmd_c_log(s, "mmap 共享内存失败: %s", strerror(errno)); + return -1; + } + + s->shm_base = base; + s->shm_slots = slots; + s->shm_slot_bytes = slot_sz; + s->shm_total = total; + dmd_c_log(s, "共享内存已挂载: %d 槽 x %zu 字节 (共 %zu)", slots, slot_sz, total); + return 0; +} + +/* ------------------------------------------------------------ 连接与握手 */ +/* 非阻塞 connect + 带上界的等待。TCP 与 Unix socket 两条路共用, + * 差别只在地址结构 —— 超时、SO_ERROR 检查、错误分类都是同一套。 */ +static int sock_connect_wait(int fd, const struct sockaddr *sa, socklen_t slen, + const char *what, int timeout_ms, + struct dmd_error *err) +{ + if (connect(fd, sa, slen) < 0) { + if (errno != EINPROGRESS) { + char m[96]; + snprintf(m, sizeof(m), "connect %s 失败", what); + err_set(err, DMD_ERR_CONNECT, 0, m, 1); + close(fd); + return -1; + } + int r = wait_fd(fd, POLLOUT, timeout_ms); + if (r < 0) { + err_set(err, DMD_ERR_CONNECT, 0, "poll 等待 connect 失败", 1); + close(fd); + return -1; + } + if (r == 0) { + err_set(err, DMD_ERR_TIMEOUT, 0, "connect 超时", 0); + close(fd); + return -1; + } + int se = 0; + socklen_t sl = sizeof(se); + if (getsockopt(fd, SOL_SOCKET, SO_ERROR, &se, &sl) < 0) { + err_set(err, DMD_ERR_CONNECT, 0, "getsockopt(SO_ERROR) 失败", 1); + close(fd); + return -1; + } + if (se != 0) { + errno = se; + err_set(err, DMD_ERR_CONNECT, 0, "connect 被拒绝", 1); + close(fd); + return -1; + } + } + return 0; +} + +/* 连 TCP 127.0.0.1:port。依赖容器与 Android 共享 net namespace —— + * DroidSpaces 的 host 型容器满足,NAT 型容器不满足。 */ +static int tcp_connect(struct dmd_session *s, uint16_t port, int timeout_ms, + struct dmd_error *err) +{ + int fd = socket(AF_INET, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0); + if (fd < 0) { + err_set(err, DMD_ERR_CONNECT, 0, "创建 TCP socket 失败", 1); + return -1; + } + + struct sockaddr_in a; + memset(&a, 0, sizeof(a)); + a.sin_family = AF_INET; + a.sin_addr.s_addr = htonl(INADDR_LOOPBACK); + a.sin_port = htons(port); + + if (sock_connect_wait(fd, (struct sockaddr *)&a, sizeof(a), + "127.0.0.1", timeout_ms, err) < 0) + return -1; + + /* 帧交付要低延迟;失败不致命,忽略返回值 */ + int one = 1; + (void)setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &one, sizeof(one)); + s->fd = fd; + return 0; +} + +/* 连路径式 Unix socket。 + * + * 相比 TCP 与 abstract socket,这条路的关键优势是**不依赖 net namespace**: + * 平台把宿主上的 socket 文件 bind mount 进容器即可, + * 所以 host 型与 NAT 型容器都能用(实测 NAT 容器 netns 独立, + * 127.0.0.1 与 abstract socket 都不可达,只有这条通)。 + * + * DroidSpaces 自己的显示通道就是这个模式: + * 宿主 /data/local/tmp/anland-.sock → 容器 /run/display.sock + * (实测两侧 inode 相同,确认是同一文件)。 + * + * 鉴权直接靠文件权限 + SELinux,不必把服务暴露到网络。 + * TCP_NODELAY 不适用于 AF_UNIX,故此处不设。 */ +static int unix_connect(struct dmd_session *s, const char *path, + int timeout_ms, struct dmd_error *err) +{ + int fd = socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0); + if (fd < 0) { + err_set(err, DMD_ERR_CONNECT, 0, "创建 Unix socket 失败", 1); + return -1; + } + + struct sockaddr_un ua; + memset(&ua, 0, sizeof(ua)); + ua.sun_family = AF_UNIX; + if (strlen(path) >= sizeof(ua.sun_path)) { + err_set(err, DMD_ERR_CONNECT, 0, "socket 路径过长", 0); + close(fd); + return -1; + } + memcpy(ua.sun_path, path, strlen(path)); + + if (sock_connect_wait(fd, (struct sockaddr *)&ua, sizeof(ua), + path, timeout_ms, err) < 0) + return -1; + + /* 接收缓冲必须显式放大 —— 这是 Unix 端点能否实时解码的关键。 + * + * AF_UNIX 默认 SO_RCVBUF 只有 229376 (224KB),而一帧 NV12 是 + * 1.38MB(720p) / 3.11MB(1080p)。缓冲装不下整帧时,daemon 的 send_all + * 会反复阻塞等本端取走,往返次数远高于 TCP(其默认 SO_RCVBUF 有 1MB): + * 实测吞吐从 8.6x 塌到 0.92x,且 daemon 侧因输出线程被堵而报 + * "输入缓冲暂满"最终放弃会话。服务端也设了 4MB —— 两端一起放大才有效。 + * + * 受 net.core.rmem_max 截断,设不到就退化为原状,失败不致命。 */ + { + int bufsz = 4 * 1024 * 1024; + (void)setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &bufsz, sizeof(bufsz)); + (void)setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &bufsz, sizeof(bufsz)); + } + + /* 记录端点路径供握手后做 inode 对账(见 do_handshake) */ + snprintf(s->ep_path, sizeof(s->ep_path), "%s", path); + s->fd = fd; + return 0; +} + +/* + * 握手。请求固定 24 字节: + * [4B 魔数][4B 版本][4B codec][4B 宽][4B 高][4B 传输模式] + * 全部大端。daemon 先读 4 字节魔数,再一次读余下 20 字节, + * 所以必须一次写满 24 字节。本客户端发 version=3。 + * + * 响应至少 12 字节:[4B status][4B 实际模式][4B 名字长度 n]。 + * v3(daemon>=v0.3.x 配套版本)在 status==0 时把 bit31 置入"名字长度"字段, + * 并在其后、名字之前追加 16 字节 endpoint 扩展(dev/ino 各拆高低 u32); + * 客户端对 connect 路径 stat 对账,不一致返回 DMD_ERR_ENDPOINT_MISMATCH。 + * 旧 daemon 回裸 12 字节 → 跳过校验(一次性 WARN)。错误路径同样是裸 12 字节。 + */ +static int do_handshake(struct dmd_session *s, + const struct dmd_session_config *cfg, + uint32_t use_version, + struct dmd_error *err) +{ + uint32_t hello[6]; + hello[0] = htonl(DMD_HELLO_MAGIC); + hello[1] = htonl(use_version); + hello[2] = htonl((uint32_t)cfg->codec); + hello[3] = htonl((uint32_t)cfg->width); + hello[4] = htonl((uint32_t)cfg->height); + hello[5] = htonl(cfg->want_shm ? (uint32_t)DMD_XFER_SHM + : (uint32_t)DMD_XFER_TCP); + + if (send_exact(s, hello, sizeof(hello), s->io_timeout_ms) != DMD_OK) { + if (err) + *err = s->err; + return -1; + } + + uint32_t head[3]; + int r = recv_exact(s, head, sizeof(head), s->io_timeout_ms, s->io_timeout_ms); + if (r != DMD_OK) { + if (r == DMD_EOS) + sess_err(s, DMD_ERR_PROTOCOL, + "daemon 未回握手响应就关闭了连接(版本不匹配?)", 0); + else if (r == DMD_ERR_TIMEOUT) + sess_err(s, DMD_ERR_TIMEOUT, "等待握手响应超时", 0); + if (err) + *err = s->err; + return -1; + } + + uint32_t status = ntohl(head[0]); + uint32_t mode = ntohl(head[1]); + uint32_t nlen_w = ntohl(head[2]); + int has_ext = (nlen_w >> 31) != 0; /* v3: bit31 = 带 endpoint 扩展 */ + uint32_t nlen = nlen_w & 0x7fffffffu; + uint64_t ep_dev = 0, ep_ino = 0; + + /* daemon 的错误路径回的是裸 12 字节(nlen=0),先处理拒绝再读后续字节 */ + if (status != 0) { + const char *why = (status == 1) ? "daemon 拒绝握手: 协议版本不支持" + : (status == 2) ? "daemon 拒绝握手: codec 不支持" + : (status == 3) ? "daemon 拒绝握手: 分辨率超出 96x96~8192x4320" + : (status == 4) ? "daemon 拒绝握手: 缺少握手" + : "daemon 拒绝握手: 未知 status"; + err_set(&s->err, DMD_ERR_REJECTED, (int)status, why, 0); + if (err) + *err = s->err; + return -1; + } + + /* v3 endpoint 扩展:[u32 dev_hi][u32 dev_lo][u32 ino_hi][u32 ino_lo],大端 */ + if (has_ext) { + uint32_t ext[4]; + if (recv_exact(s, ext, sizeof(ext), + s->io_timeout_ms, s->io_timeout_ms) != DMD_OK) { + sess_err(s, DMD_ERR_PROTOCOL, "读取 endpoint 扩展失败", 0); + if (err) + *err = s->err; + return -1; + } + ep_dev = ((uint64_t)ntohl(ext[0]) << 32) | ntohl(ext[1]); + ep_ino = ((uint64_t)ntohl(ext[2]) << 32) | ntohl(ext[3]); + } else { + /* 旧 daemon(协议<3)不携带端点信息。只提醒一次,避免每连接刷屏。 */ + static int warned_legacy; + if (!warned_legacy) { + warned_legacy = 1; + dmd_c_log(s, "daemon 未上报 endpoint inode(协议<3),跳过 inode 校验"); + } + } + + char name[64]; + memset(name, 0, sizeof(name)); + if (nlen > 0) { + if (nlen >= sizeof(name)) { + sess_err(s, DMD_ERR_PROTOCOL, "握手响应里的名字长度非法", 0); + if (err) + *err = s->err; + return -1; + } + if (recv_exact(s, name, nlen, s->io_timeout_ms, s->io_timeout_ms) != DMD_OK) { + sess_err(s, DMD_ERR_PROTOCOL, "读取共享内存名字失败", 0); + if (err) + *err = s->err; + return -1; + } + } + + /* + * endpoint inode 对账 —— 本函数的核心新增。 + * + * connect 成功只说明"路径上有个活着的监听者",不说明它是我们要的那个。 + * 若平台把单个 socket 文件(而非目录)做 bind mount,daemon 重启换 inode + * 后,客户端侧解析到的是孤立旧 socket:症状曾是静默退化成软解或断流, + * 两侧 stat 甚至可能显示同一个孤立 inode,人工极难定位。 + * 现在 daemon 在响应里如实上报自己监听路径的 (st_dev, st_ino),客户端对 + * 自己 connect 所用路径 stat 对账;不一致就立刻失败并给出可行动的解释。 + * 绝不带病继续跑 —— 那正是本机制要消灭的"假装连接"。 + */ + if (s->ep_path[0] && !(ep_dev == 0 && ep_ino == 0)) { + struct stat st; + if (stat(s->ep_path, &st) != 0) { + char msg[192]; + snprintf(msg, sizeof(msg), + "无法 stat endpoint %s 核对 inode,拒绝继续", s->ep_path); + sess_err(s, DMD_ERR_ENDPOINT_MISMATCH, msg, 1); + if (err) + *err = s->err; + return -1; + } + uint64_t my_dev = (uint64_t)st.st_dev, my_ino = (uint64_t)st.st_ino; + if (my_dev != ep_dev || my_ino != ep_ino) { + /* 详细数值走日志(不受 err.msg 192 字节限制); + * err.msg 只放紧凑但可行动的核心结论。 */ + if (s->log) + dmd_c_log(s, "endpoint inode 不匹配详情: path=%s " + "stat(dev=%llu,ino=%llu) != daemon(dev=%llu,ino=%llu)", + s->ep_path, + (unsigned long long)my_dev, (unsigned long long)my_ino, + (unsigned long long)ep_dev, (unsigned long long)ep_ino); + char msg[192]; + snprintf(msg, sizeof(msg), + "endpoint inode mismatch: stat(ino=%llu) != daemon(ino=%llu)" + "; 挂载点指向旧 socket(bind mount 应挂目录而非 socket 文件)", + (unsigned long long)my_ino, (unsigned long long)ep_ino); + sess_err(s, DMD_ERR_ENDPOINT_MISMATCH, msg, 0); + if (err) + *err = s->err; + return -1; + } + if (s->log) + dmd_c_log(s, "endpoint 校验通过: dev=%llu ino=%llu", + (unsigned long long)my_dev, (unsigned long long)my_ino); + } + + /* mode==SHM 只是 daemon 的意向:响应在 memfd 交接之前发出 + * (decode-daemon.c:404 vs :409),交接失败它会静默退回 TCP 帧格式。 + * 所以领取失败绝不能当致命错误 —— 直接按 TCP 继续。 */ + s->xfer = DMD_XFER_TCP; + if (mode == (uint32_t)DMD_XFER_SHM && nlen > 0) { + if (shm_attach(s, name) == 0) + s->xfer = DMD_XFER_SHM; + else + dmd_c_log(s, "共享内存领取失败,退回 TCP 帧格式"); + } + return 0; +} + +/* ------------------------------------------------------------ 公开接口 */ +void dmd_session_config_init(struct dmd_session_config *cfg) +{ + if (!cfg) + return; + memset(cfg, 0, sizeof(*cfg)); + cfg->port = DMD_DEFAULT_PORT; + cfg->codec = DMD_CODEC_H264; + cfg->connect_timeout_ms = DMD_DEF_CONNECT_MS; + cfg->io_timeout_ms = DMD_DEF_IO_MS; +} + +int dmd_format_display_width(const struct dmd_format *fmt) +{ + if (!fmt || !fmt->valid) + return 0; + int w = fmt->crop_right - fmt->crop_left + 1; + return w > 0 ? w : 0; +} + +int dmd_format_display_height(const struct dmd_format *fmt) +{ + if (!fmt || !fmt->valid) + return 0; + int h = fmt->crop_bottom - fmt->crop_top + 1; + return h > 0 ? h : 0; +} + +struct dmd_session *dmd_session_create(const struct dmd_session_config *cfg, + struct dmd_error *err) +{ + if (err) { + memset(err, 0, sizeof(*err)); + } + if (!cfg) { + err_set(err, DMD_ERR_INVAL, 0, "cfg 为 NULL", 0); + return NULL; + } + /* 上界随 DMD_CODEC_* 增长,别写死数字 —— 加 AV1 时就漏改过一次。 */ + if (cfg->codec < DMD_CODEC_H264 || cfg->codec > DMD_CODEC_AV1) { + err_set(err, DMD_ERR_INVAL, 0, "codec 取值非法(应为 0..4)", 0); + return NULL; + } + if (cfg->width < 96 || cfg->height < 96 || + cfg->width > 8192 || cfg->height > 4320) { + err_set(err, DMD_ERR_INVAL, 0, + "分辨率超出 daemon 接受范围 96x96~8192x4320", 0); + return NULL; + } + + struct dmd_session *s = calloc(1, sizeof(*s)); + if (!s) { + err_set(err, DMD_ERR_NOMEM, 0, "会话分配失败", 0); + return NULL; + } + s->fd = -1; + s->log = dmd_log_wanted(); + s->codec = cfg->codec; + s->io_timeout_ms = cfg->io_timeout_ms > 0 ? cfg->io_timeout_ms : DMD_DEF_IO_MS; + s->xfer = DMD_XFER_TCP; + + uint16_t port = cfg->port ? cfg->port : DMD_DEFAULT_PORT; + int cto = cfg->connect_timeout_ms > 0 ? cfg->connect_timeout_ms + : DMD_DEF_CONNECT_MS; + + /* sock_path 优先:它不依赖 net namespace,适用面比 TCP 广。 */ + int crc = cfg->sock_path ? unix_connect(s, cfg->sock_path, cto, err) + : tcp_connect(s, port, cto, err); + if (crc < 0) { + if (err) + s->err = *err; + dmd_session_destroy(s); + return NULL; + } + if (do_handshake(s, cfg, DMD_HELLO_VERSION, err) < 0) { + /* + * 版本降级重试:daemon 侧 v0.3.1 及更早按**严格相等**判版本, + * 见到 v3 一律回 status=1 并断开。部署上 daemon 由平台 App 投放、 + * 驱动在容器内独立更新,"驱动新 / daemon 旧"是常态错配方向, + * 所以这里自动退一步用 v2 重连再试一次(v2 响应无 endpoint 扩展, + * inode 校验随之跳过 —— 能用总比连不上好,且会打日志说明)。 + * 只对 status=1 降级:其它拒绝原因(codec/分辨率)换版本也没用。 + */ + if (s->err.code == DMD_ERR_REJECTED && s->err.handshake_status == 1 && + DMD_HELLO_VERSION > 2) { + dmd_c_log(s, "daemon 不接受协议 v%u,降级为 v2 重试" + "(旧 daemon 按严格相等判版本;inode 校验将跳过)", + (unsigned)DMD_HELLO_VERSION); + if (s->fd >= 0) { + close(s->fd); /* daemon 拒绝后已断开,必须重连 */ + s->fd = -1; + } + s->ep_path[0] = '\0'; + memset(&s->err, 0, sizeof(s->err)); + crc = cfg->sock_path ? unix_connect(s, cfg->sock_path, cto, err) + : tcp_connect(s, port, cto, err); + if (crc < 0 || do_handshake(s, cfg, 2u, err) < 0) { + dmd_session_destroy(s); + return NULL; + } + } else { + dmd_session_destroy(s); + return NULL; + } + } + + /* 控制通道与帧传输是两件事,分开报。混在一起曾把走通的 Unix socket + * 误标成 TCP,据此排查会一路查错方向。 */ + if (cfg->sock_path) + dmd_c_log(s, "会话建立: unix=%s codec=%d %dx%d 帧传输=%s", + cfg->sock_path, cfg->codec, cfg->width, cfg->height, + s->xfer == DMD_XFER_SHM ? "SHM" : "内联"); + else + dmd_c_log(s, "会话建立: tcp=%u codec=%d %dx%d 帧传输=%s", + (unsigned)port, cfg->codec, cfg->width, cfg->height, + s->xfer == DMD_XFER_SHM ? "SHM" : "内联"); + return s; +} + +void dmd_session_destroy(struct dmd_session *s) +{ + if (!s) + return; + if (s->shm_base) { + /* 归还所有仍被持有的槽位:会话结束时 daemon 可能还在等, + * 留着占用会让它多等 1 秒才判定异常。 */ + for (int i = 0; i < s->shm_slots; i++) + __atomic_store_n(shm_state_word(s, i), 0u, __ATOMIC_RELEASE); + munmap(s->shm_base, s->shm_total); + s->shm_base = NULL; + } + if (s->fd >= 0) { + close(s->fd); + s->fd = -1; + } + free(s->rbuf); + s->rbuf = NULL; + free(s); +} + +int dmd_session_send_unit(struct dmd_session *s, const void *data, size_t len) +{ + if (!s) + return DMD_ERR_INVAL; + if (!data || len == 0) + return sess_err(s, DMD_ERR_INVAL, "数据单元为空", 0); + if (len > DMD_MAX_UNIT_BYTES) + return sess_err(s, DMD_ERR_TOOBIG, + "数据单元超过 daemon 的 8MB 上限", 0); + if (s->input_finished) + return sess_err(s, DMD_ERR_STATE, "已 finish_input,不能再发送", 0); + if (s->fd < 0) + return sess_err(s, DMD_ERR_STATE, "会话已无有效连接", 0); + /* 上一次发送在长度前缀之后失败过:上行字节流已经错位, + * 继续发只会让 daemon 把数据当长度解析。直接拒绝,逼调用方重建会话。 */ + if (s->tx_broken) + return sess_err(s, DMD_ERR_STATE, + "上行流已损坏(此前发送中断),需重建会话", 0); + + /* H.264/HEVC 必须带 Annex B 起始码:daemon 靠它定位 nal_unit_header + * 识别 SPS/PPS/VPS(decode-daemon.c:209-240)。缺失时解码器会静默 + * 吞掉全部输入、一帧不产 —— 与其静默失败,不如在这里直接报错。 + * VP8/VP9 相反:补起始码会破坏帧数据,所以这里也绝不代补。 */ + if (s->codec == DMD_CODEC_H264 || s->codec == DMD_CODEC_HEVC) { + const uint8_t *b = data; + int sc3 = (len >= 3 && b[0] == 0 && b[1] == 0 && b[2] == 1); + int sc4 = (len >= 4 && b[0] == 0 && b[1] == 0 && b[2] == 0 && b[3] == 1); + if (!sc3 && !sc4) + return sess_err(s, DMD_ERR_PROTOCOL, + "H.264/HEVC 数据单元缺少 Annex B 起始码", 0); + } + + uint32_t be = htonl((uint32_t)len); + int r = send_exact(s, &be, 4, s->io_timeout_ms); + if (r != DMD_OK) { + /* 长度前缀本身可能已部分写出,同样算流损坏 */ + s->tx_broken = 1; + return r; + } + r = send_exact(s, data, len, s->io_timeout_ms); + if (r != DMD_OK) { + s->tx_broken = 1; + return r; + } + + s->units_sent++; + return DMD_OK; +} + +int dmd_session_drain(struct dmd_session *s) +{ + if (!s) + return DMD_ERR_INVAL; + if (s->input_finished) + return sess_err(s, DMD_ERR_STATE, "已 finish_input,无需排空", 0); + if (s->fd < 0) + return sess_err(s, DMD_ERR_STATE, "会话已无有效连接", 0); + if (s->tx_broken) + return sess_err(s, DMD_ERR_STATE, + "上行流已损坏(此前发送中断),需重建会话", 0); + + /* 长度 0 = 排空请求。daemon 会送 EOS 逼解码器吐出在手的帧, + * 收齐后 flush 复位并重送 CSD —— 与 finish_input 不同,**会话仍可用**。 + * + * 为什么需要:消费者只保持 3 帧在飞,而解码器有 B 帧时要第 4 个单元 + * 才吐首帧,双方互等。原先只能用 finish_input 打破,但那不可逆, + * 每次都要重建会话(实测每帧 155 ms、播放慢 4.7 倍)。 */ + uint32_t be = htonl(0); + int r = send_exact(s, &be, 4, s->io_timeout_ms); + if (r != DMD_OK) { + s->tx_broken = 1; + return r; + } + s->drains_sent++; + return DMD_OK; +} + +int dmd_session_finish_input(struct dmd_session *s) +{ + if (!s) + return DMD_ERR_INVAL; + if (s->input_finished) + return DMD_OK; /* 幂等 */ + if (s->fd < 0) + return sess_err(s, DMD_ERR_STATE, "会话已无有效连接", 0); + /* shutdown 让 daemon 的 input_thread 读到 EOF,进而 queue 一个带 + * FLAG_END_OF_STREAM 的空缓冲触发 flush(decode-daemon.c:510-518)。 + * 不做这一步就取不到解码器里排队的尾部帧。 */ + if (shutdown(s->fd, SHUT_WR) < 0 && errno != ENOTCONN) + return sess_err(s, DMD_ERR_IO, "shutdown(SHUT_WR) 失败", 1); + s->input_finished = 1; + dmd_c_log(s, "已关闭写端,等待 flush 出的剩余帧"); + return DMD_OK; +} + +static int ensure_rbuf(struct dmd_session *s, size_t need) +{ + if (s->rbuf_size >= need) + return DMD_OK; + size_t ns = need + need / 2; + if (ns < 256 * 1024) + ns = 256 * 1024; + uint8_t *nb = realloc(s->rbuf, ns); + if (!nb) + return sess_err(s, DMD_ERR_NOMEM, "接收缓冲扩容失败", 0); + s->rbuf = nb; + s->rbuf_size = ns; + return DMD_OK; +} + +/* 把当前格式快照写进帧,让每帧自带自洽的几何信息 */ +static void frame_apply_format(const struct dmd_session *s, struct dmd_frame *f) +{ + f->unit_seq = s->last_pts; + f->stride = s->fmt.stride; + f->slice_height = s->fmt.slice_height; + f->crop_left = s->fmt.crop_left; + f->crop_top = s->fmt.crop_top; + f->crop_right = s->fmt.crop_right; + f->crop_bottom = s->fmt.crop_bottom; +} + +int dmd_session_next_frame(struct dmd_session *s, struct dmd_frame *out, + int timeout_ms) +{ + if (!s) + return DMD_ERR_INVAL; + if (!out) + return sess_err(s, DMD_ERR_INVAL, "out 为 NULL", 0); + if (s->fd < 0) + return sess_err(s, DMD_ERR_STATE, "会话已无有效连接", 0); + if (s->eos) + return DMD_EOS; + if (s->rbuf_busy) + return sess_err(s, DMD_ERR_STATE, + "上一帧尚未 release,TCP 缓冲仍被占用", 0); + + int first_to = (timeout_ms < 0) ? s->io_timeout_ms : timeout_ms; + int rest_to = s->io_timeout_ms; + + /* 循环:帧头可能是格式描述块的哨兵,要消费掉再继续等真正的帧 */ + for (;;) { + uint8_t hdr[12]; + int r = recv_exact(s, hdr, sizeof(hdr), first_to, rest_to); + if (r != DMD_OK) + return r; /* DMD_EOS / TIMEOUT / 错误原样上报 */ + + /* 逐字节 memcpy 再 ntohl:hdr 是 uint8_t[],aarch64 上直接强转 + * uint32_t* 解引用可能未对齐,是未定义行为 */ + uint32_t w_be, h_be, sz_be; + memcpy(&w_be, hdr + 0, 4); + memcpy(&h_be, hdr + 4, 4); + memcpy(&sz_be, hdr + 8, 4); + uint32_t w = ntohl(w_be), h = ntohl(h_be), sz = ntohl(sz_be); + + if (sz == DMD_FMTDESC_SENTINEL) { + /* 第 2 个字是能力标志(旧 daemon 为 0) */ + s->caps = h; + /* [0][0][0xFFFFFFFF] 之后是 8 个 32 位字的格式描述块 */ + uint32_t fw[DMD_FMTDESC_WORDS]; + r = recv_exact(s, fw, sizeof(fw), rest_to, rest_to); + if (r == DMD_EOS) + return sess_err(s, DMD_ERR_PROTOCOL, + "格式描述块被截断", 0); + if (r != DMD_OK) + return r; + s->fmt.buf_width = (int)ntohl(fw[0]); + s->fmt.buf_height = (int)ntohl(fw[1]); + s->fmt.stride = (int)ntohl(fw[2]); + s->fmt.slice_height = (int)ntohl(fw[3]); + s->fmt.crop_left = (int)ntohl(fw[4]); + s->fmt.crop_top = (int)ntohl(fw[5]); + s->fmt.crop_right = (int)ntohl(fw[6]); + s->fmt.crop_bottom = (int)ntohl(fw[7]); + s->fmt.valid = 1; + s->fmt.changes++; + dmd_c_log(s, "格式块#%d: 缓冲 %dx%d stride=%d slice=%d 显示 %dx%d", + s->fmt.changes, s->fmt.buf_width, s->fmt.buf_height, + s->fmt.stride, s->fmt.slice_height, + dmd_format_display_width(&s->fmt), + dmd_format_display_height(&s->fmt)); + /* 已经等到了字节,后续继续用 rest_to,避免探测式短超时误判 */ + first_to = rest_to; + continue; + } + + if (sz == DMD_SHMFRAME_SENTINEL) { + /* SHM 控制消息:帧头之后再跟 [4B 槽位号][4B 数据长度],共 20 字节 */ + uint32_t si[2]; + r = recv_exact(s, si, sizeof(si), rest_to, rest_to); + if (r == DMD_EOS) + return sess_err(s, DMD_ERR_PROTOCOL, "SHM 控制消息被截断", 0); + if (r != DMD_OK) + return r; + int slot = (int)ntohl(si[0]); + uint32_t dlen = ntohl(si[1]); + + /* 支持 PTS 的 daemon 在槽位/长度之后再跟一个字:输入单元序号。 + * 与 TCP 路径的帧头第 4 字段同义,保证两种传输模式一致。 */ + if (s->caps & DMD_CAP_FRAME_PTS) { + uint32_t p_be; + r = recv_exact(s, &p_be, 4, rest_to, rest_to); + if (r == DMD_EOS) + return sess_err(s, DMD_ERR_PROTOCOL, + "SHM 消息 PTS 字段被截断", 0); + if (r != DMD_OK) + return r; + s->last_pts = ntohl(p_be); + } else { + s->last_pts = 0; + } + + if (!s->shm_base) + return sess_err(s, DMD_ERR_PROTOCOL, + "收到 SHM 帧但共享内存未挂载", 0); + if (slot < 0 || slot >= s->shm_slots) + return sess_err(s, DMD_ERR_PROTOCOL, "SHM 槽位号越界", 0); + if ((size_t)dlen > s->shm_slot_bytes) + return sess_err(s, DMD_ERR_PROTOCOL, "SHM 帧长度超出槽位", 0); + + memset(out, 0, sizeof(*out)); + out->data = s->shm_base + DMD_SHM_CTRL_BYTES + + (size_t)slot * s->shm_slot_bytes; + out->size = dlen; + out->width = w; + out->height = h; + out->unit_seq = s->last_pts; + out->shm_slot = slot; + out->seq = s->frames_recv; + frame_apply_format(s, out); + /* SHM 路径也必须累加 frames_recv —— 它不只是统计。 + * + * ⚠️ 这里原先只读不写,于是 SHM 模式下该计数恒为 0, + * 造成两个后果: + * + * 1. dmd_session_frames_received() 恒 0,而 decode.c 的排空判据 + * 用 `frames_received() > 0` 当护栏("至少收到过一帧才允许 + * 判定等待徒劳",那是黑帧根因的修复)。恒 0 会让整个 + * wait_is_futile 恒假 —— 方向上偏保守(只靠超时、不会误排空), + * 但护栏语义已经失真,一旦将来有人改动那个表达式就会踩坑。 + * 2. out->seq 恒为 0,帧序号信息丢失。 + * + * TCP 路径在下面 s->frames_recv++ 处累加,两条路径必须一致。 */ + s->frames_recv++; + s->shm_held++; + return DMD_OK; + } + + /* 普通 TCP 帧。 + * 支持 CAP_FRAME_PTS 的 daemon 在 12 字节帧头后再跟一个字: + * 该帧对应的输入单元序号。必须在读帧体**之前**取走, + * 否则字节流错位(实测表现为六条流全部差异,含无重排的 VP8/VP9)。 */ + if (s->caps & DMD_CAP_FRAME_PTS) { + uint32_t p_be; + r = recv_exact(s, &p_be, 4, first_to, rest_to); + if (r == DMD_EOS) + return sess_err(s, DMD_ERR_PROTOCOL, "帧头 PTS 字段被截断", 0); + if (r != DMD_OK) + return r; + s->last_pts = ntohl(p_be); + } else { + s->last_pts = 0; /* 0 = 无 PTS 信息(旧 daemon) */ + } + + if (sz == 0) + return sess_err(s, DMD_ERR_PROTOCOL, "帧长度为 0", 0); + if (sz > DMD_MAX_FRAME_BYTES || w > 16384 || h > 16384) + return sess_err(s, DMD_ERR_PROTOCOL, "帧头数值不合理", 0); + + r = ensure_rbuf(s, sz); + if (r != DMD_OK) + return r; + r = recv_exact(s, s->rbuf, sz, rest_to, rest_to); + if (r == DMD_EOS) + return sess_err(s, DMD_ERR_PROTOCOL, "帧数据被截断", 0); + if (r != DMD_OK) + return r; + + memset(out, 0, sizeof(*out)); + out->data = s->rbuf; + out->size = sz; + out->width = w; + out->height = h; + out->shm_slot = -1; + out->seq = s->frames_recv; + frame_apply_format(s, out); + s->frames_recv++; + s->rbuf_busy = 1; + return DMD_OK; + } +} + +int dmd_session_release_frame(struct dmd_session *s, struct dmd_frame *f) +{ + if (!s) + return DMD_ERR_INVAL; + if (!f || !f->data) + return DMD_OK; /* 无条件调用是安全的 */ + + if (f->shm_slot >= 0) { + if (!s->shm_base || f->shm_slot >= s->shm_slots) + return sess_err(s, DMD_ERR_INVAL, "release 的槽位号无效", 0); + /* release 序:确保本进程对帧数据的读取都已完成, + * daemon 看到状态字变 0 之后才会覆写这个槽位 */ + __atomic_store_n(shm_state_word(s, f->shm_slot), 0u, __ATOMIC_RELEASE); + if (s->shm_held > 0) + s->shm_held--; + } else { + s->rbuf_busy = 0; + } + + f->data = NULL; + f->size = 0; + f->shm_slot = -1; + return DMD_OK; +} + +const struct dmd_format *dmd_session_format(const struct dmd_session *s) +{ + return s ? &s->fmt : NULL; +} + +const char *dmd_session_last_error(const struct dmd_session *s) +{ + if (!s) + return "会话为 NULL"; + return s->err.msg; +} + +int dmd_session_last_error_code(const struct dmd_session *s) +{ + return s ? s->err.code : DMD_ERR_INVAL; +} + +int dmd_session_xfer_mode(const struct dmd_session *s) +{ + return s ? s->xfer : DMD_XFER_TCP; +} + +int dmd_session_fd(const struct dmd_session *s) +{ + return s ? s->fd : -1; +} + +uint64_t dmd_session_units_sent(const struct dmd_session *s) +{ + return s ? s->units_sent : 0; +} + +uint64_t dmd_session_frames_received(const struct dmd_session *s) +{ + return s ? s->frames_recv : 0; +} diff --git a/codec/vaapi/src/dmd_client.h b/codec/vaapi/src/dmd_client.h new file mode 100644 index 0000000..26e0ace --- /dev/null +++ b/codec/vaapi/src/dmd_client.h @@ -0,0 +1,272 @@ +/* + * dmd_client.h - decode-daemon 客户端库(供 VA-API driver 内部使用) + * + * 这个库把「容器侧作为 Android decode-daemon 的客户端」这件事封装成一个 + * 不透明会话句柄。它最终会被链进 msm_drm_drv_video.so,由 libva 在 + * Firefox / ffmpeg 进程里 dlopen,因此遵守宿主插件的硬约束: + * + * - 绝不 exit() / abort() / assert():任何错误都通过返回码上报 + * - 绝不写 stdout;日志走 stderr,且默认静默,DMD_VA_LOG=1 才开 + * - 无全局/静态可变状态:所有状态在 struct dmd_session 内, + * 同进程内可并发开多个会话(每个会话一条 TCP 连接、一个 MediaCodec 实例) + * - 所有阻塞操作带超时:内部一律 poll + 非阻塞 fd,超时返回 DMD_ERR_TIMEOUT + * - 发送用 MSG_NOSIGNAL:对端断开不会给宿主进程投 SIGPIPE + * - 所有 fd 带 CLOEXEC:宿主可能 fork/exec,不泄漏 fd + * - 只依赖 libc + pthread(实际未用 pthread 原语,但目标链接里已有) + * + * 传输模式对调用方是透明的:SHM 模式下 dmd_frame.data 指向共享内存池, + * TCP 模式下指向会话内部缓冲。两种情况都必须调用 dmd_session_release_frame, + * 之后 data 失效。这是本库的主要价值 —— 调用方不必分两条路径。 + */ +#ifndef DMD_CLIENT_H +#define DMD_CLIENT_H + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/* ------------------------------------------------------------ 返回码 */ +/* + * 约定:0 成功,正数是非错误的流状态,负数是错误。 + * 出错后可用 dmd_session_last_error() 取人类可读的原因(含 errno 描述)。 + */ +enum { + DMD_OK = 0, + DMD_EOS = 1, /* 对端已关闭写端,且不会再有帧 */ + + DMD_ERR_INVAL = -1, /* 参数非法 */ + DMD_ERR_NOMEM = -2, /* 内存分配失败 */ + DMD_ERR_CONNECT = -3, /* connect 失败或超时 */ + DMD_ERR_REJECTED = -4, /* daemon 拒绝握手,见 dmd_error.handshake_status */ + DMD_ERR_IO = -5, /* socket 读写失败 */ + DMD_ERR_TIMEOUT = -6, /* 等待超时 */ + DMD_ERR_PROTOCOL = -7, /* 收到不符合协议的字节 */ + DMD_ERR_STATE = -8, /* 会话状态不允许该操作(如已 finish_input 后再发) */ + DMD_ERR_TOOBIG = -9, /* 数据单元/帧超出协议上限 */ + DMD_ERR_ENDPOINT_MISMATCH = -10 + /* 客户端 stat 到的 endpoint (dev,ino) 与 daemon 上报的不一致。 + * 典型病因:平台把单个 socket 文件而非目录做 bind mount,daemon 重启后 + * inode 变化,客户端侧解析到旧 socket。此错误不重试、不降级, + * 直接把错误抛给调用方(ffmpeg 会立刻看到失败而不是静默软解)。 */ +}; + +/* daemon 的 codec id,与 decode-daemon.c 的 CodecId 逐值一致。 + * ⚠️ 跨目录耦合:这些值是线协议的一部分(握手第 4 个字),改一侧必须改另一侧。 + * 只能在末尾追加,不可重排 —— 数值错配不会报错,会静默解错码。 */ +enum { + DMD_CODEC_H264 = 0, + DMD_CODEC_HEVC = 1, + DMD_CODEC_VP9 = 2, + DMD_CODEC_VP8 = 3, + DMD_CODEC_AV1 = 4 +}; + +/* 帧数据传输模式 */ +enum { + DMD_XFER_TCP = 0, + DMD_XFER_SHM = 1 +}; + +/* 上行数据单元上限(与 daemon 的 MAX_FRAME 一致,超出会被 daemon 判为非法长度) */ +#define DMD_MAX_UNIT_BYTES (8u * 1024u * 1024u) +/* 下行帧的合理性上限。注意它必须远大于 DMD_MAX_UNIT_BYTES: + * 4K NV12 单帧就是 12441600 字节,daemon 的 8MB 只约束输入侧。 */ +#define DMD_MAX_FRAME_BYTES (64u * 1024u * 1024u) + +/* 默认 Unix socket 路径。存在且是 socket 时优先于 TCP。 + * + * 平台应把宿主上的 socket 文件 bind mount 到这里 —— 仿 DroidSpaces 自己的 + * 显示通道做法:宿主 /data/local/tmp/anland-.sock → 容器 + * /run/display.sock(实测两侧 inode 相同,确认是同一文件)。 + * + * 这条路不依赖 net namespace,所以 host 型与 NAT 型容器都能用。 */ +#define DMD_DEFAULT_SOCK "/run/dmd/decode.sock" + +/* ------------------------------------------------------------ 配置 */ +struct dmd_session_config { + uint16_t port; /* daemon TCP 端口,0 表示用 20003 */ + /* 非 NULL = 连这个路径的 Unix socket,此时忽略 port。 + * 默认路径见 DMD_DEFAULT_SOCK。 + * + * 路径式 Unix socket **不属于 net namespace**:平台把宿主上的 socket + * 文件 bind mount 进容器即可,host 型与 NAT 型容器都能用。 + * 而 TCP 127.0.0.1 只在共享 net namespace 时可达(实测 NAT 型容器 + * netns 独立,TCP loopback 与 abstract socket 都不通)。 + * + * 字符串只在 dmd_session_create 期间被读取,调用方保证那段时间内有效。 */ + const char *sock_path; + int codec; /* DMD_CODEC_* */ + int width; /* 96..8192 */ + int height; /* 96..4320 */ + int want_shm; /* 非 0 = 请求共享内存传输(daemon 可降级) */ + int connect_timeout_ms;/* <=0 表示用默认 2000 */ + int io_timeout_ms; /* 单次收发的默认超时,<=0 表示用默认 5000 */ +}; + +/* 用默认值填充 cfg(端口 20003、H.264、TCP、2s/5s 超时)。cfg 为 NULL 时无操作。 */ +void dmd_session_config_init(struct dmd_session_config *cfg); + +/* ------------------------------------------------------------ 错误详情 */ +struct dmd_error { + int code; /* DMD_ERR_* */ + int handshake_status; /* code==DMD_ERR_REJECTED 时为 daemon 的 status + * 1=版本不支持 2=codec 不支持 3=分辨率超范围 + * 4=缺少握手;其他情况为 0 */ + char msg[192]; /* 人类可读原因,总是以 '\0' 结尾 */ +}; + +/* ------------------------------------------------------------ 格式 */ +/* + * 解码器输出缓冲的几何信息,来自 daemon 的格式描述块。 + * + * buf_width/buf_height 是**填充后的**缓冲尺寸(Venus 把宽对齐 128、高对齐 32, + * 1080p 输出 1920x1088);真实显示区由 crop 给出,且 crop 是**闭区间**: + * 显示宽 = crop_right - crop_left + 1 + * 显示高 = crop_bottom - crop_top + 1 + * 定位 UV 平面必须用 stride/slice_height:UV 起点 = stride * slice_height。 + */ +struct dmd_format { + int buf_width; + int buf_height; + int stride; + int slice_height; + int crop_left; + int crop_top; + int crop_right; + int crop_bottom; + int valid; /* 0 = 还没收到过格式块 */ + int changes; /* 收到格式块的次数,>1 说明流内分辨率变过 */ +}; + +/* 显示尺寸便捷取值(crop 闭区间换算),fmt 无效时返回 0 */ +int dmd_format_display_width(const struct dmd_format *fmt); +int dmd_format_display_height(const struct dmd_format *fmt); + +/* ------------------------------------------------------------ 帧 */ +/* + * 一帧 NV12 数据。data 的所有权始终属于库: + * SHM 模式 → 指向共享内存槽位,release 时把状态字置 0 归还给 daemon + * TCP 模式 → 指向会话内部接收缓冲,release 只是把它标记为可复用 + * 两种情况下 release 之后 data 都失效,调用方要么用完再 release, + * 要么自己先拷走。忘记 release 在 SHM 模式下会让 daemon 约 1 秒后判定 + * 客户端卡死并结束会话,因此 release 是强制的。 + */ +struct dmd_frame { + uint8_t *data; + size_t size; + + /* 帧头声明的尺寸(daemon 用的是缓冲尺寸,与 fmt.buf_* 一致) */ + uint32_t width; + uint32_t height; + + /* 该帧对应的**输入单元序号**(1 起),0 = daemon 未提供。 + * + * 由 daemon 在 queueInputBuffer 时写入 presentationTimeUs, + * MediaCodec 原样带到输出帧上。用途是精确配对:调用方据此就知道 + * 这一帧属于第几次提交,**无需知道解码器按什么顺序出帧**。 + * 旧 daemon 不带此字段时为 0,调用方需回退到按顺序推断。 */ + uint32_t unit_seq; + + /* 该帧生效的几何信息,从最近一次格式描述块复制而来,随帧自洽 */ + int stride; + int slice_height; + int crop_left; + int crop_top; + int crop_right; + int crop_bottom; + + int shm_slot; /* >=0 = SHM 槽位号;-1 = TCP 内部缓冲 */ + uint64_t seq; /* 会话内帧序号,从 0 起 */ +}; + +/* ------------------------------------------------------------ 会话 */ +struct dmd_session; + +/* + * 建立会话:连接 daemon、完成握手、(若请求)领取共享内存池。 + * 返回 NULL 表示失败;err 非 NULL 时写入失败原因(含 daemon 的拒绝码)。 + * 失败时不会有任何 fd 或映射泄漏。 + */ +struct dmd_session *dmd_session_create(const struct dmd_session_config *cfg, + struct dmd_error *err); + +/* 释放会话:关连接、解映射、释放缓冲。s 为 NULL 时无操作。 */ +void dmd_session_destroy(struct dmd_session *s); + +/* + * 送一个数据单元。 + * H.264/HEVC:一个 NALU,**必须带 Annex B 起始码**(3 或 4 字节)—— + * daemon 靠起始码定位 nal_unit_header 识别 SPS/PPS/VPS + * VP8/VP9: 一个完整帧,**不得带起始码** + * 本库不替调用方补起始码:补错会静默破坏码流,交由上层显式负责。 + * H.264/HEVC 缺起始码时直接返回 DMD_ERR_PROTOCOL,早失败早发现。 + * 返回 DMD_OK / DMD_ERR_*。 + */ +int dmd_session_send_unit(struct dmd_session *s, const void *data, size_t len); + +/* + * 关闭写端(shutdown(SHUT_WR)),触发 daemon 送 EOS 并 flush 解码器。 + * 送入的数据单元数 != 返回的帧数(排队、重排序、参数集不产帧), + * 因此必须调用本函数才能取到全部剩余帧。可重复调用(幂等)。 + */ +int dmd_session_finish_input(struct dmd_session *s); + +/* + * 可逆排空:让 daemon 送 EOS 逼解码器吐出在手的帧,收齐后 flush 复位 + * 并重送 CSD —— 与 finish_input 的区别是**会话之后仍然可用**。 + * + * 用途:消费者只保持少量帧在飞(浏览器是 3 帧),而解码器有 B 帧时要收到 + * 第 4 个输入单元才吐首帧,双方互等。此时调用本函数即可拿到帧且不作废会话。 + * 原先只能用 finish_input 打破互等,代价是每次都要重建会话 + * (实测每帧 155 ms,播放慢 4.7 倍)。 + * + * 排空后 daemon 会重新下发格式描述块,next_frame 内部自动消费,调用方无感。 + * 返回 DMD_OK / DMD_ERR_*。 + */ +int dmd_session_drain(struct dmd_session *s); + +/* + * 取下一帧。timeout_ms <0 表示用配置里的 io_timeout_ms。 + * 返回 DMD_OK 拿到帧、DMD_EOS 流结束、DMD_ERR_TIMEOUT 暂时无帧(会话仍可用)、 + * 其他负值为错误。内部自动消费格式描述块并更新 dmd_session_format()。 + * + * 注意:帧头到达后剩余字节按 io_timeout_ms 收,不会因为 timeout_ms 很小而 + * 留下半帧;超时只发生在「一个字节都还没来」的边界上。 + */ +int dmd_session_next_frame(struct dmd_session *s, struct dmd_frame *out, + int timeout_ms); + +/* + * 归还帧。SHM 模式归还槽位,TCP 模式解除内部缓冲占用。 + * 两种模式都必须调用,无条件调用是安全的(f 为 NULL 或已归还时无操作)。 + */ +int dmd_session_release_frame(struct dmd_session *s, struct dmd_frame *f); + +/* 最近一次格式描述块的内容。返回的指针在会话生命期内有效。 */ +const struct dmd_format *dmd_session_format(const struct dmd_session *s); + +/* 最近一次错误的人类可读原因;无错误时返回空字符串,绝不返回 NULL。 */ +const char *dmd_session_last_error(const struct dmd_session *s); + +/* 最近一次错误码(DMD_ERR_*),无错误时 0 */ +int dmd_session_last_error_code(const struct dmd_session *s); + +/* 实际生效的传输模式:DMD_XFER_TCP / DMD_XFER_SHM。 + * 请求 SHM 也可能因交接失败被静默降级,用它核实。 */ +int dmd_session_xfer_mode(const struct dmd_session *s); + +/* 底层 socket fd,供调用方自己 poll(不要 close 它) */ +int dmd_session_fd(const struct dmd_session *s); + +/* 统计:送入的数据单元数 / 取出的帧数 */ +uint64_t dmd_session_units_sent(const struct dmd_session *s); +uint64_t dmd_session_frames_received(const struct dmd_session *s); + +#ifdef __cplusplus +} +#endif + +#endif /* DMD_CLIENT_H */ diff --git a/codec/vaapi/src/driver.c b/codec/vaapi/src/driver.c new file mode 100644 index 0000000..ab24a9a --- /dev/null +++ b/codec/vaapi/src/driver.c @@ -0,0 +1,230 @@ +/* LFA MediaCodec VA-API driver — entry point and vtable wiring + * + * This file is derived from the DroidSpaces MediaCodec VA-API driver. The + * original relied on libva deriving the driver name from a DRM render node + * ("msm_drm") and therefore had to be installed as msm_drm_drv_video.so. LFA + * does not have a usable DRM render node inside the container, so it always + * selects the driver explicitly: + * + * LIBVA_DRIVER_NAME=lfa_codec + * LIBVA_DRIVERS_PATH=/usr/local/lib/lfa-codec/dri + * DMD_ENDPOINT=unix:/tmp/termux-va/termux-va.sock + * + * and installs the plugin as lfa_codec_drv_video.so. The driver name is not + * otherwise hard-coded; the vtable is the same. + * + * The entry symbol is generated by VA_DRIVER_INIT_FUNC for the header version + * in use (for example __vaDriverInit_1_20). libva tries the current version + * and then older ones, so the macro follows a libva upgrade automatically. + */ + +#include +#include +#include +#include + +#include "driver.h" + +/* 日志开关只读一次。driver 被 dlopen 进宿主进程, + * 每帧调 getenv 是不必要的开销。 */ +static int dmd_log_enabled = -1; + +void dmd_log(const char *fmt, ...) +{ + if (dmd_log_enabled < 0) { + const char *env = getenv("DMD_VA_LOG"); + dmd_log_enabled = (env && env[0] == '1') ? 1 : 0; + } + if (!dmd_log_enabled) + return; + + va_list ap; + va_start(ap, fmt); + /* 只写 stderr:stdout 属于宿主程序,driver 不得污染。 */ + fputs("[dmd-va] ", stderr); + vfprintf(stderr, fmt, ap); + va_end(ap); +} + +struct dmd_driver *dmd_get_driver(VADriverContextP ctx) +{ + if (!ctx || !ctx->pDriverData) + return NULL; + return (struct dmd_driver *)ctx->pDriverData; +} + +VAStatus dmd_Terminate(VADriverContextP ctx) +{ + if (!ctx) + return VA_STATUS_ERROR_INVALID_PARAMETER; + + struct dmd_driver *drv = dmd_get_driver(ctx); + if (!drv) { + /* init 中途失败后 libva 仍可能调到这里,必须安全返回。 */ + return VA_STATUS_SUCCESS; + } + + dmd_log("Terminate\n"); + + /* 释放全部对象:消费者理应自己销毁,但异常退出路径下不会。 + * driver 被 dlclose 后这些内存就再也回收不了,所以必须在这里兜。 + * + * 顺序有讲究:context 先拆(它持有 daemon 会话与 socket), + * 再拆 image(可能借用 surface 缓冲),最后 surface 与 buffer。 */ + pthread_mutex_lock(&drv->lock); + + int leaked_ctx = 0, leaked_surf = 0, leaked_buf = 0, leaked_img = 0; + + for (int i = 0; i < DMD_MAX_CONTEXTS; i++) { + if (drv->contexts[i].in_use) { + leaked_ctx++; + dmd_context_reset_locked(&drv->contexts[i]); + } + } + for (int i = 0; i < DMD_MAX_IMAGES; i++) { + struct dmd_image *img = &drv->images[i]; + if (!img->in_use) + continue; + leaked_img++; + /* derive 的 image 借用 surface 缓冲,不能重复 free。 */ + if (img->derived_from == VA_INVALID_ID) + free(img->data); + memset(img, 0, sizeof(*img)); + } + for (int i = 0; i < DMD_MAX_SURFACES; i++) { + if (drv->surfaces[i].in_use) { + leaked_surf++; + dmd_surface_reset_locked(&drv->surfaces[i]); + } + } + for (int i = 0; i < DMD_MAX_BUFFERS; i++) { + if (drv->buffers[i].in_use) { + leaked_buf++; + free(drv->buffers[i].data); + memset(&drv->buffers[i], 0, sizeof(drv->buffers[i])); + } + } + pthread_mutex_unlock(&drv->lock); + + if (leaked_ctx || leaked_surf || leaked_buf || leaked_img) + dmd_log("Terminate: 兜底回收 context=%d surface=%d buffer=%d image=%d" + "(消费者未自行销毁)\n", + leaked_ctx, leaked_surf, leaked_buf, leaked_img); + + pthread_cond_destroy(&drv->io_done); + pthread_mutex_destroy(&drv->lock); + free(drv); + ctx->pDriverData = NULL; + + return VA_STATUS_SUCCESS; +} + +/* 装配 vtable:覆盖 va_backend.h 中 VADriverVTable 的全部槽位。 + * + * libva 在 vaInitialize 里逐个校验 39 个槽位非 NULL(va/va.c 的 CHECK_VTABLE), + * 任一为 NULL 会导致整个初始化失败并 dlclose —— + * 所以未实现的入口也必须指向返回 UNIMPLEMENTED 的桩函数。 + * 装配列表由 tools/gen_stubs.py 从头文件生成,避免手抄漏项。 */ +static void dmd_init_vtable(struct VADriverVTable *vtable) +{ +#include "vtable.inc" +} + +/* 入口符号名必须是 __vaDriverInit__。libva 头文件没有提供生成 + * 该名字的宏(已确认 va_backend.h 只有 typedef VADriverInit),所以自己拼。 + * + * 版本选择:libva 从自身版本 1.N 起**降序**逐个 dlsym 到 1.0 + * (va/va.c 的 va_getDriverInitName + compatible_versions 循环),首个命中即用。 + * 因此导出 __vaDriverInit_1_0 的兼容窗口最宽 —— 任意 libva 1.x 都能接受; + * 只导出 1_22 则在 libva 低于 1.22 时不会被命中。 + * 两者都导出,成本为零:编译期版本一个(跟随头文件),1_0 一个(保底)。 + * + * -fvisibility=hidden 下必须显式标 default 可见性,否则符号不导出, + * libva 会报 "has no function __vaDriverInit_1_0"。 */ +#define DMD_CONCAT_(a, b, c) a##b##_##c +#define DMD_INIT_NAME_(maj, min) DMD_CONCAT_(__vaDriverInit_, maj, min) +#define DMD_DRIVER_INIT DMD_INIT_NAME_(VA_MAJOR_VERSION, VA_MINOR_VERSION) + +static VAStatus dmd_driver_init(VADriverContextP ctx); + +__attribute__((visibility("default"))) VAStatus +DMD_DRIVER_INIT(VADriverContextP ctx) +{ + return dmd_driver_init(ctx); +} + +/* 保底入口:让低于编译期版本的 libva 也能加载本驱动。 + * 若头文件本身就是 1.0,上面的宏已展开成同名函数,此处不再重复定义。 */ +#if VA_MAJOR_VERSION != 1 || VA_MINOR_VERSION != 0 +__attribute__((visibility("default"))) VAStatus +__vaDriverInit_1_0(VADriverContextP ctx) +{ + return dmd_driver_init(ctx); +} +#endif + +static VAStatus dmd_driver_init(VADriverContextP ctx) +{ + if (!ctx || !ctx->vtable) + return VA_STATUS_ERROR_INVALID_PARAMETER; + + struct dmd_driver *drv = calloc(1, sizeof(*drv)); + if (!drv) + return VA_STATUS_ERROR_ALLOCATION_FAILED; + + if (pthread_mutex_init(&drv->lock, NULL) != 0) { + free(drv); + return VA_STATUS_ERROR_ALLOCATION_FAILED; + } + if (pthread_cond_init(&drv->io_done, NULL) != 0) { + pthread_mutex_destroy(&drv->lock); + free(drv); + return VA_STATUS_ERROR_ALLOCATION_FAILED; + } + + /* 各类 ID 从 1 起,0 不发给调用方。 + * 各表用独立的 ID 空间,但 image 的 buf_id 借用 buffer 空间 —— + * MapBuffer 要能用一个 ID 同时在两张表里查(见 image.c 的说明)。 */ + drv->next_config_id = 1; + drv->next_surface_id = 1; + drv->next_context_id = 1; + drv->next_buffer_id = 1; + drv->next_image_id = 1; + + /* drm_state 由 libva 填好(display_type 0x31 = DRM_RENDERNODES)。 + * 当前只记录 fd,解码路径接入后才会用到。 */ + drv->drm_fd = -1; + if (ctx->drm_state) { + const struct drm_state *drm = (const struct drm_state *)ctx->drm_state; + drv->drm_fd = drm->fd; + } + + ctx->pDriverData = drv; + + /* libva 传入 version_major/minor 为 0/0,driver 必须自己填。 */ + ctx->version_major = VA_MAJOR_VERSION; + ctx->version_minor = VA_MINOR_VERSION; + + /* 这 5 个 max 字段必须全部 > 0(va/va.c 的 CHECK_MAXIMUM), + * 且消费者据此分配查询数组,必须 >= 我们实际返回的数量。 */ + ctx->max_profiles = DMD_MAX_PROFILES; + ctx->max_entrypoints = DMD_MAX_ENTRYPOINTS; + ctx->max_attributes = DMD_MAX_CONFIG_ATTRIBUTES; + ctx->max_image_formats = DMD_MAX_IMAGE_FORMATS; + ctx->max_subpic_formats = DMD_MAX_SUBPIC_FORMATS; + ctx->max_display_attributes = DMD_MAX_DISPLAY_ATTRIBUTES; + + /* str_vendor 必须非 NULL(CHECK_STRING)。 + * 注意 ffmpeg 按这个串匹配 vaapi_driver_quirks 名单; + * 我们不在名单内 → 走 standard behaviour。 */ + ctx->str_vendor = DMD_VENDOR_STRING; + + dmd_init_vtable(ctx->vtable); + + /* display_type 在 VADriverContext 里是 unsigned long,用 %lx。 */ + dmd_log("init: display_type=0x%lx drm_fd=%d va=%d.%d vendor=%s\n", + (unsigned long)ctx->display_type, drv->drm_fd, ctx->version_major, + ctx->version_minor, ctx->str_vendor); + + return VA_STATUS_SUCCESS; +} diff --git a/codec/vaapi/src/driver.h b/codec/vaapi/src/driver.h new file mode 100644 index 0000000..77486d2 --- /dev/null +++ b/codec/vaapi/src/driver.h @@ -0,0 +1,564 @@ +/* DroidSpaces MediaCodec VA-API driver — 内部数据结构与公共声明 + * + * 本驱动被 libva 以 dlopen 方式加载进消费者进程(vainfo / ffmpeg / Firefox), + * 因此遵守插件规矩:不 exit/abort、不写 stdout、日志默认静默、全部入口线程安全。 + */ + +#ifndef DMD_DRIVER_H +#define DMD_DRIVER_H + +#include +#include + +#include +#include +#include +#include +#include +/* struct drm_state 定义在这里,va_backend.h 只做前向声明。 */ +#include + +#include "dmd_client.h" +#include "stubs.h" + +/* 驱动版本,随 vendor 串一起被消费者看到。 + * 注意 ffmpeg 按 vendor 串匹配 vaapi_driver_quirks 名单;我们不在名单内, + * 走 standard behaviour,即要求语义标准。 */ +/* ⚠️ 发版时必须同步:本串经 DMD_VENDOR_STRING 显示在 vainfo 的 + * "Driver version" 里,是用户可见信息。曾长期停在 0.3.3 而项目已到 + * 0.3.7(落后 4 版),用户按 vainfo 报 bug 时会指向错误的版本。 + * 同步清单:本文件、ksu-module/module.prop、CHANGELOG.md。 */ +#define DMD_DRIVER_VERSION "lfa-1" +#define DMD_VENDOR_STRING "LFA MediaCodec VA-API driver " DMD_DRIVER_VERSION + +/* 设备硬件解码能力,来自 /vendor/etc/media_codecs.xml(真机取证)。 + * H.264/HEVC 解码器规格:96x96 ~ 8192x4320,并发实例 16,支持 adaptive-playback。 */ +#define DMD_MIN_WIDTH 96 +#define DMD_MIN_HEIGHT 96 +#define DMD_MAX_WIDTH 8192 +#define DMD_MAX_HEIGHT 4320 + +/* libva 要求 max_* 字段全部 > 0(va/va.c 的 CHECK_MAXIMUM), + * 且这些值是消费者分配查询数组的依据,必须 >= 我们实际返回的数量。 */ +#define DMD_MAX_PROFILES 16 +#define DMD_MAX_ENTRYPOINTS 4 +#define DMD_MAX_CONFIG_ATTRIBUTES 32 +#define DMD_MAX_IMAGE_FORMATS 4 +#define DMD_MAX_SUBPIC_FORMATS 4 +#define DMD_MAX_DISPLAY_ATTRIBUTES 4 + +/* 同时存活的 config 对象上限。VA-API 的 config 极轻量, + * 消费者通常只建 1-2 个;给足余量即可。 */ +#define DMD_MAX_CONFIGS 32 + +/* surface 上限:ffmpeg 的 hwframe pool 默认 20+ 个(initial_pool_size 加 + * 解码器的 DPB 需求),Firefox 会更多。64 对 8 个并发实例足够。 */ +#define DMD_MAX_SURFACES 64 + +/* MediaCodec 的输出滞后深度(实测值,见 vaapi-driver/tools 里的 probe_lag): + * 有 B 帧的 H.264 流要送进第 4 个输入单元才吐出第 1 帧,无 B 帧时是 1。 + * + * SyncSurface 用它作为"放行额度":在飞帧数低于此值时不阻塞消费者, + * 让它继续送料把流水线填满;达到之后才真正阻塞等帧。 + * 取 6(滞后 4 再留 2 的余量)—— 太小会退回死锁,太大会让队列变长、 + * 增加延迟且浪费 surface。 + * + * ⚠️ 跨目录耦合:daemon 侧的 SHM_SLOTS(src/decode-daemon.c)必须 + * >= 本值。本值决定驱动会放行多少帧不取,池装不下就会撞"槽位全忙"。 + * 历史事故:SHM_SLOTS=4 < 本值 6,第 5 帧必然撞池满,daemon 在 + * 1 秒后判死并杀掉会话 —— 4K + 慢消费者场景 10/10 丢帧(238/300)。 + * 调大本值时必须同步检查 SHM_SLOTS。 */ +#define DMD_PIPELINE_DEPTH 6 + +/* 队列满时为腾空位收一帧的等待上限。 + * + * 短一点:这条路径在 EndPicture 里(提交路径),等太久会拖慢提交。 + * 长一点:太短则腾不出空位、白白返回失败。 + * 200ms 足够 MediaCodec 在正常负载下吐出一帧(实测 1080p p95 约 10ms)。 */ +#define DMD_BACKPRESSURE_MS 200 + +/* 等这么久(毫秒)仍取不到帧,才认定上游不再送料、执行不可逆的 flush。 + * + * 必须是固定值,不能按调用方的超时推算:调用方的耐心不是"流已结束"的证据。 + * Firefox 用很短的超时轮询 vaSyncSurface,按比例推算会得到极小的阈值, + * 才送 3 帧就误判流结束 → flush → 会话作废 → 永久回落软解。 */ +#define DMD_FLUSH_AFTER_MS 2000 +/* context 上限对齐 media_codecs.xml 声明的并发解码实例数(16)。 */ +#define DMD_MAX_CONTEXTS 16 +/* buffer 上限:每帧 4 个左右(pic param / IQ matrix / slice param / slice data), + * ffmpeg 在 EndPicture 后才 Destroy,同时存活量与 DPB 深度相关。 */ +#define DMD_MAX_BUFFERS 256 +/* image 上限:ffmpeg 每次 map 建一个、unmap 即销毁,同时存活量很小。 */ +#define DMD_MAX_IMAGES 64 + +/* 缓冲几何对齐:Venus 解码器输出宽对齐 128、高对齐 32 + * (1080p → 1920x1088,真机取证)。surface 按此预分配, + * 保证 daemon 回来的帧一定装得下,不必等到收到格式块才分配。 */ +#define DMD_WIDTH_ALIGN 128 +#define DMD_HEIGHT_ALIGN 32 + +/* 等一帧从 daemon 回来的上限。driver 跑在宿主进程里,绝不允许无限等: + * 超时返回错误让消费者自己决定重试或放弃,比挂死整个进程好。 + * + * ⚠️ 跨目录耦合:daemon 侧的 SHM_SLOT_WAIT_MS(src/decode-daemon.c) + * 必须 > 本值。本值是客户端愿意等一帧的时长,daemon 等空闲槽位的上限 + * 若比它短,daemon 就会在客户端还愿意等的时候先放弃并杀掉会话。 + * 历史事故:daemon 只等 1000ms < 本值 5000ms,把本可正常完成的解码 + * 变成丢帧。调大本值时必须同步检查 SHM_SLOT_WAIT_MS。 */ +#define DMD_FRAME_TIMEOUT_MS 5000 + +/* 一个 surface:VA-API 的解码目标,持有一块 NV12 缓冲。 + * + * 数据流:EndPicture 把 slice data 送给 daemon 并把 surface 挂进 context 的 + * 待解码队列;SyncSurface 从 daemon 取帧、按 FIFO 顺序填进队首 surface 的缓冲。 + */ +struct dmd_surface { + int in_use; + VASurfaceID id; + /* 请求尺寸(显示尺寸,ffmpeg 传 1920x1080)。VAImage 以此为准。 */ + unsigned int width; + unsigned int height; + /* 缓冲几何:宽对齐 128、高对齐 32 后的值,data 按此分配。 */ + unsigned int buf_width; + unsigned int buf_height; + unsigned int stride; + unsigned int slice_height; + unsigned int format; /* VA_RT_FORMAT_* */ + unsigned char *data; + size_t data_size; + /* dumb buffer 后备存储:exportable 非 0 表示 data 是 mmap 出来的可导出 + * 内存,可通过 DRM_IOCTL_PRIME_HANDLE_TO_FD 导出 dmabuf fd。 + * Firefox 取帧走 vaExportSurfaceHandle,没有它就整条流回落软解; + * 分配失败时回落普通 heap(exportable=0),ffmpeg 的 hwdownload 仍可用。 */ + uint32_t dumb_handle; + size_t dumb_size; + int exportable; + /* 释放 dumb buffer 需要当初分配它的 drm fd。存在 surface 上而不是让 + * 释放函数多收一个参数 —— 这样不可能传错 fd。 */ + int dumb_drm_fd; + /* 解码状态:0=空闲(VASurfaceReady),1=已提交待解码(VASurfaceRendering), + * 2=帧已就绪(VASurfaceReady 且 data 有效)。 */ + int state; + /* 该 surface 上一次解码的结果,SyncSurface 返回它。 */ + VAStatus decode_status; + VAContextID context; /* 提交时所属 context,未提交为 VA_INVALID_ID */ +}; + +#define DMD_SURFACE_IDLE 0 +#define DMD_SURFACE_PENDING 1 +#define DMD_SURFACE_READY 2 + +/* 一个 buffer:VA-API 参数/码流缓冲。 */ +struct dmd_buffer { + int in_use; + VABufferID id; + VAContextID context; + VABufferType type; + unsigned int element_size; + unsigned int num_elements; + size_t size; /* element_size * num_elements */ + void *data; + int mapped; +}; + +/* 一个 image:VAImage 的后备存储。data 是普通 heap 内存 + * (容器内 ION/dma_heap 均不可用,dmabuf 零拷贝这条路已被否掉)。 */ +struct dmd_image { + int in_use; + VAImageID id; + VABufferID buf_id; /* 供 vaMapBuffer 用的伪 buffer ID */ + VAImage image; + unsigned char *data; + size_t data_size; + int mapped; + /* derive 出来的 image 绑定在某个 surface 上;CreateImage 的为 VA_INVALID_ID */ + VASurfaceID derived_from; +}; + +/* 一个 context:config + render target 集合 + 一条 daemon 会话。 + * + * 待解码队列 pending[] 是 VA-API 乱序语义与 MediaCodec 流式语义之间的桥。 + * + * ⚠️ 配对规则按 codec 分两种,因为两侧的顺序不一定相同: + * + * - VP9/VP8(无帧重排):ffmpeg 的提交顺序 == daemon 的出帧顺序, + * 直接 FIFO 配对(取队首)。实测严格 1 进 1 出。 + * + * - H.264/HEVC(有 B 帧重排):ffmpeg 按**解码顺序**调 EndPicture, + * 而 MediaCodec 按**显示顺序**吐帧 —— 两者不同序! + * 本流实测解码序 I P B B B...(P 在第 2 位,因为 B 要参考它), + * 显示序 I B B B P...。若按 FIFO 配对,第 2 个提交(P 的 surface) + * 会被填进第 2 个输出(B 的内容),从第 2 帧起全错。 + * 所以必须按 POC(显示顺序)配对:daemon 的第 k 帧给 POC 第 k 小的 surface。 + * POC 取自 VAPictureParameterBufferH264.CurrPic.TopFieldOrderCnt, + * ffmpeg 传的是已解包的 field_poc[0](vaapi_h264.c:74), + * 不是码流里 6 bit 会回绕的 poc_lsb,故可直接比较大小。 + */ +struct dmd_context { + int in_use; + VAContextID id; + VAConfigID config_id; + VAProfile profile; + int codec; /* DMD_CODEC_* */ + unsigned int picture_width; + unsigned int picture_height; + int flag; + + /* daemon 会话。惰性创建:CreateContext 时建,失败则留 NULL 由 + * EndPicture 重试 —— 建 context 时 daemon 不可用不该让整个初始化失败。 */ + struct dmd_session *session; + int session_failed; /* 建会话失败过,避免每帧重试拖慢失败路径 */ + + /* 待解码队列:EndPicture 提交的 surface。 + * VP9/VP8 取队首;H.264/HEVC 取 pending_poc 最小者(见结构体头注释)。 */ + VASurfaceID pending[DMD_MAX_SURFACES]; + int32_t pending_poc[DMD_MAX_SURFACES]; + /* 所属 coded video sequence 序号:POC 每逢 IDR 会重置,跨序列比 POC + * 大小没有意义,所以排序时先比 seq 再比 POC。 */ + unsigned int pending_seq[DMD_MAX_SURFACES]; + /* 该 surface 对应的**提交序号**(第几次向 daemon 送数据单元,1 起)。 + * daemon 把它作为 PTS 原样回传到帧上(dmd_frame.unit_seq), + * 于是配对可以精确匹配,而不必假设解码器的出帧顺序。 */ + uint64_t pending_unit[DMD_MAX_SURFACES]; + int pending_head; + int pending_count; + /* 已提交的数据单元计数,给 pending_unit 发号。 */ + uint64_t units_submitted; + /* daemon 是否回传 unit_seq(运行时从帧里观测,非编译期假设)。 + * 有它就能精确配对,且说明 daemon 已开跟随输入序输出(滞后 1)。 */ + int daemon_has_unit_seq; + /* 本帧的 POC,RenderPicture 从 pic param 取、EndPicture 随 surface 入队。 + * 仅 H.264/HEVC 有意义。 */ + int32_t current_poc; + int have_current_poc; + /* frame_num 在每个 IDR 处归零(规范 7.4.3),用它检测新序列 —— + * 不能用 POC 比较,因为解码序内 POC 本来就起伏。 */ + unsigned int current_frame_num; + int32_t last_poc; + unsigned int last_frame_num; + int have_last_poc; + unsigned int last_seq; + + /* 当前 BeginPicture 选定的目标 surface,EndPicture 用完清空 */ + VASurfaceID current_target; + /* 本帧累积的码流数据(RenderPicture 可能分多次给 slice data) */ + unsigned char *slice_data; + size_t slice_len; + size_t slice_cap; + /* 本帧的 VP8 slice 参数,合成 uncompressed chunk 需要 */ + int have_vp8_slice_param; + VASliceParameterBufferVP8 vp8_slice_param; + int have_vp8_pic_param; + VAPictureParameterBufferVP8 vp8_pic_param; + + /* AV1:合成 OBU 需要两样东西 —— + * 1) pic param 的结构化字段:序列头与帧头**只存在于这里**, + * VASliceDataBuffer 里仅有 tile 载荷、不含任何 OBU 封装 + * (va_dec_av1.h:643-645 明确说明码流按 per-tile 粒度传入) + * 2) 每个 tile 在码流缓冲里的偏移与长度:tile_group 必须逐 tile 写 + * tile_size_minus_1,而 slice_data 是连成一片累积的。 + * + * ⚠️ 边界来源必须是 VASliceParameterBufferAV1,**不能**数 + * VASliceDataBuffer 的追加次数。实机实测:ffmpeg 每帧只调一次 + * vaRenderPicture 送 slice data,却在同一帧声明 8 个 tile —— + * 即整帧 tile 打包在一个 buffer 里,靠追加次数只会得到 1。 + * 正确来源是每 tile 一份的 slice param(va_dec_av1.h:635 "should be + * sent once per tile"),其 slice_data_size/slice_data_offset 分别是 + * tile 字节数与在缓冲内的偏移(:649-658,注释明确说 slice_data_size + * "actually means tile_data_size")。 + * + * 512 项足以覆盖 8K/多 tile 场景(规范 MAX_TILE_COLS×MAX_TILE_ROWS + * 名义上 64×64,实际受 MAX_TILE_AREA 约束远小于此)。 */ + int have_av1_pic_param; + VADecPictureParameterBufferAV1 av1_pic_param; + VASliceParameterBufferAV1 av1_tile_param[512]; + int av1_tile_count; + + /* H.264:VA-API 从不传递参数集(SPS/PPS 被解析成字段后原始比特流就丢了), + * 所以要从 pic param 反向合成,并在首个 VCL 之前发给 daemon。 */ + int have_h264_pic_param; + VAPictureParameterBufferH264 h264_pic_param; + /* HEVC 图像参数:合成 VPS/SPS/PPS 用。与 h264 那份互斥使用。 */ + /* PPS 的 num_ref_idx 默认值推导:l0 取见过的最大、l1 取见过的最小。 + * 见 decode.c 的说明 —— 直接照抄每帧生效值会写出错误的 PPS 默认值。 */ + unsigned int refidx_l0_max; + unsigned int refidx_l1_min; + int refidx_seen; + + VAPictureParameterBufferHEVC hevc_pic_param; + int hevc_pic_param_valid; + int have_h264_slice_param; + VASliceParameterBufferH264 h264_slice_param; + int have_h264_iq_matrix; + VAIQMatrixBufferH264 h264_iq_matrix; + int param_sets_sent; + unsigned int sent_mbs_wide; + unsigned int sent_mbs_high; + /* 上次随 PPS 发出的 num_ref_idx 默认值。它必须跟随当前帧的生效值, + * 变化时要重发 PPS —— l1 偏大会改变 ref_idx_l1 的熵解码码长。 */ + unsigned int sent_l0; + unsigned int sent_l1; + unsigned int pending_l0; + unsigned int pending_l1; + /* 已 shutdown(SHUT_WR):不能再发送,也不必重复 flush */ + int input_finished; +}; + +/* 一个 VA-API config 对象:profile + entrypoint + 属性集合 */ +struct dmd_config { + int in_use; + VAConfigID id; + VAProfile profile; + VAEntrypoint entrypoint; + VAConfigAttrib attribs[DMD_MAX_CONFIG_ATTRIBUTES]; + int num_attribs; +}; + +/* 驱动私有数据,挂在 ctx->pDriverData + * + * 锁策略:单把 lock 保护所有对象表。这不是性能瓶颈 —— 表操作都是 O(表长) + * 的内存操作。**但阻塞 IO 绝不能持锁做**:与 daemon 的收发在放锁后进行, + * 靠 context 的 busy 标志串行化同一 context 上的 IO。 + */ +struct dmd_driver { + pthread_mutex_t lock; + /* IO 完成时广播,等 context 的 busy 标志用 */ + pthread_cond_t io_done; + + struct dmd_config configs[DMD_MAX_CONFIGS]; + struct dmd_surface surfaces[DMD_MAX_SURFACES]; + struct dmd_context contexts[DMD_MAX_CONTEXTS]; + struct dmd_buffer buffers[DMD_MAX_BUFFERS]; + struct dmd_image images[DMD_MAX_IMAGES]; + + unsigned int next_config_id; + unsigned int next_surface_id; + unsigned int next_context_id; + unsigned int next_buffer_id; + unsigned int next_image_id; + + /* 某个 context 正在做 daemon IO(放锁期间的互斥标志)。 + * 用数组下标而非 ID,查找更快。 */ + int io_busy[DMD_MAX_CONTEXTS]; + + int drm_fd; /* 来自 ctx->drm_state,仅记录,当前不做 ioctl */ +}; + +/* 从 VADriverContext 取私有数据;ctx 或 pDriverData 为空时返回 NULL。 */ +struct dmd_driver *dmd_get_driver(VADriverContextP ctx); + +/* 日志:默认静默,设 DMD_VA_LOG=1 后输出到 stderr。 + * 绝不写 stdout —— 那会污染宿主进程的输出。 */ +void dmd_log(const char *fmt, ...) __attribute__((format(printf, 1, 2))); + +/* ---- 已实现的 vtable 入口(其余在自动生成的 stubs.c 中) ---- */ + +VAStatus dmd_Terminate(VADriverContextP ctx); + +VAStatus dmd_QueryConfigProfiles(VADriverContextP ctx, VAProfile *profile_list, + int *num_profiles); + +VAStatus dmd_QueryConfigEntrypoints(VADriverContextP ctx, VAProfile profile, + VAEntrypoint *entrypoint_list, + int *num_entrypoints); + +VAStatus dmd_GetConfigAttributes(VADriverContextP ctx, VAProfile profile, + VAEntrypoint entrypoint, + VAConfigAttrib *attrib_list, int num_attribs); + +VAStatus dmd_CreateConfig(VADriverContextP ctx, VAProfile profile, + VAEntrypoint entrypoint, VAConfigAttrib *attrib_list, + int num_attribs, VAConfigID *config_id); + +VAStatus dmd_DestroyConfig(VADriverContextP ctx, VAConfigID config_id); + +VAStatus dmd_QueryConfigAttributes(VADriverContextP ctx, VAConfigID config_id, + VAProfile *profile, VAEntrypoint *entrypoint, + VAConfigAttrib *attrib_list, + int *num_attribs); + +VAStatus dmd_QuerySurfaceAttributes(VADriverContextP ctx, VAConfigID config, + VASurfaceAttrib *attrib_list, + unsigned int *num_attribs); + +VAStatus dmd_QueryImageFormats(VADriverContextP ctx, VAImageFormat *format_list, + int *num_formats); + +VAStatus dmd_QuerySubpictureFormats(VADriverContextP ctx, + VAImageFormat *format_list, + unsigned int *flags, + unsigned int *num_formats); + +VAStatus dmd_QueryDisplayAttributes(VADriverContextP ctx, + VADisplayAttribute *attr_list, + int *num_attributes); + +VAStatus dmd_GetDisplayAttributes(VADriverContextP ctx, + VADisplayAttribute *attr_list, + int num_attributes); + +VAStatus dmd_SetDisplayAttributes(VADriverContextP ctx, + VADisplayAttribute *attr_list, + int num_attributes); + +/* ---- decode.c:解码数据路径 ---- */ + +VAStatus dmd_CreateSurfaces(VADriverContextP ctx, int width, int height, + int format, int num_surfaces, + VASurfaceID *surfaces); + +VAStatus dmd_CreateSurfaces2(VADriverContextP ctx, unsigned int format, + unsigned int width, unsigned int height, + VASurfaceID *surfaces, unsigned int num_surfaces, + VASurfaceAttrib *attrib_list, + unsigned int num_attribs); + +VAStatus dmd_DestroySurfaces(VADriverContextP ctx, VASurfaceID *surface_list, + int num_surfaces); + +VAStatus dmd_CreateContext(VADriverContextP ctx, VAConfigID config_id, + int picture_width, int picture_height, int flag, + VASurfaceID *render_targets, int num_render_targets, + VAContextID *context); + +VAStatus dmd_DestroyContext(VADriverContextP ctx, VAContextID context); + +VAStatus dmd_CreateBuffer(VADriverContextP ctx, VAContextID context, + VABufferType type, unsigned int size, + unsigned int num_elements, void *data, + VABufferID *buf_id); + +VAStatus dmd_BufferSetNumElements(VADriverContextP ctx, VABufferID buf_id, + unsigned int num_elements); + +VAStatus dmd_MapBuffer(VADriverContextP ctx, VABufferID buf_id, void **pbuf); + +VAStatus dmd_MapBuffer2(VADriverContextP ctx, VABufferID buf_id, void **pbuf, + uint32_t flags); + +VAStatus dmd_UnmapBuffer(VADriverContextP ctx, VABufferID buf_id); + +VAStatus dmd_DestroyBuffer(VADriverContextP ctx, VABufferID buffer_id); + +VAStatus dmd_BufferInfo(VADriverContextP ctx, VABufferID buf_id, + VABufferType *type, unsigned int *size, + unsigned int *num_elements); + +VAStatus dmd_BeginPicture(VADriverContextP ctx, VAContextID context, + VASurfaceID render_target); + +VAStatus dmd_RenderPicture(VADriverContextP ctx, VAContextID context, + VABufferID *buffers, int num_buffers); + +VAStatus dmd_EndPicture(VADriverContextP ctx, VAContextID context); + +VAStatus dmd_SyncSurface(VADriverContextP ctx, VASurfaceID render_target); + +VAStatus dmd_SyncSurface2(VADriverContextP ctx, VASurfaceID surface, + uint64_t timeout_ns); + +/* ---- export.c:dmabuf 出口 ---- */ + +/* 把 surface 导出成 dmabuf(DRM_PRIME_2)。 + * + * Firefox 取帧只走这条路:CreateImageVAAPI 拿不到 DRM_PRIME_2 描述符就 + * 返回 DECODE_ERR,播放器随即回落软解,且没有拷贝回退路径。 + * ffmpeg 命令行不需要它(hwdownload 走 vaDeriveImage + vaMapBuffer)。 */ +VAStatus dmd_ExportSurfaceHandle(VADriverContextP ctx, VASurfaceID surface_id, + uint32_t mem_type, uint32_t flags, + void *descriptor); + +/* 等到 surface 像素真的就绪(内部自行加锁,调用方不得持锁)。 + * + * SyncSurface 为避免与 MediaCodec 的流水线深度死锁,会对"已提交但未就绪" + * 的 surface 直接报成功放行,真正的等待推迟到取像素时。所以 image.c 的 + * DeriveImage / GetImage 在读 surface 几何或拷像素之前必须先调用本函数。 */ +VAStatus dmd_surface_wait(struct dmd_driver *drv, VASurfaceID surface); + +VAStatus dmd_QuerySurfaceStatus(VADriverContextP ctx, + VASurfaceID render_target, + VASurfaceStatus *status); + +/* ---- image.c:VAImage 出口 ---- */ + +VAStatus dmd_CreateImage(VADriverContextP ctx, VAImageFormat *format, + int width, int height, VAImage *image); + +VAStatus dmd_DeriveImage(VADriverContextP ctx, VASurfaceID surface, + VAImage *image); + +VAStatus dmd_DestroyImage(VADriverContextP ctx, VAImageID image); + +VAStatus dmd_GetImage(VADriverContextP ctx, VASurfaceID surface, int x, int y, + unsigned int width, unsigned int height, VAImageID image); + +/* ---- 跨文件内部辅助(均要求调用方已持 drv->lock) ---- */ + +struct dmd_surface *dmd_find_surface_locked(struct dmd_driver *drv, + VASurfaceID id); +struct dmd_context *dmd_find_context_locked(struct dmd_driver *drv, + VAContextID id); +struct dmd_buffer *dmd_find_buffer_locked(struct dmd_driver *drv, + VABufferID id); +struct dmd_image *dmd_find_image_locked(struct dmd_driver *drv, VAImageID id); + +/* 隐式同步一个 surface(GetImage 在 surface 未就绪时用)。 + * 要求调用方已持锁;内部会临时放锁做 IO,返回时仍持锁 —— + * 调用方必须重新查找所有缓存的对象指针。 */ +VAStatus dmd_surface_sync_locked(struct dmd_driver *drv, VASurfaceID surface, + int timeout_ms); + +/* 释放一个 surface 槽位持有的资源(不加锁)。 */ +void dmd_surface_reset_locked(struct dmd_surface *s); +/* 释放一个 context 槽位持有的资源,含 daemon 会话(不加锁;会做 socket 关闭)。 */ +void dmd_context_reset_locked(struct dmd_context *c); + +/* 按 surface 几何填一个 VAImage 描述(不含 image_id/buf)。 + * 这是 1088-vs-1080 那处几何的唯一真源,derive 与 create 共用。 */ +void dmd_fill_image_geometry(VAImage *img, unsigned int disp_width, + unsigned int disp_height, unsigned int stride, + unsigned int slice_height); + +/* 对齐辅助 */ +unsigned int dmd_align_up(unsigned int v, unsigned int align); + +/* ---- profiles.c 内部辅助 ---- */ + +/* 该 profile 是否由本驱动支持(即 Android 侧 MediaCodec 有对应硬件解码器)。 */ +int dmd_profile_supported(VAProfile profile); + +/* profile → 协议 codec id(DMD_CODEC_*)。不支持的 profile 返回 -1。 */ +int dmd_profile_to_codec(VAProfile profile); + +/* ---- h264_bitstream.c ---- */ + +/* 从 VA-API 的 pic param 反向合成带 4 字节起始码的 SPS / PPS NALU。 + * VA-API 从不传递参数集原始比特流,而 daemon 靠起始码识别 NAL 类型把它们 + * 累积成 codec-specific data,所以必须自己写出来。 + * 返回写入 out 的字节数,0 表示失败(含 out_cap 不足)。 */ +/* HEVC 参数集合成(hevc_bitstream.c)。 + * + * dmd_hevc_can_build 返回 0 表示这个码流无法合成(VA-API 缺少必要信息), + * 调用方应让上层回落软解,而不是产出坏画面。 */ +int dmd_hevc_can_build(const VAPictureParameterBufferHEVC *pp); +size_t dmd_hevc_build_vps_nalu(const VAPictureParameterBufferHEVC *pp, + VAProfile profile, + unsigned char *out, size_t cap); +size_t dmd_hevc_build_sps_nalu(const VAPictureParameterBufferHEVC *pp, + VAProfile profile, + unsigned char *out, size_t cap); +size_t dmd_hevc_build_pps_nalu(const VAPictureParameterBufferHEVC *pp, + unsigned char *out, size_t cap); + +size_t dmd_h264_build_sps_nalu(const VAPictureParameterBufferH264 *pp, + VAProfile profile, unsigned int disp_width, + unsigned int disp_height, unsigned char *out, + size_t out_cap); +size_t dmd_h264_build_pps_nalu(const VAPictureParameterBufferH264 *pp, + const VAIQMatrixBufferH264 *iq, int have_iq, + const VASliceParameterBufferH264 *sp, + unsigned int def_l0_minus1, + unsigned int def_l1_minus1, + unsigned char *out, size_t out_cap); + +#endif /* DMD_DRIVER_H */ diff --git a/codec/vaapi/src/export.c b/codec/vaapi/src/export.c new file mode 100644 index 0000000..23c5f58 --- /dev/null +++ b/codec/vaapi/src/export.c @@ -0,0 +1,159 @@ +/* vaExportSurfaceHandle:把 surface 导出成 dmabuf(DRM_PRIME_2)。 + * + * 为什么必须实现:**Firefox 取帧只走这条路**。 + * `FFmpegVideoDecoder::CreateImageVAAPI`(FFmpegVideoDecoder.cpp:1649)拿到 + * 解码帧后立刻调 `GetVAAPISurfaceDescriptor` → `vaExportSurfaceHandle`, + * 失败就返回 `NS_ERROR_DOM_MEDIA_DECODE_ERR`,播放器随即 ProcessFlush() + * 并重建成**软解**。整个过程没有任何错误日志,也**没有回退到拷贝的路径** —— + * 症状就是"硬解出 1 帧然后永久软解",极难定位(我们靠给未实现桩加日志才发现)。 + * + * ffmpeg 命令行不需要它:`hwdownload` 走 vaDeriveImage + vaMapBuffer。 + * 所以此前一直"ffmpeg 全绿、浏览器不动"。 + * + * 这不是零拷贝。MediaCodec 那块输出内存我们拿不到 fd(容器 ION 不可用、 + * 无 /dev/dma_heap、NDK 也不暴露输出缓冲的 fd)。做法是 surface 本身就分配在 + * msm_drm 的 dumb buffer 里(见 decode.c 的 surface_alloc_dumb), + * daemon 回传的帧直接拷进这块可导出内存 —— 拷贝次数和原来一样, + * 但多了"能被 GL/合成器导入"这个关键能力。 + */ + +#include +#include /* O_CLOEXEC —— drm.h 的 DRM_CLOEXEC 是它的别名 */ +#include +#include + +#include +#include + +#include "driver.h" + +VAStatus dmd_ExportSurfaceHandle(VADriverContextP ctx, VASurfaceID surface_id, + uint32_t mem_type, uint32_t flags, + void *descriptor) +{ + struct dmd_driver *drv = dmd_get_driver(ctx); + + if (!drv || !descriptor) + return VA_STATUS_ERROR_INVALID_PARAMETER; + + /* 只支持 DRM_PRIME_2。Firefox 传的正是这个;老的 DRM_PRIME(v1) + * 结构不同,不声明支持比给个错结构安全。 */ + if (mem_type != VA_SURFACE_ATTRIB_MEM_TYPE_DRM_PRIME_2) { + dmd_log("ExportSurfaceHandle: 不支持的 mem_type=0x%x\n", mem_type); + return VA_STATUS_ERROR_UNSUPPORTED_MEMORY_TYPE; + } + + /* 导出前帧必须已经在 surface 里:Firefox 是在拿到解码帧之后才导出的, + * 但 VA-API 不保证这一点,稳妥起见先等就绪(内部自行加锁)。 */ + VAStatus wait = dmd_surface_wait(drv, surface_id); + if (wait != VA_STATUS_SUCCESS) + return wait; + + pthread_mutex_lock(&drv->lock); + struct dmd_surface *s = dmd_find_surface_locked(drv, surface_id); + if (!s) { + pthread_mutex_unlock(&drv->lock); + return VA_STATUS_ERROR_INVALID_SURFACE; + } + + if (!s->exportable || !s->dumb_handle || s->dumb_drm_fd < 0) { + /* 分配时回落成普通 heap 了(dumb buffer 不可用)。 + * 明确报不支持,别给出一个假的 fd。 */ + pthread_mutex_unlock(&drv->lock); + dmd_log("ExportSurfaceHandle: surface %u 不是可导出内存\n", + (unsigned)surface_id); + return VA_STATUS_ERROR_UNSUPPORTED_MEMORY_TYPE; + } + + unsigned int stride = s->stride; + unsigned int slice_h = s->slice_height; + unsigned int disp_w = s->width; + unsigned int disp_h = s->height; + uint32_t handle = s->dumb_handle; + int drm_fd = s->dumb_drm_fd; + size_t total = s->dumb_size; + pthread_mutex_unlock(&drv->lock); + + /* 导出 fd 时不持锁:ioctl 是内核调用,且调用方拿到 fd 后由它负责 close。 */ + struct drm_prime_handle prime; + memset(&prime, 0, sizeof(prime)); + prime.handle = handle; + /* DRM_CLOEXEC 就是 O_CLOEXEC 的别名(drm.h),用它避免额外包含 fcntl.h。 + * fd 必须 CLOEXEC:驱动跑在浏览器进程里,泄漏到子进程是安全问题。 */ + prime.flags = DRM_CLOEXEC; + if (ioctl(drm_fd, DRM_IOCTL_PRIME_HANDLE_TO_FD, &prime) != 0) { + dmd_log("ExportSurfaceHandle: PRIME_HANDLE_TO_FD 失败\n"); + return VA_STATUS_ERROR_OPERATION_FAILED; + } + + VADRMPRIMESurfaceDescriptor *desc = + (VADRMPRIMESurfaceDescriptor *)descriptor; + memset(desc, 0, sizeof(*desc)); + + desc->fourcc = VA_FOURCC_NV12; + desc->width = disp_w; + desc->height = disp_h; + + /* 单个 dmabuf object 承载 Y 与 UV 两个平面。 */ + desc->num_objects = 1; + desc->objects[0].fd = prime.fd; + desc->objects[0].size = (uint32_t)total; + desc->objects[0].drm_format_modifier = DRM_FORMAT_MOD_LINEAR; + + /* Firefox 传 VA_EXPORT_SURFACE_SEPARATE_LAYERS,要求 Y / UV 各成一层。 + * 合并成一层(NV12 单 layer)只有在对方传 COMPOSED_LAYERS 时才合适。 */ + if (flags & VA_EXPORT_SURFACE_COMPOSED_LAYERS) { + desc->num_layers = 1; + desc->layers[0].drm_format = DRM_FORMAT_NV12; + desc->layers[0].num_planes = 2; + desc->layers[0].object_index[0] = 0; + desc->layers[0].offset[0] = 0; + desc->layers[0].pitch[0] = stride; + desc->layers[0].object_index[1] = 0; + desc->layers[0].offset[1] = (uint32_t)stride * slice_h; + desc->layers[0].pitch[1] = stride; + } else { + desc->num_layers = 2; + /* Y 平面:8bpp 单通道 */ + desc->layers[0].drm_format = DRM_FORMAT_R8; + desc->layers[0].num_planes = 1; + desc->layers[0].object_index[0] = 0; + desc->layers[0].offset[0] = 0; + desc->layers[0].pitch[0] = stride; + /* UV 平面:交织的两通道,宽度减半(每个采样 2 字节, + * 所以 pitch 与 Y 相同)。offset 用 **slice_height** 不是显示高 —— + * 与 VAImage.offsets[1] 同一个坑。 */ + desc->layers[1].drm_format = DRM_FORMAT_GR88; + desc->layers[1].num_planes = 1; + desc->layers[1].object_index[0] = 0; + desc->layers[1].offset[0] = (uint32_t)stride * slice_h; + desc->layers[1].pitch[0] = stride; + } + + /* 诊断黑帧:DMD_VA_LUMA=1 时抽样算 Y 平面亮度均值并打进日志。 + * + * 为什么需要在这里量:黑帧只在浏览器路径上出现,而 ffmpeg 路径 + * (六条流回归)永远看不到 —— 它不会像浏览器那样中途重启解码器。 + * 导出这一刻是驱动能看到最终像素的最后位置。 + * 纯诊断,默认关闭,不影响正常路径。 */ + if (getenv("DMD_VA_LUMA")) { + const unsigned char *y = s->data; + if (y && s->data_size >= (size_t)stride * 16) { + double sum = 0; int cnt = 0; + size_t lim = (size_t)stride * slice_h; + if (lim > s->data_size) lim = s->data_size; + for (size_t k = 0; k < lim; k += 1499) { sum += y[k]; cnt++; } + double mean = cnt ? sum / cnt : 0; + dmd_log("亮度: surface=%u 均值 %.1f%s\n", + (unsigned)surface_id, mean, + mean < 20.0 ? " ← 黑帧!" : ""); + } + } + + dmd_log("ExportSurfaceHandle: surface=%u -> fd=%d %ux%u stride=%u " + "uv_offset=%u layers=%u\n", + (unsigned)surface_id, prime.fd, disp_w, disp_h, stride, + (unsigned)(stride * slice_h), desc->num_layers); + + return VA_STATUS_SUCCESS; +} diff --git a/codec/vaapi/src/h264_bitstream.c b/codec/vaapi/src/h264_bitstream.c new file mode 100644 index 0000000..d2db7e4 --- /dev/null +++ b/codec/vaapi/src/h264_bitstream.c @@ -0,0 +1,462 @@ +/* 从 VA-API 参数缓冲反向合成 H.264 SPS/PPS 比特流 + * + * ── 为什么需要这个 ──────────────────────────────────────── + * daemon 侧是 MediaCodec,它要的是标准 Annex B 码流,靠起始码定位 + * nal_unit_header 把 SPS/PPS 识别为 codec config(decode-daemon.c:461-489)。 + * 但 ffmpeg 的 hwaccel 不把 SPS/PPS 交给 driver —— 它自己解析掉了 + * (h264dec.c:699 / :717 的 case H264_NAL_SPS / PPS),只把 VCL NALU + * 经 decode_slice 传下来。所以参数集必须由我们从 + * VAPictureParameterBufferH264 反向合成。 + * + * ── 好消息:slice 不用重建 ──────────────────────────────── + * 主会话核实(research/M-1-forwarding-spec.md)并经本单元复核: + * h264dec.c:674 FF_HW_CALL(avctx, decode_slice, nal->raw_data, nal->raw_size) + * h2645_parse.c:92/145 nal->raw_data = src,src 指向起始码之后 + * h2645_parse.h:102-107 raw_data 保留 emulation prevention 字节(未去转义) + * vaapi_h264.c:386-388 这对 buffer/size 原样进 slice data buffer + * vaapi_h264.c:349-350 slice_data_offset=0、slice_data_flag=VA_SLICE_DATA_FLAG_ALL + * 即 slice data 里是**完整原始 NALU(含 NALU header 与 slice header)**, + * 只缺起始码。决定性的旁证是 vaapi_h264.c:351 的 + * slice_data_bit_offset = get_bits_count(&sl->gb) —— 它是 slice header + * **结束**的 bit 位置,这个字段能存在就说明 slice header 在 buffer 里。 + * + * 所以我们不需要重建 slice header,也就绕开了参考列表重排序与 MMCO 命令的 + * 反推(那是欠定问题:VAPictureH264 数组给的是最终列表而非重排序命令)。 + * 转发 slice 只需前置 4 字节 00 00 00 01。 + * + * ── 仍然要猜的字段 ──────────────────────────────────────── + * profile_idc / level_idc / VUI 在 VA-API 里不存在。处理见下面各处注释: + * profile_idc 由 VAProfile 映射,level_idc 按分辨率与 DPB 查表推一个刚好够用的。 + */ + +#include + +#include "driver.h" +#include "bitstream.h" + +/* 比特写入原语与 EPB 转义已提取到 bitstream.c,与 HEVC 共用。 */ + +/* ------------------------------------------------------------ 字段推导 */ + +/* profile_idc:VA-API 没有这个字段,只能从 VAProfile 映射。 + * + * ⚠️ 关键约束:profile_idc >= 100 时 SPS 比特流里才出现 chroma_format_idc / + * bit_depth_* / seq_scaling_matrix_present_flag 这一组字段。所以 profile_idc + * 与我们是否写这组字段必须自洽,否则解析器整体错位、码流报废。 + * + * 策略:只要 pic param 里的 chroma/bit_depth 是非默认值,就必须用 High(100) + * 才能表达它们;否则按 VAProfile 映射。ffmpeg 的 H264High 是最常见情况。 + */ +static unsigned int derive_profile_idc(VAProfile profile, + const VAPictureParameterBufferH264 *pp) +{ + unsigned int chroma = pp->seq_fields.bits.chroma_format_idc; + unsigned int bd_luma = pp->bit_depth_luma_minus8; + unsigned int bd_chroma = pp->bit_depth_chroma_minus8; + + /* 非 4:2:0 或非 8-bit 只能用 High 系列表达。 */ + if (chroma != 1 || bd_luma != 0 || bd_chroma != 0) + return 100; + /* transform_8x8 是 High profile 独有的工具。 */ + if (pp->pic_fields.bits.transform_8x8_mode_flag) + return 100; + + switch (profile) { + case VAProfileH264ConstrainedBaseline: + return 66; + case VAProfileH264Main: + return 77; + case VAProfileH264High: + default: + return 100; + } +} + +/* level_idc:VA-API 完全没有。填过高的风险是 MediaCodec 按 level 预留过大 + * 缓冲甚至拒绝配置;填过低的风险是解码器认为码流超规格。 + * + * 按 Annex A 的 MaxMBPS/MaxFS 表推一个**刚好够用**的 level,比填固定值稳。 + * 只用帧尺寸推(帧率未知),所以取每个 level 的 MaxFS(帧大小上限,单位宏块)。 + */ +static unsigned int derive_level_idc(unsigned int mbs_wide, + unsigned int mbs_high) +{ + unsigned int fs = mbs_wide * mbs_high; /* 帧大小,宏块数 */ + + /* Annex A 表 A-1 的 MaxFS 列。level 值是 idc(level×10)。 */ + static const struct { + unsigned int max_fs; + unsigned int idc; + } tbl[] = { + { 99, 10 }, /* 1.0 QCIF */ + { 396, 11 }, /* 1.1 */ + { 396, 12 }, /* 1.2 */ + { 396, 20 }, /* 2.0 CIF */ + { 792, 21 }, /* 2.1 */ + { 1620, 22 }, /* 2.2 SD */ + { 1620, 30 }, /* 3.0 */ + { 3600, 31 }, /* 3.1 720p */ + { 5120, 32 }, /* 3.2 */ + { 8192, 40 }, /* 4.0 1080p */ + { 8192, 41 }, /* 4.1 */ + { 8704, 42 }, /* 4.2 */ + { 22080, 50 }, /* 5.0 */ + { 36864, 51 }, /* 5.1 4K */ + { 36864, 52 }, /* 5.2 */ + { 139264, 60 }, /* 6.0 8K */ + }; + + for (size_t i = 0; i < sizeof(tbl) / sizeof(tbl[0]); i++) { + if (fs <= tbl[i].max_fs) + return tbl[i].idc; + } + return 62; /* 超出表范围,给最高 */ +} + +/* ------------------------------------------------------------ SPS 序列化 */ + +/* 按 ISO/IEC 14496-10 §7.3.2.1.1 的语法顺序写 seq_parameter_set_rbsp。 + * 每个字段标注来源:A = VA-API 有、B = 可推导、C = 只能填默认值。 */ +static size_t build_sps_rbsp(const VAPictureParameterBufferH264 *pp, + VAProfile profile, unsigned int disp_width, + unsigned int disp_height, unsigned char *out, + size_t out_cap) +{ + struct dmd_bitwriter bw; + dmd_bw_init(&bw, out, out_cap); + + unsigned int mbs_wide = (unsigned int)pp->picture_width_in_mbs_minus1 + 1; + unsigned int mbs_high = (unsigned int)pp->picture_height_in_mbs_minus1 + 1; + unsigned int profile_idc = derive_profile_idc(profile, pp); + unsigned int frame_mbs_only = pp->seq_fields.bits.frame_mbs_only_flag; + + /* C:profile_idc 由 VAProfile 推 */ + dmd_bw_put_bits(&bw, profile_idc, 8); + /* C:constraint_set0..5 + 2 位 reserved。 + * + * ⚠️ 这 8 位不能随便填:h264_ps.c:677-689 的 more_rbsp_data_in_pps() + * 在 `profile_idc ∈ {66,77,88} 且 (constraint_set_flags & 7) != 0` 时 + * 返回 0,**PPS 解析会跳过尾部**的 transform_8x8_mode_flag / + * pic_scaling_matrix_present_flag / second_chroma_qp_index_offset + * (调用点 h264_ps.c:795)。 + * + * 所以只在 ConstrainedBaseline 上置 set0|set1(那是它的定义), + * 其余一律 0 —— 我们需要 PPS 尾部能被读到。 */ + unsigned int constraints = 0; + if (profile_idc == 66 && profile == VAProfileH264ConstrainedBaseline) { + /* set0 (bit7) + set1 (bit6):baseline 且 constrained */ + constraints = 0xC0; + } + dmd_bw_put_bits(&bw, constraints, 8); + /* C:level_idc 按帧尺寸推 */ + dmd_bw_put_bits(&bw, derive_level_idc(mbs_wide, mbs_high), 8); + /* C:seq_parameter_set_id 固定 0(slice header 经 PPS 间接引用, + * 而 PPS 里我们也写 0,两边自洽即可) */ + dmd_bw_put_ue(&bw, 0); + + if (profile_idc == 100 || profile_idc == 110 || profile_idc == 122 || + profile_idc == 244 || profile_idc == 44 || profile_idc == 83 || + profile_idc == 86 || profile_idc == 118 || profile_idc == 128) { + /* A:这一组只在 High 系列出现,取值必须与 profile_idc 的选择自洽 */ + dmd_bw_put_ue(&bw, pp->seq_fields.bits.chroma_format_idc); + if (pp->seq_fields.bits.chroma_format_idc == 3) { + /* A:VA-API 的 residual_colour_transform_flag 即新标准的 + * separate_colour_plane_flag */ + dmd_bw_put_flag(&bw, pp->seq_fields.bits.residual_colour_transform_flag); + } + dmd_bw_put_ue(&bw, pp->bit_depth_luma_minus8); /* A */ + dmd_bw_put_ue(&bw, pp->bit_depth_chroma_minus8); /* A */ + /* C:qpprime_y_zero_transform_bypass_flag,填 0(仅无损编码用) */ + dmd_bw_put_flag(&bw, 0); + /* B:不写 SPS 级缩放矩阵。VAIQMatrixBufferH264 给的是**最终**矩阵, + * 反推 delta_scale 序列需要区分它来自 SPS 还是 PPS 的 fallback 规则, + * 无法判定。改为把矩阵放进 PPS(见 build_pps_rbsp),那里语义明确。 */ + dmd_bw_put_flag(&bw, 0); + } + + dmd_bw_put_ue(&bw, pp->seq_fields.bits.log2_max_frame_num_minus4); /* A */ + dmd_bw_put_ue(&bw, pp->seq_fields.bits.pic_order_cnt_type); /* A */ + + if (pp->seq_fields.bits.pic_order_cnt_type == 0) { + /* A */ + dmd_bw_put_ue(&bw, pp->seq_fields.bits.log2_max_pic_order_cnt_lsb_minus4); + } else if (pp->seq_fields.bits.pic_order_cnt_type == 1) { + /* A */ + dmd_bw_put_flag(&bw, pp->seq_fields.bits.delta_pic_order_always_zero_flag); + /* C:offset_for_non_ref_pic / offset_for_top_to_bottom_field / + * num_ref_frames_in_pic_order_cnt_cycle 与 offset_for_ref_frame[] + * 在 VA-API 里完全没有。pic_order_cnt_type==1 极少见(ffmpeg 生成的 + * 码流几乎都是 type 0 或 2),这里填最简形式:cycle 长度 0。 + * 若真遇到 type 1 码流,POC 会算错 → 帧序错乱。 */ + dmd_bw_put_se(&bw, 0); + dmd_bw_put_se(&bw, 0); + dmd_bw_put_ue(&bw, 0); + } + + dmd_bw_put_ue(&bw, pp->num_ref_frames); /* A */ + /* A */ + dmd_bw_put_flag(&bw, pp->seq_fields.bits.gaps_in_frame_num_value_allowed_flag); + dmd_bw_put_ue(&bw, pp->picture_width_in_mbs_minus1); /* A */ + /* B:⚠️ VA-API 给的是**帧高**宏块数(vaapi_h264.c:251 填的是 + * h->mb_width/mb_height-1,而 h264_ps.c:457 解析时做过 + * mb_height *= 2 - frame_mbs_only_flag)。比特流里这个字段是 + * map units 数,交错流时是帧高的一半,必须换算回去。 + * 直接原值写入会让交错码流的高度算成两倍。 */ + dmd_bw_put_ue(&bw, mbs_high / (frame_mbs_only ? 1u : 2u) - 1); + dmd_bw_put_flag(&bw, frame_mbs_only); /* A */ + if (!frame_mbs_only) { + /* A */ + dmd_bw_put_flag(&bw, pp->seq_fields.bits.mb_adaptive_frame_field_flag); + } + dmd_bw_put_flag(&bw, pp->seq_fields.bits.direct_8x8_inference_flag); /* A */ + + /* B:frame_cropping 由"宏块对齐后的尺寸"与"实际显示尺寸"之差推出。 + * 这是 1088-vs-1080 在码流侧的对应物:1080 不是 16 的倍数, + * 所以 SPS 里编码高度是 1088,靠 crop 砍掉 8 行。 + * 单位:crop offset 的单位是"色度采样",4:2:0 下垂直方向要再除 2, + * 且 frame_mbs_only=0 时垂直单位再乘 2。 */ + unsigned int coded_w = mbs_wide * 16; + unsigned int coded_h = mbs_high * 16 * (frame_mbs_only ? 1 : 2); + unsigned int crop_right = 0, crop_bottom = 0; + unsigned int chroma = pp->seq_fields.bits.chroma_format_idc; + /* SubWidthC/SubHeightC:4:2:0 → 2/2,4:2:2 → 2/1,4:4:4 → 1/1 */ + unsigned int sub_w = (chroma == 3) ? 1 : 2; + unsigned int sub_h = (chroma == 1) ? 2 : 1; + unsigned int unit_x = sub_w; + unsigned int unit_y = sub_h * (frame_mbs_only ? 1 : 2); + + if (disp_width > 0 && disp_width < coded_w) + crop_right = (coded_w - disp_width) / unit_x; + if (disp_height > 0 && disp_height < coded_h) + crop_bottom = (coded_h - disp_height) / unit_y; + + if (crop_right || crop_bottom) { + dmd_bw_put_flag(&bw, 1); + dmd_bw_put_ue(&bw, 0); /* crop_left */ + dmd_bw_put_ue(&bw, crop_right); + dmd_bw_put_ue(&bw, 0); /* crop_top */ + dmd_bw_put_ue(&bw, crop_bottom); + } else { + dmd_bw_put_flag(&bw, 0); + } + + /* C:VUI 只写 bitstream_restriction 一段,其余(色彩空间、SAR、帧率) + * 仍然缺失 —— VA-API 不提供它们,解码器用默认值:SAR 1:1、 + * 色彩空间 unspecified。对 NV12 输出,几何与像素值都不受影响 + * (显示区域由我们按 crop 处理)。 + * + * 为什么必须写 bitstream_restriction: + * 没有它时 max_num_reorder_frames 的缺省值等于 DPB 上限(§E.2.1), + * MediaCodec 只能按最坏情况攥帧 —— 实测滞后 4 个输入单元才吐首帧 + * (无 B 帧的流滞后 1,证明攥帧确实来自重排假设)。 + * 而浏览器里的 ffmpeg 稳态只保持 3 帧在飞(H.264 重排深度决定), + * 送完第 3 帧就阻塞在 vaSyncSurface 等第 1 帧 → 双方差一帧 → 死锁 → + * 驱动兜底 flush(不可逆)→ 会话作废 → 浏览器永久回落软解。 + * 实测 Firefox 140 因此只硬解出 1 帧。 + * + * ⚠️ 不要把 max_num_reorder_frames 写 0(曾经试过,已否决): + * 那是谎报流的重排需求,会破坏语义 —— 软解侧实测 150 帧掉到 115 帧。 + * 这里用 num_ref_frames 作上界:它是 SPS 自带的参考帧数上限, + * 重排深度不可能超过它,所以这是**真实且不放大**的约束。 */ + dmd_bw_put_flag(&bw, 1); /* vui_parameters_present_flag */ + + dmd_bw_put_flag(&bw, 0); /* aspect_ratio_info_present_flag */ + dmd_bw_put_flag(&bw, 0); /* overscan_info_present_flag */ + dmd_bw_put_flag(&bw, 0); /* video_signal_type_present_flag */ + dmd_bw_put_flag(&bw, 0); /* chroma_loc_info_present_flag */ + dmd_bw_put_flag(&bw, 0); /* timing_info_present_flag */ + dmd_bw_put_flag(&bw, 0); /* nal_hrd_parameters_present_flag */ + dmd_bw_put_flag(&bw, 0); /* vcl_hrd_parameters_present_flag */ + dmd_bw_put_flag(&bw, 0); /* pic_struct_present_flag */ + + dmd_bw_put_flag(&bw, 1); /* bitstream_restriction_flag */ + dmd_bw_put_flag(&bw, 1); /* motion_vectors_over_pic_boundaries_flag: + * 缺省即 1,写 1 不改变语义 */ + dmd_bw_put_ue(&bw, 0); /* max_bytes_per_pic_denom:0 = 无限制 */ + dmd_bw_put_ue(&bw, 0); /* max_bits_per_mb_denom:0 = 无限制 */ + /* log2_max_mv_length_horizontal/vertical:写规范允许的最大值 15, + * 等价于不施加额外限制。 */ + dmd_bw_put_ue(&bw, 15); + dmd_bw_put_ue(&bw, 15); + dmd_bw_put_ue(&bw, pp->num_ref_frames); /* max_num_reorder_frames */ + dmd_bw_put_ue(&bw, pp->num_ref_frames); /* max_dec_frame_buffering */ + + dmd_bw_rbsp_trailing(&bw); + + return bw.overflow ? 0 : dmd_bw_bytes(&bw); +} + +/* ------------------------------------------------------------ PPS 序列化 */ + +/* 按 §7.3.2.2 写 pic_parameter_set_rbsp。 */ +static size_t build_pps_rbsp(const VAPictureParameterBufferH264 *pp, + const VAIQMatrixBufferH264 *iq, int have_iq, + int have_sp, unsigned int sp_l0_minus1, + unsigned int sp_l1_minus1, unsigned char *out, + size_t out_cap) +{ + struct dmd_bitwriter bw; + dmd_bw_init(&bw, out, out_cap); + + dmd_bw_put_ue(&bw, 0); /* C:pic_parameter_set_id,与 slice header 引用的一致 */ + dmd_bw_put_ue(&bw, 0); /* C:seq_parameter_set_id,与 SPS 里写的一致 */ + + dmd_bw_put_flag(&bw, pp->pic_fields.bits.entropy_coding_mode_flag); /* A */ + /* A:VA-API 的 pic_order_present_flag 即 + * bottom_field_pic_order_in_frame_present_flag */ + dmd_bw_put_flag(&bw, pp->pic_fields.bits.pic_order_present_flag); + /* B:FMO 不支持(VA-API 头文件明确 "FMO is not supported"), + * 所以 slice group 数恒为 1。 */ + dmd_bw_put_ue(&bw, 0); + + /* B:num_ref_idx_l0/l1_default_active_minus1。 + * + * 照抄**当前帧** slice param 的 num_ref_idx_l0/l1_active_minus1, + * 并且每当这两个值变化就重发 PPS(见 decode.c 的 h264_send_param_sets)。 + * + * 为什么照抄是对的:VA-API 给的是"该 slice 的生效值"。 + * - 对未带 num_ref_idx_active_override_flag 的 slice,生效值**就等于** + * PPS 默认值 → 照抄即得真值 + * - 对带 override 的 slice,PPS 默认值对它不起作用 → 填什么都无妨 + * 两种情况都正确,且不需要区分 override_flag(VA-API 并未暴露它)。 + * + * ⚠️ 两条不能走的歧路,都已实测证伪: + * 1) 取**首个 IDR** 的 slice param —— I slice 没有这个语法元素,恒为 0, + * 于是非 override 的 B slice 只用 1 个参考帧。这是旧实现的 bug。 + * 2) 用 num_ref_frames-1 当"安全上界" —— **l1 一位都不能偏大**。 + * 单变量实测(另一值保持真值 l0=2/l1=0): + * l0_m1 = 0,1 → 错;2,3,4,15 → 对(l0 可偏大) + * l1_m1 = 0 → 对;1,2,3 → 全错(l1 不可偏大) + * 因为 l1_default_active 决定非 override B slice 里 ref_idx_l1 的 + * **熵解码码长**,改了它就是语法解析层错位,不是预测质量问题。 + * + * ── 实测修正(浏览器黑屏的真正原因)───────────────────── + * 上面"照抄当前帧生效值"的推理漏了一种情况:**带 override 的 slice**。 + * 对它们 VA-API 给的是 override 后的值,与 PPS 默认值无关, + * 于是我们会写出一个错的默认值,而**其他**非 override slice 会用它。 + * + * 实测证据:test1080.h264 的真实 PPS 恒为 l0=2 l1=0(原码流只有一份 + * PPS),而驱动送出了 5 种变体:l0 取 0/1/2/3、l1 取 0/1。 + * 其中只有 l0=2 l1=0 那份是对的。会话开头送的恰好是 l0=0 那份, + * 于是从第 4 帧起(前 3 帧是流水线里已解好的)画面全黑到下一个 IDR —— + * 每轮循环黑 25 帧左右,就是用户看到的"每隔一段黑屏一次"。 + * + * 修正办法:**取见过的最大 l0、最小 l1**。 + * - l0 可以偏大(已实测:l0_m1=2,3,4,15 都对),所以取最大值安全, + * 且能覆盖真实默认值(真实值必 <= 某个 slice 的生效值)。 + * - l1 一位都不能偏大,所以取最小值 —— 非 override slice 报的就是 + * 真实默认值,而 override slice 只会报得更大。 + * 这样多轮之后收敛到唯一一份 PPS,也顺带消除了无意义的反复重送。 */ + unsigned int def_l0 = have_sp ? sp_l0_minus1 : 0; + unsigned int def_l1 = have_sp ? sp_l1_minus1 : 0; + (void)pp; + if (def_l0 > 31) + def_l0 = 31; + if (def_l1 > 31) + def_l1 = 31; + dmd_bw_put_ue(&bw, def_l0); + dmd_bw_put_ue(&bw, def_l1); + + dmd_bw_put_flag(&bw, pp->pic_fields.bits.weighted_pred_flag); /* A */ + dmd_bw_put_bits(&bw, pp->pic_fields.bits.weighted_bipred_idc, 2); /* A */ + dmd_bw_put_se(&bw, pp->pic_init_qp_minus26); /* A */ + dmd_bw_put_se(&bw, pp->pic_init_qs_minus26); /* A */ + dmd_bw_put_se(&bw, pp->chroma_qp_index_offset); /* A */ + /* A */ + dmd_bw_put_flag(&bw, pp->pic_fields.bits.deblocking_filter_control_present_flag); + dmd_bw_put_flag(&bw, pp->pic_fields.bits.constrained_intra_pred_flag); /* A */ + dmd_bw_put_flag(&bw, pp->pic_fields.bits.redundant_pic_cnt_present_flag); /* A */ + + /* PPS 的可选尾部:只在需要表达 transform_8x8 或缩放矩阵时才写。 + * 注意这三个字段是"要么全写要么全不写"(more_rbsp_data 判定)。 + * + * 前提:SPS 侧的 profile_idc / constraint_set 组合必须允许解码器读到 + * 这段尾部(见 build_sps_rbsp 里 constraint_set 的说明)。我们只在 + * ConstrainedBaseline 上置 constraint 位,而 ConstrainedBaseline 不允许 + * transform_8x8,所以 need_tail 与"尾部可读"这两件事不会冲突。 */ + int need_tail = pp->pic_fields.bits.transform_8x8_mode_flag || have_iq || + pp->second_chroma_qp_index_offset != + pp->chroma_qp_index_offset; + + if (need_tail) { + dmd_bw_put_flag(&bw, pp->pic_fields.bits.transform_8x8_mode_flag); /* A */ + + /* B:缩放矩阵。VAIQMatrixBufferH264 给的是最终绝对值矩阵, + * 而码流里是相对 fallback 的差分(delta_scale)。 + * + * 这里选择**不写**(pic_scaling_matrix_present_flag = 0): + * 反推 delta_scale 需要知道 fallback 基准(规则 A 用默认矩阵、 + * 规则 B 用前一个矩阵),而"这个矩阵到底来自 SPS 还是 PPS" + * 在 VA-API 层面无法判定 —— 猜错会让整张矩阵偏移。 + * + * 后果:若码流用了非默认缩放矩阵,反量化系数会与编码端不一致, + * 表现为**轻微失真而非花屏**(矩阵只影响系数缩放,不影响熵解码 + * 与预测结构)。实测 ffmpeg 默认编码不启用自定义矩阵, + * 这条路径在常见码流上不触发。 */ + dmd_bw_put_flag(&bw, 0); + + dmd_bw_put_se(&bw, pp->second_chroma_qp_index_offset); /* A */ + } + + dmd_bw_rbsp_trailing(&bw); + + (void)iq; + return bw.overflow ? 0 : dmd_bw_bytes(&bw); +} + +/* ------------------------------------------------------------ 对外接口 */ + +/* 组装一个带起始码的 NALU:00 00 00 01 + nal_header + 转义后的 RBSP。 + * nal_ref_idc 对参数集固定 3(最高优先级,标准推荐)。 */ +static size_t emit_nalu(unsigned int nal_ref_idc, unsigned int nal_unit_type, + const unsigned char *rbsp, size_t rbsp_len, + unsigned char *out, size_t out_cap) +{ + if (out_cap < 5) + return 0; + + out[0] = 0x00; + out[1] = 0x00; + out[2] = 0x00; + out[3] = 0x01; + out[4] = (unsigned char)(((nal_ref_idc & 0x3) << 5) | + (nal_unit_type & 0x1F)); + + size_t n = dmd_rbsp_escape(rbsp, rbsp_len, out + 5, out_cap - 5); + if (n == 0 && rbsp_len > 0) + return 0; + + return 5 + n; +} + +size_t dmd_h264_build_sps_nalu(const VAPictureParameterBufferH264 *pp, + VAProfile profile, unsigned int disp_width, + unsigned int disp_height, unsigned char *out, + size_t out_cap) +{ + unsigned char rbsp[256]; + size_t n = build_sps_rbsp(pp, profile, disp_width, disp_height, rbsp, + sizeof(rbsp)); + if (n == 0) + return 0; + return emit_nalu(3, 7 /* SPS */, rbsp, n, out, out_cap); +} + +size_t dmd_h264_build_pps_nalu(const VAPictureParameterBufferH264 *pp, + const VAIQMatrixBufferH264 *iq, int have_iq, + const VASliceParameterBufferH264 *sp, + unsigned int def_l0_minus1, + unsigned int def_l1_minus1, + unsigned char *out, size_t out_cap) +{ + unsigned char rbsp[256]; + /* l0/l1 由调用方推导后传入,**不能**直接取 sp 里的生效值 —— + * 带 override_flag 的 slice 其生效值与 PPS 默认值无关。 + * 见 decode.c 里的推导说明。 */ + size_t n = build_pps_rbsp(pp, iq, have_iq, sp != NULL, + def_l0_minus1, def_l1_minus1, rbsp, + sizeof(rbsp)); + if (n == 0) + return 0; + return emit_nalu(3, 8 /* PPS */, rbsp, n, out, out_cap); +} diff --git a/codec/vaapi/src/hevc_bitstream.c b/codec/vaapi/src/hevc_bitstream.c new file mode 100644 index 0000000..338ad3d --- /dev/null +++ b/codec/vaapi/src/hevc_bitstream.c @@ -0,0 +1,362 @@ +/* 从 VA-API 的 HEVC 参数缓冲合成 VPS/SPS/PPS NALU。 + * + * 为什么要合成:MediaCodec 要的是标准 Annex B 码流,而 ffmpeg 通过 VA-API + * 交给我们的是**已解析成结构体**的参数集。原始 SPS/PPS 字节流不会传下来, + * 只能按 H.265 语法重新写出来。 + * + * ── slice 不需要重建 ───────────────────────────────────── + * 和 H.264 一样,VASliceParameterBufferHEVC 里有 slice_data_byte_offset, + * 它是 slice header 结束的位置 —— 这个字段能存在就说明 slice header + * 原样在 slice data buffer 里。所以转发 slice 只需前置起始码, + * 不必反推参考列表重排序(那是欠定问题)。 + * + * ── VA-API 缺失、必须推导的字段 ─────────────────────────── + * profile_tier_level 的大部分、conformance window、VUI、 + * 以及 st_ref_pic_set 的内容都不在 VA-API 里。处理见下面各处注释。 + * + * ⚠️ 最关键的约束是 num_short_term_ref_pic_sets:VA-API 只给个数、不给内容。 + * 若原码流在 SPS 里放了参考集(个数 > 0),我们无法复现, + * 而 slice header 中 short_term_ref_pic_set_sps_flag=1 的引用会指向 + * 不存在的集合 —— 那会解出坏画面。所以个数 > 0 时**直接拒绝**, + * 让上层回落软解,而不是产出错误图像。 + * 实测 x265 默认输出该字段为 0(slice header 内联自己的参考集), + * 所以常见码流不受影响(tools/probe_hevc_sps.c)。 + */ + +#include + +#include "driver.h" +#include "bitstream.h" + +/* ---------------------------------------------------------------- 字段推导 */ + +/* general_profile_idc:VA-API 不提供,从 VAProfile 映射。 + * 只声明了 VAProfileHEVCMain(见 profiles.c),所以固定为 Main=1。 */ +static unsigned int hevc_profile_idc(VAProfile profile) +{ + switch (profile) { + case VAProfileHEVCMain10: + return 2; /* Main 10 */ + case VAProfileHEVCMain: + default: + return 1; /* Main */ + } +} + +/* general_level_idc = 30 × level。按分辨率取一个刚好够用的档位。 + * + * 宁可偏高:level 只是能力声明,报高了解码器仍按实际码流解, + * 报低了则可能被拒。这里按 H.265 表 A.6 的 MaxLumaPs 取。 */ +static unsigned int hevc_level_idc(unsigned int w, unsigned int h) +{ + unsigned int luma = w * h; + if (luma <= 36864) return 30; /* 1.0 176x144 */ + if (luma <= 122880) return 60; /* 2.0 352x288 */ + if (luma <= 245760) return 63; /* 2.1 640x360 */ + if (luma <= 552960) return 90; /* 3.0 960x540 */ + if (luma <= 983040) return 93; /* 3.1 1280x720 */ + if (luma <= 2228224) return 120; /* 4.0 2048x1080 */ + if (luma <= 8912896) return 150; /* 5.0 4096x2160 */ + return 180; /* 6.0 8192x4320 */ +} + +/* profile_tier_level():H.265 7.3.3。 + * + * VA-API 只有 profile 与分辨率,其余按"Main profile 的常规取值"填: + * general_profile_compatibility_flag 只置对应 profile 那一位, + * progressive_source + frame_only_constraint 置 1(我们不处理场编码)。 + * 这些 flag 是能力声明,解码器不会据此改变解码行为。 */ +static void put_ptl(struct dmd_bitwriter *bw, VAProfile profile, + unsigned int w, unsigned int h) +{ + unsigned int pidc = hevc_profile_idc(profile); + + dmd_bw_put_bits(bw, 0, 2); /* general_profile_space = 0 */ + dmd_bw_put_flag(bw, 0); /* general_tier_flag = Main tier */ + dmd_bw_put_bits(bw, pidc, 5); /* general_profile_idc */ + + /* general_profile_compatibility_flag[32]:只置自己那一位 */ + for (int i = 0; i < 32; i++) + dmd_bw_put_flag(bw, i == (int)pidc); + + dmd_bw_put_flag(bw, 1); /* general_progressive_source_flag */ + dmd_bw_put_flag(bw, 0); /* general_interlaced_source_flag */ + dmd_bw_put_flag(bw, 0); /* general_non_packed_constraint_flag */ + dmd_bw_put_flag(bw, 1); /* general_frame_only_constraint_flag */ + + /* general_reserved_zero_43bits */ + dmd_bw_put_bits(bw, 0, 22); + dmd_bw_put_bits(bw, 0, 21); + /* general_inbld_flag / reserved_zero_bit */ + dmd_bw_put_flag(bw, 0); + + dmd_bw_put_bits(bw, hevc_level_idc(w, h), 8); /* general_level_idc */ + /* sps_max_sub_layers_minus1 固定为 0,所以没有 sub_layer 的 PTL */ +} + +/* ---------------------------------------------------------------- VPS */ + +/* VPS:H.265 7.3.2.1。 + * + * 解码单层码流其实用不到 VPS 的多层信息,但 MediaCodec 的 CSD 通常期望 + * VPS+SPS+PPS 三件套,缺 VPS 有些解码器会拒。这里写一个最小可用的单层 VPS。 */ +static size_t build_vps_rbsp(const VAPictureParameterBufferHEVC *pp, + VAProfile profile, + unsigned char *out, size_t cap) +{ + struct dmd_bitwriter bw; + dmd_bw_init(&bw, out, cap); + + dmd_bw_put_bits(&bw, 0, 4); /* vps_video_parameter_set_id */ + dmd_bw_put_bits(&bw, 3, 2); /* vps_base_layer_internal/available: 保留位=3 */ + dmd_bw_put_bits(&bw, 0, 6); /* vps_max_layers_minus1 */ + dmd_bw_put_bits(&bw, 0, 3); /* vps_max_sub_layers_minus1 */ + dmd_bw_put_flag(&bw, 1); /* vps_temporal_id_nesting_flag */ + dmd_bw_put_bits(&bw, 0xFFFF, 16); /* vps_reserved_0xffff_16bits */ + + put_ptl(&bw, profile, + pp->pic_width_in_luma_samples, pp->pic_height_in_luma_samples); + + dmd_bw_put_flag(&bw, 0); /* vps_sub_layer_ordering_info_present_flag */ + /* 只有 sub_layer 0:三个 ue(v) */ + dmd_bw_put_ue(&bw, pp->sps_max_dec_pic_buffering_minus1); + dmd_bw_put_ue(&bw, 0); /* vps_max_num_reorder_pics */ + dmd_bw_put_ue(&bw, 0); /* vps_max_latency_increase_plus1 */ + + dmd_bw_put_bits(&bw, 0, 6); /* vps_max_layer_id */ + dmd_bw_put_ue(&bw, 0); /* vps_num_layer_sets_minus1 */ + dmd_bw_put_flag(&bw, 0); /* vps_timing_info_present_flag */ + dmd_bw_put_flag(&bw, 0); /* vps_extension_flag */ + + dmd_bw_rbsp_trailing(&bw); + return bw.overflow ? 0 : dmd_bw_bytes(&bw); +} + +/* ---------------------------------------------------------------- SPS */ + +/* SPS:H.265 7.3.2.2。 */ +static size_t build_sps_rbsp(const VAPictureParameterBufferHEVC *pp, + VAProfile profile, + unsigned char *out, size_t cap) +{ + struct dmd_bitwriter bw; + dmd_bw_init(&bw, out, cap); + + dmd_bw_put_bits(&bw, 0, 4); /* sps_video_parameter_set_id */ + dmd_bw_put_bits(&bw, 0, 3); /* sps_max_sub_layers_minus1 */ + dmd_bw_put_flag(&bw, 1); /* sps_temporal_id_nesting_flag */ + + put_ptl(&bw, profile, + pp->pic_width_in_luma_samples, pp->pic_height_in_luma_samples); + + dmd_bw_put_ue(&bw, 0); /* sps_seq_parameter_set_id */ + dmd_bw_put_ue(&bw, pp->pic_fields.bits.chroma_format_idc); + if (pp->pic_fields.bits.chroma_format_idc == 3) + dmd_bw_put_flag(&bw, pp->pic_fields.bits.separate_colour_plane_flag); + + dmd_bw_put_ue(&bw, pp->pic_width_in_luma_samples); + dmd_bw_put_ue(&bw, pp->pic_height_in_luma_samples); + + /* conformance_window_flag:VA-API 不提供裁剪窗口。 + * 写 0 表示无裁剪 —— 解码尺寸就是编码尺寸。真实裁剪信息由 daemon + * 从 MediaCodec 的 crop 字段获得并回传给驱动,所以这里不写不影响最终显示。 */ + dmd_bw_put_flag(&bw, 0); + + dmd_bw_put_ue(&bw, pp->bit_depth_luma_minus8); + dmd_bw_put_ue(&bw, pp->bit_depth_chroma_minus8); + dmd_bw_put_ue(&bw, pp->log2_max_pic_order_cnt_lsb_minus4); + + dmd_bw_put_flag(&bw, 0); /* sps_sub_layer_ordering_info_present_flag */ + dmd_bw_put_ue(&bw, pp->sps_max_dec_pic_buffering_minus1); + dmd_bw_put_ue(&bw, 0); /* sps_max_num_reorder_pics */ + dmd_bw_put_ue(&bw, 0); /* sps_max_latency_increase_plus1 */ + + dmd_bw_put_ue(&bw, pp->log2_min_luma_coding_block_size_minus3); + dmd_bw_put_ue(&bw, pp->log2_diff_max_min_luma_coding_block_size); + dmd_bw_put_ue(&bw, pp->log2_min_transform_block_size_minus2); + dmd_bw_put_ue(&bw, pp->log2_diff_max_min_transform_block_size); + dmd_bw_put_ue(&bw, pp->max_transform_hierarchy_depth_inter); + dmd_bw_put_ue(&bw, pp->max_transform_hierarchy_depth_intra); + + /* scaling_list_enabled_flag。 + * 置位时本应跟 sps_scaling_list_data_present_flag 与整张缩放表, + * 而 VA-API 把缩放表放在独立的 VAIQMatrixBufferHEVC 里。 + * 这里写 present=0,表示"用默认缩放表" —— 只有当码流真的用了 + * 自定义缩放表时才会不一致,那种情况由调用方拒绝(见 dmd_hevc_can_build)。 */ + dmd_bw_put_flag(&bw, pp->pic_fields.bits.scaling_list_enabled_flag); + if (pp->pic_fields.bits.scaling_list_enabled_flag) + dmd_bw_put_flag(&bw, 0); /* sps_scaling_list_data_present_flag */ + + dmd_bw_put_flag(&bw, pp->pic_fields.bits.amp_enabled_flag); + dmd_bw_put_flag(&bw, pp->slice_parsing_fields.bits.sample_adaptive_offset_enabled_flag); + + dmd_bw_put_flag(&bw, pp->pic_fields.bits.pcm_enabled_flag); + if (pp->pic_fields.bits.pcm_enabled_flag) { + dmd_bw_put_bits(&bw, pp->pcm_sample_bit_depth_luma_minus1, 4); + dmd_bw_put_bits(&bw, pp->pcm_sample_bit_depth_chroma_minus1, 4); + dmd_bw_put_ue(&bw, pp->log2_min_pcm_luma_coding_block_size_minus3); + dmd_bw_put_ue(&bw, pp->log2_diff_max_min_pcm_luma_coding_block_size); + dmd_bw_put_flag(&bw, pp->pic_fields.bits.pcm_loop_filter_disabled_flag); + } + + /* num_short_term_ref_pic_sets:VA-API 只给个数不给内容。 + * 个数 > 0 的码流已在 dmd_hevc_can_build 里被拒,所以这里必然是 0。 */ + dmd_bw_put_ue(&bw, pp->num_short_term_ref_pic_sets); + + dmd_bw_put_flag(&bw, pp->slice_parsing_fields.bits.long_term_ref_pics_present_flag); + if (pp->slice_parsing_fields.bits.long_term_ref_pics_present_flag) + dmd_bw_put_ue(&bw, pp->num_long_term_ref_pic_sps); + + dmd_bw_put_flag(&bw, pp->slice_parsing_fields.bits.sps_temporal_mvp_enabled_flag); + dmd_bw_put_flag(&bw, pp->pic_fields.bits.strong_intra_smoothing_enabled_flag); + + dmd_bw_put_flag(&bw, 0); /* vui_parameters_present_flag */ + dmd_bw_put_flag(&bw, 0); /* sps_extension_present_flag */ + + dmd_bw_rbsp_trailing(&bw); + return bw.overflow ? 0 : dmd_bw_bytes(&bw); +} + +/* ---------------------------------------------------------------- PPS */ + +/* PPS:H.265 7.3.2.3。 */ +static size_t build_pps_rbsp(const VAPictureParameterBufferHEVC *pp, + unsigned char *out, size_t cap) +{ + struct dmd_bitwriter bw; + dmd_bw_init(&bw, out, cap); + + dmd_bw_put_ue(&bw, 0); /* pps_pic_parameter_set_id */ + dmd_bw_put_ue(&bw, 0); /* pps_seq_parameter_set_id */ + + dmd_bw_put_flag(&bw, pp->slice_parsing_fields.bits.dependent_slice_segments_enabled_flag); + dmd_bw_put_flag(&bw, pp->slice_parsing_fields.bits.output_flag_present_flag); + dmd_bw_put_bits(&bw, pp->num_extra_slice_header_bits, 3); + dmd_bw_put_flag(&bw, pp->pic_fields.bits.sign_data_hiding_enabled_flag); + dmd_bw_put_flag(&bw, pp->slice_parsing_fields.bits.cabac_init_present_flag); + + dmd_bw_put_ue(&bw, pp->num_ref_idx_l0_default_active_minus1); + dmd_bw_put_ue(&bw, pp->num_ref_idx_l1_default_active_minus1); + dmd_bw_put_se(&bw, pp->init_qp_minus26); + + dmd_bw_put_flag(&bw, pp->pic_fields.bits.constrained_intra_pred_flag); + dmd_bw_put_flag(&bw, pp->pic_fields.bits.transform_skip_enabled_flag); + + dmd_bw_put_flag(&bw, pp->pic_fields.bits.cu_qp_delta_enabled_flag); + if (pp->pic_fields.bits.cu_qp_delta_enabled_flag) + dmd_bw_put_ue(&bw, pp->diff_cu_qp_delta_depth); + + dmd_bw_put_se(&bw, pp->pps_cb_qp_offset); + dmd_bw_put_se(&bw, pp->pps_cr_qp_offset); + + dmd_bw_put_flag(&bw, pp->slice_parsing_fields.bits.pps_slice_chroma_qp_offsets_present_flag); + dmd_bw_put_flag(&bw, pp->pic_fields.bits.weighted_pred_flag); + dmd_bw_put_flag(&bw, pp->pic_fields.bits.weighted_bipred_flag); + dmd_bw_put_flag(&bw, pp->pic_fields.bits.transquant_bypass_enabled_flag); + dmd_bw_put_flag(&bw, pp->pic_fields.bits.tiles_enabled_flag); + dmd_bw_put_flag(&bw, pp->pic_fields.bits.entropy_coding_sync_enabled_flag); + + if (pp->pic_fields.bits.tiles_enabled_flag) { + dmd_bw_put_ue(&bw, pp->num_tile_columns_minus1); + dmd_bw_put_ue(&bw, pp->num_tile_rows_minus1); + /* uniform_spacing_flag:VA-API 总是给出显式的 column_width/row_height, + * 所以写 0 并原样输出,避免依赖"均匀划分"的假设。 */ + dmd_bw_put_flag(&bw, 0); + for (int i = 0; i < pp->num_tile_columns_minus1; i++) + dmd_bw_put_ue(&bw, pp->column_width_minus1[i]); + for (int i = 0; i < pp->num_tile_rows_minus1; i++) + dmd_bw_put_ue(&bw, pp->row_height_minus1[i]); + dmd_bw_put_flag(&bw, pp->pic_fields.bits.loop_filter_across_tiles_enabled_flag); + } + + dmd_bw_put_flag(&bw, pp->pic_fields.bits.pps_loop_filter_across_slices_enabled_flag); + + /* deblocking_filter_control_present_flag:VA-API 没有这个字段本身, + * 但它是下面三项的开关。只要其中任何一项非默认值就必须置 1。 */ + int dbf_ctrl = pp->slice_parsing_fields.bits.deblocking_filter_override_enabled_flag || + pp->slice_parsing_fields.bits.pps_disable_deblocking_filter_flag || + pp->pps_beta_offset_div2 || pp->pps_tc_offset_div2; + dmd_bw_put_flag(&bw, dbf_ctrl); + if (dbf_ctrl) { + dmd_bw_put_flag(&bw, pp->slice_parsing_fields.bits.deblocking_filter_override_enabled_flag); + dmd_bw_put_flag(&bw, pp->slice_parsing_fields.bits.pps_disable_deblocking_filter_flag); + if (!pp->slice_parsing_fields.bits.pps_disable_deblocking_filter_flag) { + dmd_bw_put_se(&bw, pp->pps_beta_offset_div2); + dmd_bw_put_se(&bw, pp->pps_tc_offset_div2); + } + } + + /* pps_scaling_list_data_present_flag:同 SPS,缩放表在独立 buffer 里, + * 这里声明不存在,用默认表。 */ + dmd_bw_put_flag(&bw, 0); + + dmd_bw_put_flag(&bw, pp->slice_parsing_fields.bits.lists_modification_present_flag); + dmd_bw_put_ue(&bw, pp->log2_parallel_merge_level_minus2); + dmd_bw_put_flag(&bw, pp->slice_parsing_fields.bits.slice_segment_header_extension_present_flag); + dmd_bw_put_flag(&bw, 0); /* pps_extension_present_flag */ + + dmd_bw_rbsp_trailing(&bw); + return bw.overflow ? 0 : dmd_bw_bytes(&bw); +} + +/* ---------------------------------------------------------------- 对外接口 */ + +/* 能否为这个码流合成参数集?不能则应回落软解,而不是产出坏画面。 + * + * 唯一的硬性拒绝条件是 num_short_term_ref_pic_sets > 0: + * VA-API 只给个数不给内容,无法复现,而 slice header 会引用它们。 + * 返回 0 = 不支持,非 0 = 可以。 */ +int dmd_hevc_can_build(const VAPictureParameterBufferHEVC *pp) +{ + if (!pp) + return 0; + if (pp->num_short_term_ref_pic_sets > 0) + return 0; + return 1; +} + +/* 把 RBSP 包成带起始码的 NALU: + * [00 00 00 01][nal_unit_header 2 字节][转义后的 RBSP] */ +static size_t emit_nalu(unsigned int nal_unit_type, + const unsigned char *rbsp, size_t rbsp_len, + unsigned char *out, size_t cap) +{ + if (rbsp_len == 0 || cap < 6) + return 0; + + out[0] = 0; out[1] = 0; out[2] = 0; out[3] = 1; + /* forbidden_zero(1) type(6) layer_id(6) temporal_id_plus1(3) */ + out[4] = (unsigned char)((nal_unit_type & 0x3f) << 1); + out[5] = 1; + + size_t n = dmd_rbsp_escape(rbsp, rbsp_len, out + 6, cap - 6); + if (n == 0) + return 0; + return 6 + n; +} + +size_t dmd_hevc_build_vps_nalu(const VAPictureParameterBufferHEVC *pp, + VAProfile profile, + unsigned char *out, size_t cap) +{ + unsigned char rbsp[256]; + size_t n = build_vps_rbsp(pp, profile, rbsp, sizeof(rbsp)); + return emit_nalu(32, rbsp, n, out, cap); +} + +size_t dmd_hevc_build_sps_nalu(const VAPictureParameterBufferHEVC *pp, + VAProfile profile, + unsigned char *out, size_t cap) +{ + unsigned char rbsp[512]; + size_t n = build_sps_rbsp(pp, profile, rbsp, sizeof(rbsp)); + return emit_nalu(33, rbsp, n, out, cap); +} + +size_t dmd_hevc_build_pps_nalu(const VAPictureParameterBufferHEVC *pp, + unsigned char *out, size_t cap) +{ + unsigned char rbsp[512]; + size_t n = build_pps_rbsp(pp, rbsp, sizeof(rbsp)); + return emit_nalu(34, rbsp, n, out, cap); +} diff --git a/codec/vaapi/src/image.c b/codec/vaapi/src/image.c new file mode 100644 index 0000000..28c1cfc --- /dev/null +++ b/codec/vaapi/src/image.c @@ -0,0 +1,348 @@ +/* VAImage 出口:surface 像素回读到 CPU 可访问内存 + * + * ── 为什么必须走 CPU 路径 ────────────────────────────────── + * 容器内 ION 完全不可用(legacy EINVAL / modern ENODEV),/dev/dma_heap 不存在 + * (内核 4.14),MediaCodec 的 NDK 公开 API 也拿不到输出缓冲的 dmabuf fd。 + * 所以零拷贝这条路是死的,vaExportSurfaceHandle 保持 UNIMPLEMENTED, + * 像素一律经普通 heap 内存交付。 + * + * ── ffmpeg 的实际回读路径(已读 hwcontext_vaapi.c 确证)────── + * vaapi_frames_init 先建一个测试 surface 调 vaDeriveImage 探测(:696), + * 成功且 fourcc 匹配则 derive_works=1(:700);失败只是 debug 日志,不致命。 + * 但 vaapi_map_frame 的条件是 + * derive_works && dst->format == sw_format && ((flags & MAP_DIRECT) || !(flags & MAP_READ)) + * hwdownload 是**读**访问,所以即使 derive_works=1 也仍走 else 分支: + * vaCreateImage(:900)+ vaGetImage(:910)。两条路都必须实现。 + * + * ── 1088 vs 1080:本文件最关键的一处 ──────────────────────── + * 解码器输出缓冲 1920x1088、显示 1920x1080、stride=1920、slice_height=1088。 + * VAImage.width/height 报**显示尺寸**(1920x1080,否则 ffmpeg 的尺寸校验失败), + * 但 offsets[1] 必须用**缓冲高**:offsets[1] = stride * slice_height = 1920*1088。 + * 用 1080 算会让 UV 平面整体偏移 1920*8 字节 —— 症状是绿边、花屏、色度错位。 + */ + +#include +#include + +#include "driver.h" + +void dmd_fill_image_geometry(VAImage *img, unsigned int disp_width, + unsigned int disp_height, unsigned int stride, + unsigned int slice_height) +{ + memset(img, 0, sizeof(*img)); + + img->format.fourcc = VA_FOURCC_NV12; + img->format.byte_order = VA_LSB_FIRST; + img->format.bits_per_pixel = 12; + + /* 报显示尺寸:ffmpeg 按 sw_format 的尺寸校验,报缓冲尺寸会不匹配。 */ + img->width = (uint16_t)disp_width; + img->height = (uint16_t)disp_height; + + img->num_planes = 2; /* NV12:Y 平面 + 交织 UV 平面 */ + img->pitches[0] = stride; + img->pitches[1] = stride; /* UV 交织,每行 2 字节一组,行宽与 Y 相同 */ + img->offsets[0] = 0; + /* ⚠️ 用 slice_height(缓冲高 1088),不是 disp_height(1080)。 */ + img->offsets[1] = stride * slice_height; + + /* data_size 覆盖到 UV 平面结束:Y 是 stride*slice_height, + * UV 是它的一半(4:2:0 半平面)。 */ + img->data_size = stride * slice_height * 3 / 2; + + img->num_palette_entries = 0; + img->entry_bytes = 0; +} + +/* 取一个空闲 image 槽位并分配后备存储。调用方持锁。 + * backing 为 NULL 时自行 calloc;非 NULL 时借用(derive 场景,不拥有)。 */ +static struct dmd_image *image_alloc_locked(struct dmd_driver *drv, + const VAImage *desc, + unsigned char *backing) +{ + struct dmd_image *slot = NULL; + for (int i = 0; i < DMD_MAX_IMAGES; i++) { + if (!drv->images[i].in_use) { + slot = &drv->images[i]; + break; + } + } + if (!slot) + return NULL; + + unsigned char *data = backing; + if (!data) { + data = calloc(1, desc->data_size); + if (!data) + return NULL; + } + + memset(slot, 0, sizeof(*slot)); + slot->in_use = 1; + slot->id = (VAImageID)(drv->next_image_id++); + /* image.buf 必须是能被 vaMapBuffer 认出的 ID。用独立的 buffer ID 空间会 + * 与真 buffer 撞号,所以共用 next_buffer_id —— MapBuffer 先查 buffer 表 + * 再查 image 表,两边 ID 不重叠即可。 */ + slot->buf_id = (VABufferID)(drv->next_buffer_id++); + slot->image = *desc; + slot->image.image_id = slot->id; + slot->image.buf = slot->buf_id; + slot->data = data; + slot->data_size = desc->data_size; + /* backing 非空表示数据属于 surface,DestroyImage 不能 free。 */ + slot->derived_from = VA_INVALID_ID; + + return slot; +} + +struct dmd_image *dmd_find_image_locked(struct dmd_driver *drv, VAImageID id) +{ + if (id == VA_INVALID_ID) + return NULL; + for (int i = 0; i < DMD_MAX_IMAGES; i++) { + if (drv->images[i].in_use && drv->images[i].id == id) + return &drv->images[i]; + } + return NULL; +} + +VAStatus dmd_CreateImage(VADriverContextP ctx, VAImageFormat *format, int width, + int height, VAImage *image) +{ + struct dmd_driver *drv = dmd_get_driver(ctx); + + if (!drv || !format || !image) + return VA_STATUS_ERROR_INVALID_PARAMETER; + if (width <= 0 || height <= 0) + return VA_STATUS_ERROR_INVALID_PARAMETER; + if (width > DMD_MAX_WIDTH || height > DMD_MAX_HEIGHT) + return VA_STATUS_ERROR_RESOLUTION_NOT_SUPPORTED; + /* 只支持 NV12:MediaCodec 输出 color-format 21(线性 NV12), + * 其他格式要在 driver 里做色彩转换,那属于 VPP,本驱动不声明。 */ + if (format->fourcc != VA_FOURCC_NV12) + return VA_STATUS_ERROR_UNSUPPORTED_RT_FORMAT; + + /* 这里拿不到 surface,只能按解码器的对齐规则推导几何 —— + * 与 surface 的预分配用同一套规则(宽 128、高 32)。真实几何在 + * GetImage 时按 surface 的实际 stride/slice_height 逐行搬运, + * 所以即使解码器给了不同对齐也不会错位。 */ + unsigned int stride = dmd_align_up((unsigned int)width, DMD_WIDTH_ALIGN); + unsigned int slice_h = dmd_align_up((unsigned int)height, DMD_HEIGHT_ALIGN); + + VAImage desc; + dmd_fill_image_geometry(&desc, (unsigned int)width, (unsigned int)height, + stride, slice_h); + + pthread_mutex_lock(&drv->lock); + struct dmd_image *img = image_alloc_locked(drv, &desc, NULL); + if (!img) { + pthread_mutex_unlock(&drv->lock); + dmd_log("CreateImage: 槽位耗尽或分配失败(上限 %d)\n", DMD_MAX_IMAGES); + return VA_STATUS_ERROR_ALLOCATION_FAILED; + } + *image = img->image; + pthread_mutex_unlock(&drv->lock); + + dmd_log("CreateImage: %dx%d stride=%u slice_h=%u offsets=[0,%u] size=%u " + "-> image=%u buf=%u\n", + width, height, stride, slice_h, image->offsets[1], image->data_size, + (unsigned)image->image_id, (unsigned)image->buf); + + return VA_STATUS_SUCCESS; +} + +VAStatus dmd_DeriveImage(VADriverContextP ctx, VASurfaceID surface, + VAImage *image) +{ + struct dmd_driver *drv = dmd_get_driver(ctx); + + if (!drv || !image) + return VA_STATUS_ERROR_INVALID_PARAMETER; + + /* 真正的等帧点。SyncSurface 为了不与 MediaCodec 流水线深度死锁, + * 对"已提交未就绪"的 surface 直接报成功放行(详见 decode.c 里 + * dmd_SyncSurface2 的注释)。所以像素必须在这里保证就绪 —— + * 下面要读 s->stride / s->slice_height,它们只有帧回来后才是真值。 + * 必须在取锁之前调用:dmd_surface_wait 自己会加锁。 */ + VAStatus wait = dmd_surface_wait(drv, surface); + if (wait != VA_STATUS_SUCCESS) + return wait; + + pthread_mutex_lock(&drv->lock); + struct dmd_surface *s = dmd_find_surface_locked(drv, surface); + if (!s) { + pthread_mutex_unlock(&drv->lock); + return VA_STATUS_ERROR_INVALID_SURFACE; + } + + /* derive 是"直接访问 surface 内存",所以借用 surface->data, + * 不另分配也不拷贝。DestroyImage 不得 free 它。 + * 几何用 surface 的**实际** stride/slice_height —— 帧回来后 + * 这两个值已按解码器给的格式块更新过。 */ + VAImage desc; + dmd_fill_image_geometry(&desc, s->width, s->height, s->stride, + s->slice_height); + + /* surface 缓冲装不下声明的 data_size 时不能 derive:调用方会按 + * data_size 读越界。 */ + if (desc.data_size > s->data_size) { + pthread_mutex_unlock(&drv->lock); + dmd_log("DeriveImage: surface %u 缓冲 %zu < 需要 %u,拒绝\n", + (unsigned)surface, s->data_size, desc.data_size); + return VA_STATUS_ERROR_OPERATION_FAILED; + } + + struct dmd_image *img = image_alloc_locked(drv, &desc, s->data); + if (!img) { + pthread_mutex_unlock(&drv->lock); + return VA_STATUS_ERROR_ALLOCATION_FAILED; + } + img->derived_from = surface; + *image = img->image; + pthread_mutex_unlock(&drv->lock); + + dmd_log("DeriveImage: surface=%u -> image=%u %ux%u stride=%u " + "offsets=[0,%u]\n", + (unsigned)surface, (unsigned)image->image_id, image->width, + image->height, image->pitches[0], image->offsets[1]); + + return VA_STATUS_SUCCESS; +} + +VAStatus dmd_DestroyImage(VADriverContextP ctx, VAImageID image) +{ + struct dmd_driver *drv = dmd_get_driver(ctx); + + if (!drv) + return VA_STATUS_ERROR_INVALID_PARAMETER; + + pthread_mutex_lock(&drv->lock); + struct dmd_image *img = dmd_find_image_locked(drv, image); + if (!img) { + pthread_mutex_unlock(&drv->lock); + return VA_STATUS_ERROR_INVALID_IMAGE; + } + /* derive 出来的 image 借用 surface 缓冲,绝不能 free。 */ + unsigned char *owned = + (img->derived_from == VA_INVALID_ID) ? img->data : NULL; + memset(img, 0, sizeof(*img)); + pthread_mutex_unlock(&drv->lock); + + free(owned); + return VA_STATUS_SUCCESS; +} + +/* NV12 逐行搬运:源与目的可能有不同的 stride/slice_height, + * 整块 memcpy 只在两者完全一致时才对,其余情况必须按行。 */ +static void nv12_copy(unsigned char *dst, unsigned int dst_stride, + unsigned int dst_slice, const unsigned char *src, + unsigned int src_stride, unsigned int src_slice, + unsigned int x, unsigned int y, unsigned int w, + unsigned int h) +{ + unsigned int row_bytes = w < dst_stride ? w : dst_stride; + if (row_bytes > src_stride - x) + row_bytes = src_stride - x; + + /* Y 平面 */ + for (unsigned int r = 0; r < h; r++) { + memcpy(dst + (size_t)r * dst_stride, + src + (size_t)(y + r) * src_stride + x, row_bytes); + } + + /* UV 平面:4:2:0 半平面,高度减半,x 必须按 2 对齐才不会拆开 U/V 对。 */ + unsigned char *duv = dst + (size_t)dst_stride * dst_slice; + const unsigned char *suv = src + (size_t)src_stride * src_slice; + unsigned int uv_h = h / 2; + unsigned int uv_y = y / 2; + for (unsigned int r = 0; r < uv_h; r++) { + memcpy(duv + (size_t)r * dst_stride, + suv + (size_t)(uv_y + r) * src_stride + x, row_bytes); + } +} + +VAStatus dmd_GetImage(VADriverContextP ctx, VASurfaceID surface, int x, int y, + unsigned int width, unsigned int height, VAImageID image) +{ + struct dmd_driver *drv = dmd_get_driver(ctx); + + if (!drv) + return VA_STATUS_ERROR_INVALID_PARAMETER; + if (x < 0 || y < 0) + return VA_STATUS_ERROR_INVALID_PARAMETER; + if (width == 0 || height == 0) + return VA_STATUS_ERROR_INVALID_PARAMETER; + /* 色度平面按 2x2 采样,奇数起点会把 U/V 对拆开。 */ + if ((x & 1) || (y & 1)) + return VA_STATUS_ERROR_INVALID_PARAMETER; + + /* 与 DeriveImage 同理:SyncSurface 会放行未就绪的 surface, + * 拷像素之前必须在这里等到帧真的到手。 */ + VAStatus wait = dmd_surface_wait(drv, surface); + if (wait != VA_STATUS_SUCCESS) + return wait; + + pthread_mutex_lock(&drv->lock); + + struct dmd_surface *s = dmd_find_surface_locked(drv, surface); + if (!s) { + pthread_mutex_unlock(&drv->lock); + return VA_STATUS_ERROR_INVALID_SURFACE; + } + struct dmd_image *img = dmd_find_image_locked(drv, image); + if (!img) { + pthread_mutex_unlock(&drv->lock); + return VA_STATUS_ERROR_INVALID_IMAGE; + } + + /* surface 还没解出来就 GetImage:按 VA-API 语义隐式同步。 + * ffmpeg 会先 vaSyncSurface,但别的消费者未必。 */ + if (s->state == DMD_SURFACE_PENDING) { + VAStatus st = dmd_surface_sync_locked(drv, surface, + DMD_FRAME_TIMEOUT_MS); + if (st != VA_STATUS_SUCCESS) { + pthread_mutex_unlock(&drv->lock); + return st; + } + /* sync 期间放过锁,重新查找。 */ + s = dmd_find_surface_locked(drv, surface); + img = dmd_find_image_locked(drv, image); + if (!s || !img) { + pthread_mutex_unlock(&drv->lock); + return VA_STATUS_ERROR_INVALID_SURFACE; + } + } + + if (img->image.format.fourcc != VA_FOURCC_NV12) { + pthread_mutex_unlock(&drv->lock); + return VA_STATUS_ERROR_UNSUPPORTED_RT_FORMAT; + } + /* 请求区域必须落在 surface 缓冲内。 */ + if ((unsigned int)x + width > s->stride || + (unsigned int)y + height > s->slice_height) { + pthread_mutex_unlock(&drv->lock); + dmd_log("GetImage: 区域 %d,%d %ux%u 超出 surface 缓冲 %ux%u\n", x, y, + width, height, s->stride, s->slice_height); + return VA_STATUS_ERROR_INVALID_PARAMETER; + } + /* 目标 image 必须装得下请求的尺寸。 */ + if (width > img->image.width || height > img->image.height) { + pthread_mutex_unlock(&drv->lock); + return VA_STATUS_ERROR_INVALID_PARAMETER; + } + + /* derive 出来的 image 直接指向 surface 内存,同一 surface 时无需拷贝。 */ + if (img->derived_from == surface) { + pthread_mutex_unlock(&drv->lock); + return VA_STATUS_SUCCESS; + } + + nv12_copy(img->data, img->image.pitches[0], + img->image.offsets[1] / img->image.pitches[0], s->data, s->stride, + s->slice_height, (unsigned int)x, (unsigned int)y, width, height); + + pthread_mutex_unlock(&drv->lock); + + return VA_STATUS_SUCCESS; +} diff --git a/codec/vaapi/src/profiles.c b/codec/vaapi/src/profiles.c new file mode 100644 index 0000000..f73a2c2 --- /dev/null +++ b/codec/vaapi/src/profiles.c @@ -0,0 +1,429 @@ +/* profile / entrypoint / config 查询与 config 对象管理 + * + * 声明的能力严格对应 Android 侧 decode-daemon 能提供的解码器: + * 协议 codec 取值 0=H.264 1=HEVC 2=VP9 3=VP8,四者均已真机端到端验证。 + * 高位深(HEVC Main10、VP9 Profile2、H.264 High10)未验证,因此不声明 —— + * 谎报能力会让消费者选中我们然后失败,比不报更糟。 + */ + +#include + +#include "driver.h" + +/* 本驱动支持的 profile 集合。顺序即 vainfo 的输出顺序。 + * + * ⚠️ 只列**解码路径真的通了**的 profile。声明了但解不出来比不声明更糟 —— + * 消费者会选中我们然后失败,而它本来可以直接走软解。 + * + * HEVC(VAProfileHEVCMain)曾因"码流转发未实现"被移除过一段时间 —— + * 那时声明它属于虚报,Firefox 的 vaapitest 探针会读成 CODEC_HW_HEVC + * (GfxInfo.h:63 的 1<<8)。现在 hevc_bitstream.c 已实现 VPS/SPS/PPS 合成 + * 并真机验证(1080p/4K/720p 逐字节一致、长流 1500 帧、seek 全通), + * 所以重新声明;探针输出 368 = H264|VP8|VP9|HEVC 这次名实相符。 + * + * ⚠️ HEVC 有一类码流无法支持:SPS 里带 st_ref_pic_set 的 + * (num_short_term_ref_pic_sets > 0)。VA-API 只给个数不给内容, + * 无法复现。那种情况 vaEndPicture 返回 UNIMPLEMENTED 让上层回落软解 —— + * 见 dmd_hevc_can_build。实测 x265 默认输出 0,常见码流不受影响。 + */ +static const VAProfile dmd_profiles[] = { + VAProfileH264ConstrainedBaseline, + VAProfileH264Main, + VAProfileH264High, + VAProfileHEVCMain, + VAProfileVP9Profile0, + VAProfileVP8Version0_3, +}; + +#define DMD_NUM_PROFILES ((int)(sizeof(dmd_profiles) / sizeof(dmd_profiles[0]))) + +int dmd_profile_supported(VAProfile profile) +{ + for (int i = 0; i < DMD_NUM_PROFILES; i++) { + if (dmd_profiles[i] == profile) + return 1; + } + return 0; +} + +/* profile → 协议 codec id。 + * 高位深 profile 未验证故不映射。 + * HEVCMain 保留映射但**不在 dmd_profiles 里声明**:映射本身无害, + * 等 HEVC 码流转发实现后只需把 profile 加回声明表即可。 */ +int dmd_profile_to_codec(VAProfile profile) +{ + switch (profile) { + case VAProfileH264ConstrainedBaseline: + case VAProfileH264Main: + case VAProfileH264High: + return DMD_CODEC_H264; + case VAProfileHEVCMain: + return DMD_CODEC_HEVC; + case VAProfileVP9Profile0: + return DMD_CODEC_VP9; + case VAProfileVP8Version0_3: + return DMD_CODEC_VP8; + /* AV1 Profile0 = Main(8/10bit 4:2:0),Profile1 = High(含 4:4:4)。 + * 只映射 Profile0:MediaCodec 的 video/av01 不区分 profile,由码流 + * 序列头自述,但 4:4:4 的输出格式不是 NV12,本驱动的帧回传假设不成立。 */ + case VAProfileAV1Profile0: + return DMD_CODEC_AV1; + default: + return -1; + } +} + +VAStatus dmd_QueryConfigProfiles(VADriverContextP ctx, VAProfile *profile_list, + int *num_profiles) +{ + if (!ctx || !profile_list || !num_profiles) + return VA_STATUS_ERROR_INVALID_PARAMETER; + + memcpy(profile_list, dmd_profiles, sizeof(dmd_profiles)); + *num_profiles = DMD_NUM_PROFILES; + return VA_STATUS_SUCCESS; +} + +VAStatus dmd_QueryConfigEntrypoints(VADriverContextP ctx, VAProfile profile, + VAEntrypoint *entrypoint_list, + int *num_entrypoints) +{ + if (!ctx || !entrypoint_list || !num_entrypoints) + return VA_STATUS_ERROR_INVALID_PARAMETER; + + if (!dmd_profile_supported(profile)) { + *num_entrypoints = 0; + return VA_STATUS_ERROR_UNSUPPORTED_PROFILE; + } + + /* 只做解码。编码走 MediaCodec 是另一个项目,这里不声明。 */ + entrypoint_list[0] = VAEntrypointVLD; + *num_entrypoints = 1; + return VA_STATUS_SUCCESS; +} + +VAStatus dmd_GetConfigAttributes(VADriverContextP ctx, VAProfile profile, + VAEntrypoint entrypoint, + VAConfigAttrib *attrib_list, int num_attribs) +{ + if (!ctx || (num_attribs > 0 && !attrib_list)) + return VA_STATUS_ERROR_INVALID_PARAMETER; + if (num_attribs < 0) + return VA_STATUS_ERROR_INVALID_PARAMETER; + + if (!dmd_profile_supported(profile)) + return VA_STATUS_ERROR_UNSUPPORTED_PROFILE; + if (entrypoint != VAEntrypointVLD) + return VA_STATUS_ERROR_UNSUPPORTED_ENTRYPOINT; + + /* VA-API 约定:调用方传入想查的 attribute type,driver 填 value; + * 不支持的项必须填 VA_ATTRIB_NOT_SUPPORTED 而不是报错。 */ + for (int i = 0; i < num_attribs; i++) { + switch (attrib_list[i].type) { + case VAConfigAttribRTFormat: + /* MediaCodec 输出 8-bit 4:2:0 NV12。 */ + attrib_list[i].value = VA_RT_FORMAT_YUV420; + break; + case VAConfigAttribMaxPictureWidth: + attrib_list[i].value = DMD_MAX_WIDTH; + break; + case VAConfigAttribMaxPictureHeight: + attrib_list[i].value = DMD_MAX_HEIGHT; + break; + case VAConfigAttribDecSliceMode: + /* daemon 接收的是完整 Annex B 数据单元,对应 normal slice 模式。 */ + attrib_list[i].value = VA_DEC_SLICE_MODE_NORMAL; + break; + default: + attrib_list[i].value = VA_ATTRIB_NOT_SUPPORTED; + break; + } + } + + return VA_STATUS_SUCCESS; +} + +VAStatus dmd_CreateConfig(VADriverContextP ctx, VAProfile profile, + VAEntrypoint entrypoint, VAConfigAttrib *attrib_list, + int num_attribs, VAConfigID *config_id) +{ + struct dmd_driver *drv = dmd_get_driver(ctx); + + if (!drv || !config_id) + return VA_STATUS_ERROR_INVALID_PARAMETER; + if (num_attribs < 0 || (num_attribs > 0 && !attrib_list)) + return VA_STATUS_ERROR_INVALID_PARAMETER; + if (num_attribs > DMD_MAX_CONFIG_ATTRIBUTES) + return VA_STATUS_ERROR_INVALID_PARAMETER; + + if (!dmd_profile_supported(profile)) + return VA_STATUS_ERROR_UNSUPPORTED_PROFILE; + if (entrypoint != VAEntrypointVLD) + return VA_STATUS_ERROR_UNSUPPORTED_ENTRYPOINT; + + VAStatus status = VA_STATUS_ERROR_ALLOCATION_FAILED; + + pthread_mutex_lock(&drv->lock); + for (int i = 0; i < DMD_MAX_CONFIGS; i++) { + struct dmd_config *cfg = &drv->configs[i]; + if (cfg->in_use) + continue; + + memset(cfg, 0, sizeof(*cfg)); + cfg->in_use = 1; + /* ID 从 1 开始:0 留作 VA_INVALID_ID 之外的"未初始化"哨兵, + * 避免调用方把 0 误当合法 config。 */ + cfg->id = (VAConfigID)(drv->next_config_id++); + cfg->profile = profile; + cfg->entrypoint = entrypoint; + cfg->num_attribs = num_attribs; + if (num_attribs > 0) + memcpy(cfg->attribs, attrib_list, + (size_t)num_attribs * sizeof(VAConfigAttrib)); + + *config_id = cfg->id; + status = VA_STATUS_SUCCESS; + break; + } + pthread_mutex_unlock(&drv->lock); + + if (status == VA_STATUS_SUCCESS) + dmd_log("CreateConfig: profile=%d entrypoint=%d -> config=%u\n", + (int)profile, (int)entrypoint, (unsigned)*config_id); + else + dmd_log("CreateConfig: 槽位耗尽(上限 %d)\n", DMD_MAX_CONFIGS); + + return status; +} + +/* 在已加锁的前提下按 ID 查找 config。 */ +static struct dmd_config *find_config_locked(struct dmd_driver *drv, + VAConfigID id) +{ + for (int i = 0; i < DMD_MAX_CONFIGS; i++) { + if (drv->configs[i].in_use && drv->configs[i].id == id) + return &drv->configs[i]; + } + return NULL; +} + +VAStatus dmd_DestroyConfig(VADriverContextP ctx, VAConfigID config_id) +{ + struct dmd_driver *drv = dmd_get_driver(ctx); + + if (!drv) + return VA_STATUS_ERROR_INVALID_PARAMETER; + + VAStatus status; + + pthread_mutex_lock(&drv->lock); + struct dmd_config *cfg = find_config_locked(drv, config_id); + if (cfg) { + cfg->in_use = 0; + status = VA_STATUS_SUCCESS; + } else { + status = VA_STATUS_ERROR_INVALID_CONFIG; + } + pthread_mutex_unlock(&drv->lock); + + return status; +} + +VAStatus dmd_QueryConfigAttributes(VADriverContextP ctx, VAConfigID config_id, + VAProfile *profile, VAEntrypoint *entrypoint, + VAConfigAttrib *attrib_list, + int *num_attribs) +{ + struct dmd_driver *drv = dmd_get_driver(ctx); + + if (!drv || !profile || !entrypoint || !attrib_list || !num_attribs) + return VA_STATUS_ERROR_INVALID_PARAMETER; + + VAStatus status; + + pthread_mutex_lock(&drv->lock); + struct dmd_config *cfg = find_config_locked(drv, config_id); + if (cfg) { + *profile = cfg->profile; + *entrypoint = cfg->entrypoint; + + /* 回报**驱动支持的属性**,不是回显 CreateConfig 的入参。 + * + * 这里曾直接把 cfg->attribs 抄回去 —— 对 ffmpeg 与 Firefox 有效, + * 因为它们建 config 时自己就传了 RTFormat,回显恰好等于真值。 + * + * 但 Chrome **不传任何属性**建 config,然后调本函数查询驱动 + * 支持什么。回显模式下它拿到 num_attribs=0,读不到 RTFormat, + * 于是 FillProfileInfo_Locked 判定该 profile 不可用 —— + * 六个 profile 全部枚举失败,硬解完全不可用。 + * + * VA-API 的语义是"驱动声明能力",回显是错的。现在无论 + * CreateConfig 传了什么,RTFormat 一定出现在返回集里。 */ + int n = 0; + int have_rtformat = 0; + + for (int i = 0; i < cfg->num_attribs && n < DMD_MAX_CONFIG_ATTRIBUTES; i++) { + if (cfg->attribs[i].type == VAConfigAttribRTFormat) { + /* 用驱动真实支持的值覆盖调用方传入的值 */ + attrib_list[n].type = VAConfigAttribRTFormat; + attrib_list[n].value = VA_RT_FORMAT_YUV420; + have_rtformat = 1; + } else { + attrib_list[n] = cfg->attribs[i]; + } + n++; + } + + if (!have_rtformat && n < DMD_MAX_CONFIG_ATTRIBUTES) { + attrib_list[n].type = VAConfigAttribRTFormat; + attrib_list[n].value = VA_RT_FORMAT_YUV420; + n++; + } + + *num_attribs = n; + status = VA_STATUS_SUCCESS; + } else { + status = VA_STATUS_ERROR_INVALID_CONFIG; + } + pthread_mutex_unlock(&drv->lock); + + return status; +} + +VAStatus dmd_QuerySurfaceAttributes(VADriverContextP ctx, VAConfigID config, + VASurfaceAttrib *attrib_list, + unsigned int *num_attribs) +{ + struct dmd_driver *drv = dmd_get_driver(ctx); + + if (!drv || !num_attribs) + return VA_STATUS_ERROR_INVALID_PARAMETER; + + /* config 必须有效 —— 消费者据此判断该配置下的 surface 能力。 */ + pthread_mutex_lock(&drv->lock); + int valid = find_config_locked(drv, config) != NULL; + pthread_mutex_unlock(&drv->lock); + if (!valid) + return VA_STATUS_ERROR_INVALID_CONFIG; + + /* VA-API 约定的两段式查询:attrib_list 为 NULL 时只回报数量。 */ + const unsigned int needed = 5; + if (!attrib_list) { + *num_attribs = needed; + return VA_STATUS_SUCCESS; + } + if (*num_attribs < needed) { + *num_attribs = needed; + return VA_STATUS_ERROR_MAX_NUM_EXCEEDED; + } + + unsigned int n = 0; + + attrib_list[n].type = VASurfaceAttribPixelFormat; + attrib_list[n].flags = VA_SURFACE_ATTRIB_GETTABLE | VA_SURFACE_ATTRIB_SETTABLE; + attrib_list[n].value.type = VAGenericValueTypeInteger; + attrib_list[n].value.value.i = VA_FOURCC_NV12; + n++; + + attrib_list[n].type = VASurfaceAttribMinWidth; + attrib_list[n].flags = VA_SURFACE_ATTRIB_GETTABLE; + attrib_list[n].value.type = VAGenericValueTypeInteger; + attrib_list[n].value.value.i = DMD_MIN_WIDTH; + n++; + + attrib_list[n].type = VASurfaceAttribMinHeight; + attrib_list[n].flags = VA_SURFACE_ATTRIB_GETTABLE; + attrib_list[n].value.type = VAGenericValueTypeInteger; + attrib_list[n].value.value.i = DMD_MIN_HEIGHT; + n++; + + attrib_list[n].type = VASurfaceAttribMaxWidth; + attrib_list[n].flags = VA_SURFACE_ATTRIB_GETTABLE; + attrib_list[n].value.type = VAGenericValueTypeInteger; + attrib_list[n].value.value.i = DMD_MAX_WIDTH; + n++; + + attrib_list[n].type = VASurfaceAttribMaxHeight; + attrib_list[n].flags = VA_SURFACE_ATTRIB_GETTABLE; + attrib_list[n].value.type = VAGenericValueTypeInteger; + attrib_list[n].value.value.i = DMD_MAX_HEIGHT; + n++; + + *num_attribs = n; + return VA_STATUS_SUCCESS; +} + +VAStatus dmd_QueryImageFormats(VADriverContextP ctx, VAImageFormat *format_list, + int *num_formats) +{ + if (!ctx || !format_list || !num_formats) + return VA_STATUS_ERROR_INVALID_PARAMETER; + + /* 只支持 NV12:MediaCodec 的输出格式实测为 color-format 21 + * (COLOR_FormatYUV420SemiPlanar,线性 NV12)。 */ + memset(&format_list[0], 0, sizeof(format_list[0])); + format_list[0].fourcc = VA_FOURCC_NV12; + format_list[0].byte_order = VA_LSB_FIRST; + format_list[0].bits_per_pixel = 12; /* 平面式 YUV420 每像素 12 bit */ + + *num_formats = 1; + return VA_STATUS_SUCCESS; +} + +VAStatus dmd_QuerySubpictureFormats(VADriverContextP ctx, + VAImageFormat *format_list, + unsigned int *flags, + unsigned int *num_formats) +{ + (void)format_list; + (void)flags; + + if (!ctx || !num_formats) + return VA_STATUS_ERROR_INVALID_PARAMETER; + + /* 不支持 subpicture(叠加字幕等)。返回 0 个格式而非报错: + * 消费者据此跳过 subpicture 路径。 */ + *num_formats = 0; + return VA_STATUS_SUCCESS; +} + +VAStatus dmd_QueryDisplayAttributes(VADriverContextP ctx, + VADisplayAttribute *attr_list, + int *num_attributes) +{ + (void)attr_list; + + if (!ctx || !num_attributes) + return VA_STATUS_ERROR_INVALID_PARAMETER; + + /* 无可调显示属性(亮度/对比度等由消费者自行处理)。 */ + *num_attributes = 0; + return VA_STATUS_SUCCESS; +} + +VAStatus dmd_GetDisplayAttributes(VADriverContextP ctx, + VADisplayAttribute *attr_list, + int num_attributes) +{ + if (!ctx || (num_attributes > 0 && !attr_list)) + return VA_STATUS_ERROR_INVALID_PARAMETER; + + /* 我们不声明任何显示属性,因此任何查询都标记为不支持。 */ + for (int i = 0; i < num_attributes; i++) + attr_list[i].flags = VA_DISPLAY_ATTRIB_NOT_SUPPORTED; + + return VA_STATUS_SUCCESS; +} + +VAStatus dmd_SetDisplayAttributes(VADriverContextP ctx, + VADisplayAttribute *attr_list, + int num_attributes) +{ + (void)attr_list; + (void)num_attributes; + + if (!ctx) + return VA_STATUS_ERROR_INVALID_PARAMETER; + + return VA_STATUS_ERROR_ATTR_NOT_SUPPORTED; +} diff --git a/codec/vaapi/src/stubs.c b/codec/vaapi/src/stubs.c new file mode 100644 index 0000000..d0bc3b4 --- /dev/null +++ b/codec/vaapi/src/stubs.c @@ -0,0 +1,270 @@ +/* 本文件由 tools/gen_stubs.py 自动生成,请勿手工修改。 + * + * libva 在 vaInitialize 中逐个校验 vtable 槽位非 NULL(va/va.c CHECK_VTABLE), + * 任一为 NULL 会导致整个初始化失败。未实现的入口因此必须存在并返回 + * VA_STATUS_ERROR_UNIMPLEMENTED,而不能留空指针。 + */ + +#include "driver.h" + +VAStatus dmd_QuerySurfaceError(VADriverContextP ctx, VASurfaceID render_target, VAStatus error_status, void **error_info) +{ + (void)ctx; + (void)render_target; + (void)error_status; + (void)error_info; + dmd_log("未实现入口被调用: vaQuerySurfaceError\n"); + return VA_STATUS_ERROR_UNIMPLEMENTED; +} + +VAStatus dmd_PutSurface(VADriverContextP ctx, VASurfaceID surface, void*draw, short srcx, short srcy, unsigned short srcw, unsigned short srch, short destx, short desty, unsigned short destw, unsigned short desth, VARectangle *cliprects, unsigned int number_cliprects, unsigned int flags) +{ + (void)ctx; + (void)surface; + (void)draw; + (void)srcx; + (void)srcy; + (void)srcw; + (void)srch; + (void)destx; + (void)desty; + (void)destw; + (void)desth; + (void)cliprects; + (void)number_cliprects; + (void)flags; + dmd_log("未实现入口被调用: vaPutSurface\n"); + return VA_STATUS_ERROR_UNIMPLEMENTED; +} + +VAStatus dmd_SetImagePalette(VADriverContextP ctx, VAImageID image, unsigned char *palette) +{ + (void)ctx; + (void)image; + (void)palette; + dmd_log("未实现入口被调用: vaSetImagePalette\n"); + return VA_STATUS_ERROR_UNIMPLEMENTED; +} + +VAStatus dmd_PutImage(VADriverContextP ctx, VASurfaceID surface, VAImageID image, int src_x, int src_y, unsigned int src_width, unsigned int src_height, int dest_x, int dest_y, unsigned int dest_width, unsigned int dest_height) +{ + (void)ctx; + (void)surface; + (void)image; + (void)src_x; + (void)src_y; + (void)src_width; + (void)src_height; + (void)dest_x; + (void)dest_y; + (void)dest_width; + (void)dest_height; + dmd_log("未实现入口被调用: vaPutImage\n"); + return VA_STATUS_ERROR_UNIMPLEMENTED; +} + +VAStatus dmd_CreateSubpicture(VADriverContextP ctx, VAImageID image, VASubpictureID *subpicture) +{ + (void)ctx; + (void)image; + (void)subpicture; + dmd_log("未实现入口被调用: vaCreateSubpicture\n"); + return VA_STATUS_ERROR_UNIMPLEMENTED; +} + +VAStatus dmd_DestroySubpicture(VADriverContextP ctx, VASubpictureID subpicture) +{ + (void)ctx; + (void)subpicture; + dmd_log("未实现入口被调用: vaDestroySubpicture\n"); + return VA_STATUS_ERROR_UNIMPLEMENTED; +} + +VAStatus dmd_SetSubpictureImage(VADriverContextP ctx, VASubpictureID subpicture, VAImageID image) +{ + (void)ctx; + (void)subpicture; + (void)image; + dmd_log("未实现入口被调用: vaSetSubpictureImage\n"); + return VA_STATUS_ERROR_UNIMPLEMENTED; +} + +VAStatus dmd_SetSubpictureChromakey(VADriverContextP ctx, VASubpictureID subpicture, unsigned int chromakey_min, unsigned int chromakey_max, unsigned int chromakey_mask) +{ + (void)ctx; + (void)subpicture; + (void)chromakey_min; + (void)chromakey_max; + (void)chromakey_mask; + dmd_log("未实现入口被调用: vaSetSubpictureChromakey\n"); + return VA_STATUS_ERROR_UNIMPLEMENTED; +} + +VAStatus dmd_SetSubpictureGlobalAlpha(VADriverContextP ctx, VASubpictureID subpicture, float global_alpha) +{ + (void)ctx; + (void)subpicture; + (void)global_alpha; + dmd_log("未实现入口被调用: vaSetSubpictureGlobalAlpha\n"); + return VA_STATUS_ERROR_UNIMPLEMENTED; +} + +VAStatus dmd_AssociateSubpicture(VADriverContextP ctx, VASubpictureID subpicture, VASurfaceID *target_surfaces, int num_surfaces, short src_x, short src_y, unsigned short src_width, unsigned short src_height, short dest_x, short dest_y, unsigned short dest_width, unsigned short dest_height, unsigned int flags) +{ + (void)ctx; + (void)subpicture; + (void)target_surfaces; + (void)num_surfaces; + (void)src_x; + (void)src_y; + (void)src_width; + (void)src_height; + (void)dest_x; + (void)dest_y; + (void)dest_width; + (void)dest_height; + (void)flags; + dmd_log("未实现入口被调用: vaAssociateSubpicture\n"); + return VA_STATUS_ERROR_UNIMPLEMENTED; +} + +VAStatus dmd_DeassociateSubpicture(VADriverContextP ctx, VASubpictureID subpicture, VASurfaceID *target_surfaces, int num_surfaces) +{ + (void)ctx; + (void)subpicture; + (void)target_surfaces; + (void)num_surfaces; + dmd_log("未实现入口被调用: vaDeassociateSubpicture\n"); + return VA_STATUS_ERROR_UNIMPLEMENTED; +} + +VAStatus dmd_LockSurface(VADriverContextP ctx, VASurfaceID surface, unsigned int *fourcc, unsigned int *luma_stride, unsigned int *chroma_u_stride, unsigned int *chroma_v_stride, unsigned int *luma_offset, unsigned int *chroma_u_offset, unsigned int *chroma_v_offset, unsigned int *buffer_name, void **buffer) +{ + (void)ctx; + (void)surface; + (void)fourcc; + (void)luma_stride; + (void)chroma_u_stride; + (void)chroma_v_stride; + (void)luma_offset; + (void)chroma_u_offset; + (void)chroma_v_offset; + (void)buffer_name; + (void)buffer; + dmd_log("未实现入口被调用: vaLockSurface\n"); + return VA_STATUS_ERROR_UNIMPLEMENTED; +} + +VAStatus dmd_UnlockSurface(VADriverContextP ctx, VASurfaceID surface) +{ + (void)ctx; + (void)surface; + dmd_log("未实现入口被调用: vaUnlockSurface\n"); + return VA_STATUS_ERROR_UNIMPLEMENTED; +} + +VAStatus dmd_GetSurfaceAttributes(VADriverContextP dpy, VAConfigID config, VASurfaceAttrib *attrib_list, unsigned int num_attribs) +{ + (void)dpy; + (void)config; + (void)attrib_list; + (void)num_attribs; + dmd_log("未实现入口被调用: vaGetSurfaceAttributes\n"); + return VA_STATUS_ERROR_UNIMPLEMENTED; +} + +VAStatus dmd_AcquireBufferHandle(VADriverContextP ctx, VABufferID buf_id, VABufferInfo *buf_info) +{ + (void)ctx; + (void)buf_id; + (void)buf_info; + dmd_log("未实现入口被调用: vaAcquireBufferHandle\n"); + return VA_STATUS_ERROR_UNIMPLEMENTED; +} + +VAStatus dmd_ReleaseBufferHandle(VADriverContextP ctx, VABufferID buf_id) +{ + (void)ctx; + (void)buf_id; + dmd_log("未实现入口被调用: vaReleaseBufferHandle\n"); + return VA_STATUS_ERROR_UNIMPLEMENTED; +} + +VAStatus dmd_CreateMFContext(VADriverContextP ctx, VAMFContextID *mfe_context) +{ + (void)ctx; + (void)mfe_context; + dmd_log("未实现入口被调用: vaCreateMFContext\n"); + return VA_STATUS_ERROR_UNIMPLEMENTED; +} + +VAStatus dmd_MFAddContext(VADriverContextP ctx, VAMFContextID mf_context, VAContextID context) +{ + (void)ctx; + (void)mf_context; + (void)context; + dmd_log("未实现入口被调用: vaMFAddContext\n"); + return VA_STATUS_ERROR_UNIMPLEMENTED; +} + +VAStatus dmd_MFReleaseContext(VADriverContextP ctx, VAMFContextID mf_context, VAContextID context) +{ + (void)ctx; + (void)mf_context; + (void)context; + dmd_log("未实现入口被调用: vaMFReleaseContext\n"); + return VA_STATUS_ERROR_UNIMPLEMENTED; +} + +VAStatus dmd_MFSubmit(VADriverContextP ctx, VAMFContextID mf_context, VAContextID *contexts, int num_contexts) +{ + (void)ctx; + (void)mf_context; + (void)contexts; + (void)num_contexts; + dmd_log("未实现入口被调用: vaMFSubmit\n"); + return VA_STATUS_ERROR_UNIMPLEMENTED; +} + +VAStatus dmd_CreateBuffer2(VADriverContextP ctx, VAContextID context, VABufferType type, unsigned int width, unsigned int height, unsigned int *unit_size, unsigned int *pitch, VABufferID *buf_id) +{ + (void)ctx; + (void)context; + (void)type; + (void)width; + (void)height; + (void)unit_size; + (void)pitch; + (void)buf_id; + dmd_log("未实现入口被调用: vaCreateBuffer2\n"); + return VA_STATUS_ERROR_UNIMPLEMENTED; +} + +VAStatus dmd_QueryProcessingRate(VADriverContextP ctx, VAConfigID config_id, VAProcessingRateParameter *proc_buf, unsigned int *processing_rate) +{ + (void)ctx; + (void)config_id; + (void)proc_buf; + (void)processing_rate; + dmd_log("未实现入口被调用: vaQueryProcessingRate\n"); + return VA_STATUS_ERROR_UNIMPLEMENTED; +} + +VAStatus dmd_SyncBuffer(VADriverContextP ctx, VABufferID buf_id, uint64_t timeout_ns) +{ + (void)ctx; + (void)buf_id; + (void)timeout_ns; + dmd_log("未实现入口被调用: vaSyncBuffer\n"); + return VA_STATUS_ERROR_UNIMPLEMENTED; +} + +VAStatus dmd_Copy(VADriverContextP ctx, VACopyObject *dst, VACopyObject *src, VACopyOption option) +{ + (void)ctx; + (void)dst; + (void)src; + (void)option; + dmd_log("未实现入口被调用: vaCopy\n"); + return VA_STATUS_ERROR_UNIMPLEMENTED; +} diff --git a/codec/vaapi/src/stubs.h b/codec/vaapi/src/stubs.h new file mode 100644 index 0000000..50057e2 --- /dev/null +++ b/codec/vaapi/src/stubs.h @@ -0,0 +1,33 @@ +/* 本文件由 tools/gen_stubs.py 自动生成,请勿手工修改。 */ + +#ifndef DMD_STUBS_H +#define DMD_STUBS_H + +#include + +VAStatus dmd_QuerySurfaceError(VADriverContextP ctx, VASurfaceID render_target, VAStatus error_status, void **error_info); +VAStatus dmd_PutSurface(VADriverContextP ctx, VASurfaceID surface, void*draw, short srcx, short srcy, unsigned short srcw, unsigned short srch, short destx, short desty, unsigned short destw, unsigned short desth, VARectangle *cliprects, unsigned int number_cliprects, unsigned int flags); +VAStatus dmd_SetImagePalette(VADriverContextP ctx, VAImageID image, unsigned char *palette); +VAStatus dmd_PutImage(VADriverContextP ctx, VASurfaceID surface, VAImageID image, int src_x, int src_y, unsigned int src_width, unsigned int src_height, int dest_x, int dest_y, unsigned int dest_width, unsigned int dest_height); +VAStatus dmd_CreateSubpicture(VADriverContextP ctx, VAImageID image, VASubpictureID *subpicture); +VAStatus dmd_DestroySubpicture(VADriverContextP ctx, VASubpictureID subpicture); +VAStatus dmd_SetSubpictureImage(VADriverContextP ctx, VASubpictureID subpicture, VAImageID image); +VAStatus dmd_SetSubpictureChromakey(VADriverContextP ctx, VASubpictureID subpicture, unsigned int chromakey_min, unsigned int chromakey_max, unsigned int chromakey_mask); +VAStatus dmd_SetSubpictureGlobalAlpha(VADriverContextP ctx, VASubpictureID subpicture, float global_alpha); +VAStatus dmd_AssociateSubpicture(VADriverContextP ctx, VASubpictureID subpicture, VASurfaceID *target_surfaces, int num_surfaces, short src_x, short src_y, unsigned short src_width, unsigned short src_height, short dest_x, short dest_y, unsigned short dest_width, unsigned short dest_height, unsigned int flags); +VAStatus dmd_DeassociateSubpicture(VADriverContextP ctx, VASubpictureID subpicture, VASurfaceID *target_surfaces, int num_surfaces); +VAStatus dmd_LockSurface(VADriverContextP ctx, VASurfaceID surface, unsigned int *fourcc, unsigned int *luma_stride, unsigned int *chroma_u_stride, unsigned int *chroma_v_stride, unsigned int *luma_offset, unsigned int *chroma_u_offset, unsigned int *chroma_v_offset, unsigned int *buffer_name, void **buffer); +VAStatus dmd_UnlockSurface(VADriverContextP ctx, VASurfaceID surface); +VAStatus dmd_GetSurfaceAttributes(VADriverContextP dpy, VAConfigID config, VASurfaceAttrib *attrib_list, unsigned int num_attribs); +VAStatus dmd_AcquireBufferHandle(VADriverContextP ctx, VABufferID buf_id, VABufferInfo *buf_info); +VAStatus dmd_ReleaseBufferHandle(VADriverContextP ctx, VABufferID buf_id); +VAStatus dmd_CreateMFContext(VADriverContextP ctx, VAMFContextID *mfe_context); +VAStatus dmd_MFAddContext(VADriverContextP ctx, VAMFContextID mf_context, VAContextID context); +VAStatus dmd_MFReleaseContext(VADriverContextP ctx, VAMFContextID mf_context, VAContextID context); +VAStatus dmd_MFSubmit(VADriverContextP ctx, VAMFContextID mf_context, VAContextID *contexts, int num_contexts); +VAStatus dmd_CreateBuffer2(VADriverContextP ctx, VAContextID context, VABufferType type, unsigned int width, unsigned int height, unsigned int *unit_size, unsigned int *pitch, VABufferID *buf_id); +VAStatus dmd_QueryProcessingRate(VADriverContextP ctx, VAConfigID config_id, VAProcessingRateParameter *proc_buf, unsigned int *processing_rate); +VAStatus dmd_SyncBuffer(VADriverContextP ctx, VABufferID buf_id, uint64_t timeout_ns); +VAStatus dmd_Copy(VADriverContextP ctx, VACopyObject *dst, VACopyObject *src, VACopyOption option); + +#endif /* DMD_STUBS_H */ diff --git a/codec/vaapi/src/vtable.inc b/codec/vaapi/src/vtable.inc new file mode 100644 index 0000000..06d19f7 --- /dev/null +++ b/codec/vaapi/src/vtable.inc @@ -0,0 +1,64 @@ +/* 本文件由 tools/gen_stubs.py 自动生成,请勿手工修改。 + * vtable 装配:覆盖 va_backend.h 中 VADriverVTable 的全部 60 个槽位。 + */ + + vtable->vaTerminate = dmd_Terminate; + vtable->vaQueryConfigProfiles = dmd_QueryConfigProfiles; + vtable->vaQueryConfigEntrypoints = dmd_QueryConfigEntrypoints; + vtable->vaGetConfigAttributes = dmd_GetConfigAttributes; + vtable->vaCreateConfig = dmd_CreateConfig; + vtable->vaDestroyConfig = dmd_DestroyConfig; + vtable->vaQueryConfigAttributes = dmd_QueryConfigAttributes; + vtable->vaCreateSurfaces = dmd_CreateSurfaces; + vtable->vaDestroySurfaces = dmd_DestroySurfaces; + vtable->vaCreateContext = dmd_CreateContext; + vtable->vaDestroyContext = dmd_DestroyContext; + vtable->vaCreateBuffer = dmd_CreateBuffer; + vtable->vaBufferSetNumElements = dmd_BufferSetNumElements; + vtable->vaMapBuffer = dmd_MapBuffer; + vtable->vaUnmapBuffer = dmd_UnmapBuffer; + vtable->vaDestroyBuffer = dmd_DestroyBuffer; + vtable->vaBeginPicture = dmd_BeginPicture; + vtable->vaRenderPicture = dmd_RenderPicture; + vtable->vaEndPicture = dmd_EndPicture; + vtable->vaSyncSurface = dmd_SyncSurface; + vtable->vaQuerySurfaceStatus = dmd_QuerySurfaceStatus; + vtable->vaQuerySurfaceError = dmd_QuerySurfaceError; + vtable->vaPutSurface = dmd_PutSurface; + vtable->vaQueryImageFormats = dmd_QueryImageFormats; + vtable->vaCreateImage = dmd_CreateImage; + vtable->vaDeriveImage = dmd_DeriveImage; + vtable->vaDestroyImage = dmd_DestroyImage; + vtable->vaSetImagePalette = dmd_SetImagePalette; + vtable->vaGetImage = dmd_GetImage; + vtable->vaPutImage = dmd_PutImage; + vtable->vaQuerySubpictureFormats = dmd_QuerySubpictureFormats; + vtable->vaCreateSubpicture = dmd_CreateSubpicture; + vtable->vaDestroySubpicture = dmd_DestroySubpicture; + vtable->vaSetSubpictureImage = dmd_SetSubpictureImage; + vtable->vaSetSubpictureChromakey = dmd_SetSubpictureChromakey; + vtable->vaSetSubpictureGlobalAlpha = dmd_SetSubpictureGlobalAlpha; + vtable->vaAssociateSubpicture = dmd_AssociateSubpicture; + vtable->vaDeassociateSubpicture = dmd_DeassociateSubpicture; + vtable->vaQueryDisplayAttributes = dmd_QueryDisplayAttributes; + vtable->vaGetDisplayAttributes = dmd_GetDisplayAttributes; + vtable->vaSetDisplayAttributes = dmd_SetDisplayAttributes; + vtable->vaBufferInfo = dmd_BufferInfo; + vtable->vaLockSurface = dmd_LockSurface; + vtable->vaUnlockSurface = dmd_UnlockSurface; + vtable->vaGetSurfaceAttributes = dmd_GetSurfaceAttributes; + vtable->vaCreateSurfaces2 = dmd_CreateSurfaces2; + vtable->vaQuerySurfaceAttributes = dmd_QuerySurfaceAttributes; + vtable->vaAcquireBufferHandle = dmd_AcquireBufferHandle; + vtable->vaReleaseBufferHandle = dmd_ReleaseBufferHandle; + vtable->vaCreateMFContext = dmd_CreateMFContext; + vtable->vaMFAddContext = dmd_MFAddContext; + vtable->vaMFReleaseContext = dmd_MFReleaseContext; + vtable->vaMFSubmit = dmd_MFSubmit; + vtable->vaCreateBuffer2 = dmd_CreateBuffer2; + vtable->vaQueryProcessingRate = dmd_QueryProcessingRate; + vtable->vaExportSurfaceHandle = dmd_ExportSurfaceHandle; + vtable->vaSyncSurface2 = dmd_SyncSurface2; + vtable->vaSyncBuffer = dmd_SyncBuffer; + vtable->vaCopy = dmd_Copy; + vtable->vaMapBuffer2 = dmd_MapBuffer2; diff --git a/codec/vaapi/tools/gen_stubs.py b/codec/vaapi/tools/gen_stubs.py new file mode 100644 index 0000000..a72ac50 --- /dev/null +++ b/codec/vaapi/tools/gen_stubs.py @@ -0,0 +1,151 @@ +#!/usr/bin/env python3 +"""生成 VA-API driver 的 vtable 桩函数与装配代码。 + +libva 在 vaInitialize 时强制校验 39 个 vtable 槽位非 NULL(va/va.c 的 CHECK_VTABLE), +任一为 NULL 则整个初始化失败并 dlclose。因此未实现的槽位必须指向返回 +VA_STATUS_ERROR_UNIMPLEMENTED 的桩函数,而不能留空。 + +本脚本从 vtable.json(由 gen_vtable.py 从 va_backend.h 抽取)生成: + - stubs.c :所有未实现槽位的桩函数定义 + - vtable.inc:vtable 装配的初始化列表片段 + +已实现的槽位在 IMPLEMENTED 里列出,脚本会跳过它们的桩生成, +但仍会在 vtable.inc 里引用其真实函数名(约定为 dmd_<去掉 va 前缀>)。 +""" +import json +import sys + +# 由 driver 真实实现的槽位(其余生成 UNIMPLEMENTED 桩) +IMPLEMENTED = { + "vaTerminate", + "vaQueryConfigProfiles", + "vaQueryConfigEntrypoints", + "vaGetConfigAttributes", + "vaCreateConfig", + "vaDestroyConfig", + "vaQueryConfigAttributes", + "vaQuerySurfaceAttributes", + "vaQueryImageFormats", + "vaQueryDisplayAttributes", + "vaGetDisplayAttributes", + "vaSetDisplayAttributes", + "vaQuerySubpictureFormats", + # ---- 解码数据路径(decode.c) ---- + "vaCreateSurfaces", + "vaCreateSurfaces2", + "vaDestroySurfaces", + "vaCreateContext", + "vaDestroyContext", + "vaCreateBuffer", + "vaBufferSetNumElements", + "vaMapBuffer", + # 必须实现:libva 只在槽位为 NULL 时才回落到 vaMapBuffer, + # 而我们所有槽位都填了桩,留桩会让 ffmpeg 的回读路径直接失败。 + "vaMapBuffer2", + "vaUnmapBuffer", + "vaDestroyBuffer", + "vaBufferInfo", + "vaBeginPicture", + "vaRenderPicture", + "vaEndPicture", + "vaSyncSurface", + "vaSyncSurface2", + "vaQuerySurfaceStatus", + # ---- VAImage 出口(image.c) ---- + "vaCreateImage", + "vaDeriveImage", + "vaDestroyImage", + "vaGetImage", + # ---- dmabuf 出口(export.c) ---- + # Firefox 取帧只走这条路:CreateImageVAAPI 要 DRM_PRIME_2 描述符, + # 失败即整条流回落软解,且没有拷贝回退路径。 + "vaExportSurfaceHandle", +} + +funcs = json.load(open(sys.argv[1], encoding="utf-8")) + + +def impl_name(va_name: str) -> str: + """vaQueryConfigProfiles -> dmd_QueryConfigProfiles""" + assert va_name.startswith("va") + return "dmd_" + va_name[2:] + + +def render_params(params): + """渲染形参列表,未使用的参数加 (void) 消警告需在函数体处理。""" + if not params: + return "void" + out = [] + for p in params: + t = p["type"] + # 指针类型与变量名之间不留空格更贴合项目风格 + sep = "" if t.endswith("*") else " " + out.append(f"{t}{sep}{p['name']}{p['array']}") + return ", ".join(out) + + +# ---------- stubs.c ---------- +lines = [ + "/* 本文件由 tools/gen_stubs.py 自动生成,请勿手工修改。", + " *", + " * libva 在 vaInitialize 中逐个校验 vtable 槽位非 NULL(va/va.c CHECK_VTABLE),", + " * 任一为 NULL 会导致整个初始化失败。未实现的入口因此必须存在并返回", + " * VA_STATUS_ERROR_UNIMPLEMENTED,而不能留空指针。", + " */", + "", + '#include "driver.h"', + "", +] + +stub_names = [] +for f in funcs: + if f["name"] in IMPLEMENTED: + continue + name = impl_name(f["name"]) + stub_names.append((f["name"], name)) + lines.append(f"{f['ret']} {name}({render_params(f['params'])})") + lines.append("{") + for p in f["params"]: + lines.append(f" (void){p['name']};") + # 桩被调用是重要诊断信息:消费者踩到未实现入口时,症状往往是"悄悄 + # 回落软解"而不是报错。静默返回 UNIMPLEMENTED 会让这种情况完全不可观测 + # (定位 Firefox 问题时就吃过这个亏),所以在 DMD_VA_LOG 下留一行。 + lines.append(f' dmd_log("未实现入口被调用: {f["name"]}\\n");') + lines.append(" return VA_STATUS_ERROR_UNIMPLEMENTED;") + lines.append("}") + lines.append("") + +with open("out/stubs.c", "w", encoding="utf-8") as fh: + fh.write("\n".join(lines)) + +# ---------- stubs.h ---------- +hl = [ + "/* 本文件由 tools/gen_stubs.py 自动生成,请勿手工修改。 */", + "", + "#ifndef DMD_STUBS_H", + "#define DMD_STUBS_H", + "", + '#include ', + "", +] +for va_name, name in stub_names: + f = next(x for x in funcs if x["name"] == va_name) + hl.append(f"{f['ret']} {name}({render_params(f['params'])});") +hl += ["", "#endif /* DMD_STUBS_H */", ""] +with open("out/stubs.h", "w", encoding="utf-8") as fh: + fh.write("\n".join(hl)) + +# ---------- vtable.inc ---------- +vl = [ + "/* 本文件由 tools/gen_stubs.py 自动生成,请勿手工修改。", + " * vtable 装配:覆盖 va_backend.h 中 VADriverVTable 的全部 %d 个槽位。" % len(funcs), + " */", + "", +] +for f in funcs: + vl.append(f" vtable->{f['name']} = {impl_name(f['name'])};") +vl.append("") +with open("out/vtable.inc", "w", encoding="utf-8") as fh: + fh.write("\n".join(vl)) + +print(f"槽位总数 {len(funcs)},真实现 {len(funcs)-len(stub_names)},桩 {len(stub_names)}") diff --git a/codec/vaapi/tools/gen_vtable.py b/codec/vaapi/tools/gen_vtable.py new file mode 100644 index 0000000..7240f5f --- /dev/null +++ b/codec/vaapi/tools/gen_vtable.py @@ -0,0 +1,60 @@ +#!/usr/bin/env python3 +"""从 va_backend.h 精确抽取 VADriverVTable 的全部函数指针签名。 + +用途:VA-API driver 必须填满 libva 强制校验的所有 vtable 槽位, +任一为 NULL 会导致 vaInitialize 失败。手抄 60+ 个签名易错,这里做确定性抽取。 + +输出:JSON 列表 [{name, ret, params:[{type, name}]}, ...] +""" +import json +import re +import sys + +HEADER = sys.argv[1] if len(sys.argv) > 1 else "container-headers/va_backend.h" + +with open(HEADER, encoding="utf-8") as fh: + src = fh.read() + +# 1) 切出 struct VADriverVTable { ... }; +m = re.search(r"struct VADriverVTable\s*\{(.*?)\n\};", src, re.S) +if not m: + sys.exit("未找到 struct VADriverVTable") +body = m.group(1) + +# 2) 去注释(/* */ 与 //) +body = re.sub(r"/\*.*?\*/", "", body, flags=re.S) +body = re.sub(r"//[^\n]*", "", body) + +# 3) 匹配函数指针成员:(*name)(params); +# 头文件里形如 "VAStatus(*vaTerminate)(VADriverContextP ctx);" +# 注意:头文件里返回类型与 (*name) 之间可能换行(如 vaExportSurfaceHandle), +# 所以返回类型部分要允许换行,否则会漏槽位。 +pattern = re.compile( + r"([A-Za-z_][A-Za-z_0-9 \t\*\r\n]*?)" # 返回类型(可跨行) + r"\(\s*\*\s*([A-Za-z_][A-Za-z_0-9]*)\s*\)" # (*name) + r"\s*\((.*?)\)\s*;", # (params); + re.S, +) + +funcs = [] +for ret, name, params in pattern.findall(body): + ret = " ".join(ret.split()) + raw = " ".join(params.split()) + if raw in ("void", ""): + plist = [] + else: + plist = [] + # 参数间以逗号分隔;vtable 里没有函数指针型参数,简单切分即可 + for part in raw.split(","): + part = part.strip() + # 分离类型与参数名:最后一个标识符是名字(数组形如 name[3]) + mm = re.match(r"^(.*?)([A-Za-z_][A-Za-z_0-9]*)\s*((?:\[[^\]]*\])*)$", part) + if not mm: + sys.exit(f"无法解析参数 {part!r} in {name}") + ptype, pname, arr = mm.group(1).strip(), mm.group(2), mm.group(3) + plist.append({"type": ptype, "name": pname, "array": arr}) + funcs.append({"name": name, "ret": ret, "params": plist}) + +json.dump(funcs, sys.stdout, indent=1, ensure_ascii=False) +print() +print(f"# 共 {len(funcs)} 个 vtable 槽位", file=sys.stderr) diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 7d6feb4..01ba82b 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -325,6 +325,60 @@ PID so a hard-killed server does not leave an orphan holding ports 1984 and 8554. A recorded PID is only signalled when its command line still matches `server.py` or `go2rtc`. +## Hardware video decode + +`lfa codec` bridges VA-API in the container to Android's MediaCodec decoders. +The two processes are deliberately separate: MediaCodec is only reachable from +a native Android process, and libva only loads a driver inside the consumer's +process. + +``` +mpv / VLC / ffmpeg + | + | VA-API + v +/usr/local/lib/lfa-codec/dri/lfa_codec_drv_video.so + | + | protocol over a Unix socket + v +/tmp/termux-va/termux-va.sock (Termux $TMPDIR, shared by --shared-tmp) + | + v +$PREFIX/libexec/lfa-codec/termux-va + | + | NDK AMediaCodec + v +Android MediaCodec (H.264 / HEVC / VP9 / VP8) +``` + +The daemon is built with Termux's clang against `libmediandk`. Its default API +level is too low for the NDK calls it uses, so the build pins +`aarch64-linux-android29`. The driver is built inside the container against +the container's `libva` headers. `lfa codec install` regenerates the vtable +with `codec/vaapi/tools/gen_vtable.py`, because the vtable layout follows the +installed libva version; a driver built against a different libva can load but +leave slots null. + +The driver keeps surfaces in ordinary memory and implements `vaDeriveImage`, +`vaCreateImage`, `vaGetImage`, and `vaMapBuffer`. That is the copy path mpv +uses for `--hwdec=vaapi-copy` and ffmpeg uses for `hwdownload`. MediaCodec +returns I420 or NV12; the daemon normalises to NV12 and the driver copies into +the VA surface. There is no DRM render node in the container, so +`vaExportSurfaceHandle` cannot hand a surface to a GPU consumer. Chromium and +Firefox require that export and stay on software decode. mpv and ffmpeg use +the copy path; VLC can decode with `--avcodec-hw=vaapi`, though its GL output +may still choose software. + +The bridge is a decode accelerator, not a zero-copy pipeline. Every frame +crosses the socket and the VA surface, so at low resolutions software decode +can be just as fast. The gain is CPU headroom and larger frames. On the test +phone, H.264 High with B-frames, HEVC, and VP9 decoded byte-for-byte +identically to software at 720p, 1080p, and 4K. + +The socket lives in Termux's private `$TMPDIR`, not on the network. Only the +Termux app and the container that shares `/tmp` can open it. The daemon runs +as the Termux user; it does not need root. + ## CI model ## Session wrappers diff --git a/docs/DECISIONS.md b/docs/DECISIONS.md index eb58e9f..74f9554 100644 --- a/docs/DECISIONS.md +++ b/docs/DECISIONS.md @@ -300,3 +300,42 @@ Cost: the share depends on ffmpeg, the Python `websockets` module, and still breaks the connection, and the browser has to accept a self-signed certificate or use `--http`. VNC remains available as a separate, fully local back end for users who prefer it. + +## D20: hardware decode uses a MediaCodec daemon and a standalone VA-API driver + +Decision: `lfa codec` installs a small Termux daemon that drives Android +MediaCodec through the NDK, plus a libva driver inside the container. The two +talk over a Unix socket in the shared `/tmp`. The driver implements the VA-API +decode and copy paths (`vaDeriveImage`, `vaCreateImage`, `vaGetImage`, +`vaMapBuffer`). It is installed as `lfa_codec_drv_video.so` under +`/usr/local/lib/lfa-codec/dri`, and consumers select it with +`LIBVA_DRIVER_NAME=lfa_codec`. + +Why: MediaCodec is the only decoder API that works on both Qualcomm and +MediaTek phones without a vendor-specific kernel interface. A standalone libva +driver needs no patched Mesa and no custom distro package, so the same build +works on Debian, Ubuntu, Fedora, Arch, and the other supported guests. The +protocol and the driver are derived from projects that had already solved the +hard parts: SPS/PPS reconstruction for H.264/HEVC, frame reordering with +B-frames, MediaCodec back-pressure, and a path-based socket that works across +proot's namespaces. Reimplementing those would add a large maintenance surface +for no user-visible gain. + +The alternatives do not fit this device: + +- A V4L2 M2M driver needs `/dev/video*` and, on newer kernels, dmabufs. The + container cannot open either; MediaTek's decoder nodes are SELinux-protected. +- The termux-va Mesa bridge is the other complete design, but it requires a + custom Mesa build in the container and its Chromium path is Snapdragon-only. + LFA needs a driver that works with the distro's existing libva. +- Zero-copy via `vaExportSurfaceHandle` needs a DRM render node. The container + has no usable `/dev/dri`, and MediaCodec's NDK output does not expose a + dmabuf fd. The copy path is the honest limit. + +Cost: every frame is copied through the CPU, so hardware decode is not always +faster than software at low resolutions. Chromium and Firefox need dmabuf +export and stay on software decode. The bridge supports H.264, HEVC Main, VP9 +Profile 0, and VP8; 10-bit HEVC, VP9 Profile 2, AV1, and some H.264 POC type 1 +streams fall back to software. The source is vendored (GPL-3.0 daemon, +Apache-2.0 driver), which is compatible with this project's GPL-3.0 license +but adds two upstream trees to track. diff --git a/docs/INCOMPATIBLE.md b/docs/INCOMPATIBLE.md index 49986b5..dde1f0c 100644 --- a/docs/INCOMPATIBLE.md +++ b/docs/INCOMPATIBLE.md @@ -31,7 +31,7 @@ on a fast phone. | `iptables`, `nftables`, `ufw`, `firewalld` enforcement | no `CAP_NET_ADMIN` and no netfilter control. A "success" stub would be a dangerous no-op, so LFA does not provide one. | | WireGuard, OpenVPN, Tailscale/ZeroTier **inside the guest** | no `/dev/net/tun` or TUN/TAP. Userspace proxies are the only workaround. | | CUDA, ROCm/HIP, GPU compute through the vendor runtime | no CUDA/ROCm runtime for Android, and no GPU device passthrough to the proot guest. See [GPU acceleration vs GPU compute](#gpu-acceleration-vs-gpu-compute). | -| VA-API, V4L2, NVDEC, hardware video encode/decode | the guest does not receive the hardware codec devices. Software decoding works. | +| VA-API, V4L2, NVDEC, hardware video encode/decode | `lfa codec` provides VA-API decode through Android MediaCodec (H.264, HEVC, VP9, VP8) for mpv, VLC, and ffmpeg. There are no V4L2 codec devices, no NVDEC, no hardware encode, and no dmabuf export; Chromium and Firefox stay on software decode. | | Bluetooth/BlueZ, NFC, GPS as kernel devices, camera as `/dev/video*`, sensors, USB host as `/dev/bus/usb`, IR, fingerprint, telephony, Wi-Fi control | Android owns the hardware. Termux:API can expose some **Android framework** data (battery, location, camera files, sensor values), not kernel devices. | | Real reboot/shutdown/suspend/hibernate, `fastboot`/flashing, ADB host, Magisk modules, real root | an app cannot control the Android system or bootloader. | | Simultaneous X11 + VNC, or multiple displays | LFA uses display `:1` and VNC port `5901` only. | @@ -53,7 +53,7 @@ These may start, or may work on some distros, but LFA does not promise them. | VS Code on Alpine | no ARM64 build of the Microsoft package. Use `code-oss`. | | VLC on Fedora default repositories | needs RPM Fusion. | | GNOME Software, Ubuntu App Center, snap/Flatpak stores | depend on snapd or Flatpak. | -| Hardware-accelerated video in browsers | VirGL accelerates **rendering**, not the video decode block. Some sites still decode in software. | +| Hardware-accelerated video in browsers | `lfa codec` does not change this: Chromium and Firefox need a DRM render node and dmabuf export to use a decoder, and the container has neither. They stay on software decode. mpv, VLC, and ffmpeg use the bridge. VirGL accelerates **rendering**, not the video decode block. | | AppImage **self-mounting** (FUSE) | proot does not expose `/dev/fuse`, so the type-2 mount fails with `fuse: failed to open /dev/fuse`. The application itself can still run: LFA extracts it (`lfa appimage`, or `APPIMAGE_EXTRACT_AND_RUN=1` for a direct run). Extraction does not change architecture or licensing. | | Changing permissions on `/storage/emulated/0` | Android's FUSE shared storage fixes ownership and mode and mounts the tree `noexec`. `chmod` is ignored even as root. Keep files that need a mode in the guest, or run them with `lfa storage exec`. | | Reading `/storage/emulated/0/Android/data` and `Android/obb` | Android 11 and later block both folders for apps, including Termux and anything inside proot. `chmod`, a bind mount, and "All files access" do not help. `lfa storage data` copies them through adb, which runs as the shell user. | diff --git a/docs/TROUBLESHOOTING.md b/docs/TROUBLESHOOTING.md index 30846c9..a3e40aa 100644 --- a/docs/TROUBLESHOOTING.md +++ b/docs/TROUBLESHOOTING.md @@ -55,6 +55,7 @@ Commands that say *inside the distro* are run in a guest shell opened with | App closes when the terminal closes | [§5.5](#55-app-closes-with-the-terminal) | | No sound | [§5.6](#56-no-sound) | | Chromium video is black or GPU rendering crashes | [§5.7](#57-chromium-video-is-black-or-crashes) | +| Hardware video decode fails or mpv falls back to software | [§5.10](#510-hardware-video-decode-does-not-start) | | AppImage: `failed to open /dev/fuse` or nothing starts | [§5.9](#59-an-appimage-does-not-start) | | GNOME does not start | [§6.1](#61-gnome-experimental-does-not-start) | | `sudo` rejects the password or you forgot it | [§7.1](#71-sudo-rejects-the-password) | @@ -1156,6 +1157,52 @@ AppImage or it is truncated; check it with `sha256sum` against the download page. On a musl guest (Alpine), an AppImage that bundles glibc programs may still fail to start after extraction; use a glibc distro for that app. +### 5.10 Hardware video decode does not start + +Symptom: `lfa codec test` fails, mpv prints a hardware-decoder warning and +falls back to software, or the video is black. + +Run the bridge checks first: + +```bash +lfa codec status +lfa codec doctor +``` + +`status` shows the instance, the daemon pid, the socket, and the guest driver. +`doctor` checks the Termux MediaCodec decoders, clang/make, the daemon, the +socket, the driver, and libva. + +Common causes: + +- **The daemon is stopped.** `lfa codec start` starts it. It also starts with + the desktop and stops with `lfa stop`. +- **The socket is not visible in the container.** The daemon listens on + `$TMPDIR/termux-va/termux-va.sock`; the guest sees it only when the login + uses `--shared-tmp`. `lfa codec play`, `test`, and `run` add it. A manual + `proot-distro login` without `--shared-tmp` will not see the socket. +- **The driver was not built.** Re-run `lfa codec install --force -i NAME`. + The build needs `libva-dev`, `libdrm-dev`, `build-essential`, `pkg-config`, + and `python3` in the container; the installer adds them. +- **The desktop is not on `:1`.** The VA-API device is the X display. Start + the desktop with `lfa start -i NAME` and keep Termux:X11 open. +- **The stream uses an unsupported profile.** The bridge advertises H.264 + Constrained Baseline/Main/High, HEVC Main, VP9 Profile 0, and VP8. HEVC + Main10, VP9 Profile 2, AV1, and H.264 POC type 1 streams are not covered; + the player should fall back to software. `lfa codec test` uses H.264. +- **Chromium or Firefox still uses software.** That is expected. Both need a + DRM render node and dmabuf export to hand decoded frames to the GPU, and the + container cannot open `/dev/dri`. Use mpv, VLC, or ffmpeg with the copy + path. + +The daemon log is `$PREFIX/var/lib/lfa-codec/daemon.log`. The driver logs to +stderr when `DMD_VA_LOG=1` is set; `lfa codec run` inherits the environment, +so `lfa codec run -- env DMD_VA_LOG=1 mpv ...` shows its messages. + +Hardware decode is not automatically faster. Every frame is copied through +the CPU, so at 480p or 720p software decode can keep up. The bridge helps most +when the CPU is the bottleneck or the frame is 1080p/4K. + ## 6. Desktop environments ### 6.1 GNOME (experimental) does not start diff --git a/install_linux.sh b/install_linux.sh index feea1b7..921be89 100755 --- a/install_linux.sh +++ b/install_linux.sh @@ -32,6 +32,12 @@ if [ -f "$LFA_DIR/lib/lfa-web.sh" ]; then . "$LFA_DIR/lib/lfa-web.sh" fi +# Hardware video decode helpers (`lfa codec`). Definitions only. +if [ -f "$LFA_DIR/lib/lfa-codec.sh" ]; then + # shellcheck source=lib/lfa-codec.sh + . "$LFA_DIR/lib/lfa-codec.sh" +fi + # ------------------------------------------------------------ # Interrupt safety and temporary artifacts. # The guest setup script carries the install passwords (obfuscated) and is @@ -1531,6 +1537,7 @@ Usage: lfa [options] usb real USB devices: list, scan, attach, tty, flash storage Android shared storage: status, repair, run helpers web share the desktop with a browser on the LAN + codec hardware video decode with Android MediaCodec appimage (app, ai) extract and run an AppImage run run an AppImage once without installing it diagnostics (diag) write a support bundle @@ -1592,6 +1599,8 @@ Examples: lfa web start -i ubuntu lfa web status -i ubuntu lfa web stop -i ubuntu + lfa codec install -i ubuntu + lfa codec play ~/Videos/sample.mp4 lfa appimage add ~/Foo.AppImage lfa appimage list lfa appimage run Foo @@ -6292,6 +6301,7 @@ lfa_cli() { if [ "${1:-}" = "-h" ] || [ "${1:-}" = "--help" ]; then case "$_cmd" in web) lfa_cli_web --help ;; + codec) lfa_cli_codec --help ;; *) lfa_cli_usage ;; esac return 0 @@ -6427,6 +6437,7 @@ lfa_cli() { appimage|app) lfa_cli_appimage "$@" ;; storage) lfa_cli_storage "$@" ;; web) lfa_cli_web "$@" ;; + codec) lfa_cli_codec "$@" ;; run) lfa_appimage_run "$@" ;; update) while [ $# -gt 0 ]; do case "$1" in -i|--instance) CLI_INSTANCE="${2:-}"; shift 2 ;; *) echo "Unknown option: $1" >&2; return 2 ;; esac; done @@ -8709,6 +8720,10 @@ EOF cp -f "$LFA_DIR/lib/lfa-web.sh" "$PREFIX/bin/lfa-web.sh" 2>/dev/null || true chmod +x "$PREFIX/bin/lfa-web.sh" 2>/dev/null || true fi + if [ -f "$LFA_DIR/lib/lfa-codec.sh" ]; then + cp -f "$LFA_DIR/lib/lfa-codec.sh" "$PREFIX/bin/lfa-codec.sh" 2>/dev/null || true + chmod +x "$PREFIX/bin/lfa-codec.sh" 2>/dev/null || true + fi echo "[*] Generating Universal Quick-Launch Scripts..." cat << 'EOF' > $PREFIX/bin/start-linux #!/bin/bash @@ -8722,6 +8737,12 @@ else lfa_pid_matches() { local _p="$1" _c; shift; [ -n "$_p" ] || return 1; kill -0 "$_p" 2>/dev/null || return 1; _c="$(tr '\0' ' ' < "/proc/$_p/cmdline" 2>/dev/null)" || return 1; for _pat in "$@"; do case "$_c" in *"$_pat"*) return 0 ;; esac; done; return 1; } fi +# Start the MediaCodec daemon before the desktop when the bridge is installed. +if [ -f "$PREFIX/bin/lfa-codec.sh" ]; then + . "$PREFIX/bin/lfa-codec.sh" + lfa_codec_autostart 2>/dev/null || true +fi + usage() { cat <<'USAGE' Usage: start-linux [options] @@ -9333,6 +9354,10 @@ if [ -f "$PREFIX/bin/lfa-web.sh" ]; then . "$PREFIX/bin/lfa-web.sh" lfa_web_stop_one "$DISTRO" 1 2>/dev/null || true fi +if [ -f "$PREFIX/bin/lfa-codec.sh" ]; then + . "$PREFIX/bin/lfa-codec.sh" + lfa_codec_stop >/dev/null 2>&1 || true +fi sleep 2 lfa_clear_stale_x1 EOF @@ -9482,7 +9507,7 @@ EOF if [ "$LFA_DIR" != "$LFA_RUNTIME" ] && [ -f "$LFA_DIR/install_linux.sh" ]; then mkdir -p "$LFA_RUNTIME" cp -f "$LFA_DIR/install_linux.sh" "$LFA_RUNTIME/install_linux.sh" 2>/dev/null || true - for _d in lib plugins assets web; do + for _d in lib plugins assets web codec; do if [ -d "$LFA_DIR/$_d" ]; then rm -rf "${LFA_RUNTIME:?}/$_d" cp -R "$LFA_DIR/$_d" "$LFA_RUNTIME/$_d" 2>/dev/null || true @@ -9558,6 +9583,15 @@ uninstall_linux() { . "$PREFIX/bin/lfa-web.sh" lfa_web_stop_one "$INSTANCE_NAME" 1 2>/dev/null || true fi + if [ -f "$PREFIX/bin/lfa-codec.sh" ]; then + # shellcheck source=lib/lfa-codec.sh + . "$PREFIX/bin/lfa-codec.sh" + lfa_codec_stop >/dev/null 2>&1 || true + lfa_codec_state_load 2>/dev/null || true + if [ "${LFA_CODEC_INSTANCE:-}" = "$INSTANCE_NAME" ]; then + rm -rf "$PREFIX/var/lib/lfa-codec" + fi + fi echo "[*] Removing $INSTANCE_NAME (this can take a moment)..." proot-distro remove "$INSTANCE_NAME" >/dev/null 2>&1 || true diff --git a/lib/lfa-codec.sh b/lib/lfa-codec.sh new file mode 100644 index 0000000..26e44f4 --- /dev/null +++ b/lib/lfa-codec.sh @@ -0,0 +1,666 @@ +#!/bin/bash +# Hardware video decode for the Linux container (`lfa codec`). +# +# Two pieces are installed: +# * a Termux-side daemon that drives Android MediaCodec through the NDK +# * a libva driver inside the guest that speaks to that daemon over the +# shared /tmp directory +# +# Definitions only. Nothing runs when this file is sourced. + +LFA_CODEC_STATE_DIR="${LFA_CODEC_STATE_DIR:-$PREFIX/var/lib/lfa-codec}" +LFA_CODEC_STATE="$LFA_CODEC_STATE_DIR/state" +LFA_CODEC_LOG="$LFA_CODEC_STATE_DIR/daemon.log" +LFA_CODEC_LIBEXEC="$PREFIX/libexec/lfa-codec" +LFA_CODEC_DAEMON="$LFA_CODEC_LIBEXEC/termux-va" +LFA_CODEC_SOCKET="${TMPDIR:-$PREFIX/tmp}/termux-va/termux-va.sock" +LFA_CODEC_DRIVER_NAME="lfa_codec" +LFA_CODEC_GUEST_DRIVER_DIR="/usr/local/lib/lfa-codec/dri" +LFA_CODEC_GUEST_ENV="/usr/local/lib/lfa-codec/env.sh" + +lfa_codec_source_dir() { + if [ -d "${LFA_DIR:-}/codec" ]; then + printf '%s' "$LFA_DIR/codec" + elif [ -d "${LFA_RUNTIME:-}/codec" ]; then + printf '%s' "$LFA_RUNTIME/codec" + else + printf '%s' "${LFA_DIR:-$PWD}/codec" + fi +} + +# Turn a path the caller can see into a path the container can see. URLs and +# paths that the guest already mounts are passed through; a Termux-local file +# is copied into the shared /tmp. +lfa_codec_guest_file() { + local _file="$1" + case "$_file" in + http://*|https://*|rtsp://*|rtmp://*|ftp://*) + printf '%s' "$_file"; return 0 ;; + /sdcard/*|/storage/*|/media/*|/tmp/*) + printf '%s' "$_file"; return 0 ;; + esac + if [ -f "$_file" ]; then + mkdir -p "$PREFIX/tmp/lfa-codec-media" 2>/dev/null || return 1 + cp -f "$_file" "$PREFIX/tmp/lfa-codec-media/" 2>/dev/null || return 1 + printf '/tmp/lfa-codec-media/%s' "$(basename "$_file")" + return 0 + fi + printf '%s' "$_file" +} + +lfa_codec_state_load() { + LFA_CODEC_INSTANCE="" + LFA_CODEC_USER="" + LFA_CODEC_PID="" + LFA_CODEC_INSTALLED=0 + [ -f "$LFA_CODEC_STATE" ] || return 1 + local _k _v + while IFS='=' read -r _k _v; do + case "$_k" in + installed) LFA_CODEC_INSTALLED="$_v" ;; + instance) LFA_CODEC_INSTANCE="$_v" ;; + user) LFA_CODEC_USER="$_v" ;; + pid) LFA_CODEC_PID="$_v" ;; + esac + done < "$LFA_CODEC_STATE" + [ "$LFA_CODEC_INSTALLED" = "1" ] +} + +lfa_codec_state_set() { # $1 = key, $2 = value + local _key="$1" _value="$2" _tmp + mkdir -p "$LFA_CODEC_STATE_DIR" 2>/dev/null || return 1 + _tmp="$LFA_CODEC_STATE.tmp.$$" + if [ -f "$LFA_CODEC_STATE" ]; then + grep -v "^${_key}=" "$LFA_CODEC_STATE" > "$_tmp" 2>/dev/null || true + else + : > "$_tmp" + fi + printf '%s=%s\n' "$_key" "$_value" >> "$_tmp" + mv -f "$_tmp" "$LFA_CODEC_STATE" 2>/dev/null || return 1 +} + +lfa_codec_pid() { + lfa_codec_state_load || return 0 + [ -n "$LFA_CODEC_PID" ] || return 0 + kill -0 "$LFA_CODEC_PID" 2>/dev/null || return 0 + local _cmd + _cmd="$(tr '\0' ' ' < "/proc/$LFA_CODEC_PID/cmdline" 2>/dev/null || true)" + case "$_cmd" in + *"$LFA_CODEC_DAEMON"*) printf '%s' "$LFA_CODEC_PID" ;; + esac +} + +lfa_codec_running() { + [ -n "$(lfa_codec_pid)" ] +} + +lfa_codec_installed() { + lfa_codec_state_load || return 1 + [ -x "$LFA_CODEC_DAEMON" ] || return 1 + [ -S "$LFA_CODEC_SOCKET" ] || return 1 + return 0 +} + +lfa_codec_guest_user() { + if declare -F lfa_appimage_user >/dev/null 2>&1 && [ -n "${LFA_CODEC_INSTANCE:-}" ]; then + lfa_appimage_user "$LFA_CODEC_INSTANCE" 2>/dev/null || true + fi +} + +lfa_codec_guest_run() { # $1 = user (empty = root), rest = command + local _user="$1"; shift + local _inst="${LFA_CODEC_INSTANCE:-${INSTANCE_NAME:-}}" + local -a _args=(login) + local _flags + _flags="$(pd_login_flags 2>/dev/null || true)" + if [ -n "$_flags" ]; then + _args+=("$_flags") + fi + _args+=("$_inst") + if [ -n "$_user" ]; then + _args+=(--user "$_user") + fi + _args+=(--shared-tmp --) + # shellcheck disable=SC2086 # pd_login_flags is a word list + proot-distro "${_args[@]}" "$@" +} + +lfa_codec_guest_install_pkgs() { + lfa_codec_guest_run "" bash -lc ' + set -e + if command -v apt-get >/dev/null 2>&1; then + export DEBIAN_FRONTEND=noninteractive + # A desktop update or a previous install may still hold the apt + # lock for a few seconds. + _i=0 + while [ "$_i" -lt 3 ]; do + if apt-get update -qq; then break; fi + _i=$((_i + 1)); sleep 3 + done + [ "$_i" -lt 3 ] || { echo "lfa codec: apt update is locked" >&2; exit 1; } + _i=0 + while [ "$_i" -lt 3 ]; do + if apt-get install -y -qq build-essential pkg-config libva-dev libdrm-dev python3; then break; fi + _i=$((_i + 1)); sleep 3 + done + [ "$_i" -lt 3 ] || { echo "lfa codec: apt is still locked" >&2; exit 1; } + apt-get install -y -qq ffmpeg >/dev/null 2>&1 || true + elif command -v dnf >/dev/null 2>&1; then + dnf install -y gcc gcc-c++ make pkgconf-pkg-config libva-devel libdrm-devel python3 + dnf install -y ffmpeg >/dev/null 2>&1 || true + elif command -v zypper >/dev/null 2>&1; then + zypper --non-interactive install gcc make pkg-config libva-devel libdrm-devel python3 + zypper --non-interactive install ffmpeg >/dev/null 2>&1 || true + elif command -v pacman >/dev/null 2>&1; then + pacman -Sy --noconfirm base-devel pkgconf libva libdrm python + pacman -S --noconfirm ffmpeg >/dev/null 2>&1 || true + elif command -v xbps-install >/dev/null 2>&1; then + xbps-install -Sy base-devel pkg-config libva-devel libdrm-devel python3 + xbps-install -Sy ffmpeg >/dev/null 2>&1 || true + elif command -v apk >/dev/null 2>&1; then + apk add build-base pkgconf libva-dev libdrm-dev python3 + apk add ffmpeg >/dev/null 2>&1 || true + else + echo "lfa codec: no supported package manager in the container." >&2 + exit 1 + fi + ' +} + +lfa_codec_write_guest_env() { + local _tmp="$PREFIX/tmp/lfa-codec-env.sh" + cat > "$_tmp" <&2 + return 1 + } + _make="$(command -v make 2>/dev/null || true)" + _cc="$(command -v clang 2>/dev/null || true)" + fi + [ -n "$_make" ] && [ -n "$_cc" ] || { + echo "[!] clang and make are required to build the daemon." >&2 + return 1 + } + echo "[*] Building the MediaCodec daemon..." + "$_make" -C "$_src/daemon" clean >/dev/null 2>&1 || true + "$_make" -C "$_src/daemon" CC="$_cc" BINDIR="$LFA_CODEC_LIBEXEC" install || return 1 + [ -x "$LFA_CODEC_DAEMON" ] || { + echo "[!] The daemon was not installed at $LFA_CODEC_DAEMON." >&2 + return 1 + } +} + +lfa_codec_build_driver() { + local _src="$1" _stage="$PREFIX/tmp/lfa-codec-build" + echo "[*] Building the VA-API driver in $LFA_CODEC_INSTANCE..." + rm -rf "$_stage" + mkdir -p "$_stage" || return 1 + cp -R "$_src/vaapi" "$_stage/vaapi" || return 1 + lfa_codec_guest_run "" bash -lc ' + set -e + cd /tmp/lfa-codec-build/vaapi + make clean >/dev/null 2>&1 || true + make gen + make -j2 + make install + ' || { + echo "[!] The VA-API driver failed to build." >&2 + return 1 + } +} + +lfa_codec_driver_path() { + local _rootfs + _rootfs="$(pd_rootfs "${LFA_CODEC_INSTANCE:-}" 2>/dev/null || true)" + [ -n "$_rootfs" ] || return 1 + printf '%s%s/%s_drv_video.so' "$_rootfs" "$LFA_CODEC_GUEST_DRIVER_DIR" "$LFA_CODEC_DRIVER_NAME" +} + +lfa_codec_start() { + lfa_codec_state_load || { + echo "[!] The codec bridge is not installed. Run: lfa codec install" >&2 + return 1 + } + local _pid + _pid="$(lfa_codec_pid)" + if [ -n "$_pid" ]; then + echo "Codec daemon already running (pid $_pid)." + return 0 + fi + [ -x "$LFA_CODEC_DAEMON" ] || { + echo "[!] Missing $LFA_CODEC_DAEMON. Re-run: lfa codec install" >&2 + return 1 + } + mkdir -p "$LFA_CODEC_STATE_DIR" || return 1 + : > "$LFA_CODEC_LOG" 2>/dev/null || true + nohup "$LFA_CODEC_DAEMON" >> "$LFA_CODEC_LOG" 2>&1 & + _pid=$! + lfa_codec_state_set pid "$_pid" 2>/dev/null || true + local _i=0 + while [ "$_i" -lt 50 ]; do + if [ -S "$LFA_CODEC_SOCKET" ]; then + break + fi + kill -0 "$_pid" 2>/dev/null || break + sleep 0.1 2>/dev/null || sleep 1 + _i=$((_i + 1)) + done + if [ -S "$LFA_CODEC_SOCKET" ] && kill -0 "$_pid" 2>/dev/null; then + echo "Codec daemon started (pid $_pid)." + echo "Socket: $LFA_CODEC_SOCKET" + return 0 + fi + echo "[!] The codec daemon did not start." >&2 + tail -5 "$LFA_CODEC_LOG" 2>/dev/null >&2 || true + return 1 +} + +lfa_codec_stop() { + local _pid + _pid="$(lfa_codec_pid)" + if [ -z "$_pid" ]; then + echo "Codec daemon is not running." + lfa_codec_state_set pid "" 2>/dev/null || true + return 0 + fi + echo "Stopping codec daemon (pid $_pid)..." + kill "$_pid" 2>/dev/null || true + local _i=0 + while [ "$_i" -lt 30 ] && kill -0 "$_pid" 2>/dev/null; do + sleep 0.1 2>/dev/null || sleep 1 + _i=$((_i + 1)) + done + if kill -0 "$_pid" 2>/dev/null; then + kill -9 "$_pid" 2>/dev/null || true + fi + lfa_codec_state_set pid "" 2>/dev/null || true + echo "Codec daemon stopped." +} + +lfa_codec_autostart() { + lfa_codec_state_load || return 0 + [ "$LFA_CODEC_INSTALLED" = "1" ] || return 0 + if lfa_codec_running; then + return 0 + fi + lfa_codec_start >/dev/null 2>&1 || true +} + +# Existing installs have start-linux/stop-linux generated by an older LFA. +# Add the hooks once so the daemon follows the desktop without a reinstall. +lfa_codec_patch_launchers() { + local _start="$PREFIX/bin/start-linux" _stop="$PREFIX/bin/stop-linux" + if [ -f "$_stop" ] && ! grep -q 'lfa_codec_stop' "$_stop" 2>/dev/null; then + cat >> "$_stop" <<'EOF' + +# Stop the MediaCodec daemon if the codec bridge is installed. +if [ -f "$PREFIX/bin/lfa-codec.sh" ]; then + . "$PREFIX/bin/lfa-codec.sh" + lfa_codec_stop >/dev/null 2>&1 || true +fi +EOF + fi + if [ -f "$_start" ] && ! grep -q 'lfa_codec_autostart' "$_start" 2>/dev/null; then + awk -v p="$PREFIX" ' + BEGIN { done = 0 } + /^usage\(\) \{/ && !done { + print "# Start the MediaCodec daemon if the codec bridge is installed." + print "if [ -f \"" p "/bin/lfa-codec.sh\" ]; then" + print " . \"" p "/bin/lfa-codec.sh\"" + print " lfa_codec_autostart 2>/dev/null || true" + print "fi" + print "" + done = 1 + } + { print } + ' "$_start" > "$_start.tmp" && mv "$_start.tmp" "$_start" + chmod +x "$_start" 2>/dev/null || true + fi +} + +lfa_codec_status() { + local _pid _driver _sock="missing" _daemon="not installed" + echo "Codec bridge" + if ! lfa_codec_state_load; then + echo " status: not installed" + echo " install: lfa codec install -i NAME" + return 1 + fi + _pid="$(lfa_codec_pid)" + if [ -n "$_pid" ]; then + _daemon="running (pid $_pid)" + elif [ -x "$LFA_CODEC_DAEMON" ]; then + _daemon="installed, stopped" + fi + if [ -S "$LFA_CODEC_SOCKET" ]; then + _sock="ok" + fi + _driver="$(lfa_codec_driver_path 2>/dev/null || true)" + echo " instance: ${LFA_CODEC_INSTANCE:-unknown}" + echo " user: ${LFA_CODEC_USER:-unknown}" + echo " daemon: $_daemon" + echo " socket: $_sock ($LFA_CODEC_SOCKET)" + if [ -n "$_driver" ] && [ -f "$_driver" ]; then + echo " driver: installed ($_driver)" + else + echo " driver: missing" + fi + echo " play: lfa codec play FILE" +} + +lfa_codec_doctor() { + local _rc=0 _driver _rootfs _sdk _soc _dec="" + _sdk="$(getprop ro.build.version.sdk 2>/dev/null || true)" + _soc="$(getprop ro.soc.model 2>/dev/null || getprop ro.hardware 2>/dev/null || true)" + echo "Android: SDK ${_sdk:-unknown}, ${_soc:-unknown}" + if command -v ffmpeg >/dev/null 2>&1; then + _dec="$(ffmpeg -hide_banner -decoders 2>/dev/null | grep -E 'h264_mediacodec|hevc_mediacodec' || true)" + fi + if [ -n "$_dec" ]; then + echo "[ok] Termux ffmpeg exposes the MediaCodec decoders" + else + echo "[!] Termux ffmpeg does not list h264_mediacodec; reinstall ffmpeg" + _rc=1 + fi + if command -v clang >/dev/null 2>&1 && command -v make >/dev/null 2>&1; then + echo "[ok] clang and make are available for the daemon build" + else + echo "[!] clang/make missing: pkg install clang make" + _rc=1 + fi + if ! lfa_codec_state_load; then + echo "[!] codec bridge is not installed: lfa codec install -i NAME" + return 1 + fi + if [ -x "$LFA_CODEC_DAEMON" ]; then + echo "[ok] daemon binary: $LFA_CODEC_DAEMON" + else + echo "[!] daemon binary is missing" + _rc=1 + fi + if [ -n "$(lfa_codec_pid)" ]; then + echo "[ok] daemon is running" + else + echo "[!] daemon is stopped: lfa codec start" + _rc=1 + fi + if [ -S "$LFA_CODEC_SOCKET" ]; then + echo "[ok] socket: $LFA_CODEC_SOCKET" + else + echo "[!] socket is missing; the guest cannot reach the daemon" + _rc=1 + fi + _driver="$(lfa_codec_driver_path 2>/dev/null || true)" + if [ -n "$_driver" ] && [ -f "$_driver" ]; then + echo "[ok] guest driver: $_driver" + else + echo "[!] guest driver is missing; re-run: lfa codec install" + _rc=1 + fi + _rootfs="$(pd_rootfs "$LFA_CODEC_INSTANCE" 2>/dev/null || true)" + if [ -n "$_rootfs" ] && \ + [ -n "$(find "$_rootfs/usr" -name 'libva.so.2' -print -quit 2>/dev/null)" ]; then + echo "[ok] libva is installed in the container" + else + echo "[!] libva2 is missing in the container" + _rc=1 + fi + if [ -w /dev/dri/renderD128 ] 2>/dev/null; then + echo "[ok] /dev/dri/renderD128 is writable; dmabuf export may work" + else + echo "[i] /dev/dri/renderD128 is not available; players use vaapi-copy" + echo " (Chromium and Firefox need dmabuf export, so they stay on software decode)" + fi + return "$_rc" +} + +lfa_codec_test() { + local _file="${1:-}" _hw _sw _user + lfa_codec_state_load || { + echo "[!] Install the bridge first: lfa codec install -i NAME" >&2 + return 1 + } + lfa_codec_start >/dev/null || return 1 + _user="${LFA_CODEC_USER:-$(lfa_codec_guest_user)}" + [ -n "$_user" ] || _user="user" + if [ -z "$_file" ]; then + echo "[*] Creating a small H.264 sample in the container..." + _file="/tmp/lfa-codec-test.mp4" + lfa_codec_guest_run "$_user" bash -lc ' + command -v ffmpeg >/dev/null 2>&1 || { echo "ffmpeg is missing" >&2; exit 1; } + ffmpeg -hide_banner -loglevel error -y -f lavfi \ + -i testsrc2=size=320x240:rate=30 -t 1 \ + -c:v libx264 -preset ultrafast -pix_fmt yuv420p "$1" + ' _ "$_file" || { + echo "[!] Could not create the sample. Install ffmpeg with libx264," >&2 + echo " or pass an existing file: lfa codec test FILE" >&2 + return 1 + } + else + _file="$(lfa_codec_guest_file "$_file")" || return 1 + fi + echo "[*] Decoding with the MediaCodec bridge..." + _hw="$(lfa_codec_guest_run "$_user" bash -lc ' + . /usr/local/lib/lfa-codec/env.sh + ffmpeg -hide_banner -loglevel error -hwaccel vaapi -vaapi_device :1 \ + -hwaccel_output_format vaapi -i "$1" \ + -vf hwdownload,format=nv12 -f md5 - 2>/dev/null + ' _ "$_file" 2>/dev/null | sed -n 's/^MD5=//p' | tail -1)" + _sw="$(lfa_codec_guest_run "$_user" bash -lc ' + ffmpeg -hide_banner -loglevel error -i "$1" -pix_fmt nv12 -f md5 - 2>/dev/null + ' _ "$_file" 2>/dev/null | sed -n 's/^MD5=//p' | tail -1)" + if [ -z "$_hw" ] || [ -z "$_sw" ]; then + echo "[!] Decode test failed. Check that the desktop is running and try:" + echo " lfa codec doctor" + return 1 + fi + echo " hardware: $_hw" + echo " software: $_sw" + if [ "$_hw" = "$_sw" ]; then + echo "[ok] Hardware decode matches software decode." + return 0 + fi + echo "[!] Hardware and software output differ." + return 1 +} + +lfa_codec_play() { + local _file="${1:-}" + [ -n "$_file" ] || { + echo "Usage: lfa codec play FILE [mpv options]" >&2 + return 2 + } + shift || true + lfa_codec_state_load || { + echo "[!] Install the bridge first: lfa codec install -i NAME" >&2 + return 1 + } + _file="$(lfa_codec_guest_file "$_file")" || { + echo "[!] Could not copy the file into the shared /tmp." >&2 + return 1 + } + lfa_codec_start >/dev/null || return 1 + local _user="${LFA_CODEC_USER:-}" + [ -n "$_user" ] || _user="$(lfa_codec_guest_user)" + [ -n "$_user" ] || _user="user" + if ! lfa_codec_guest_run "$_user" sh -c 'command -v mpv >/dev/null 2>&1'; then + echo "[!] mpv is not installed in the container. Install it first:" + echo " lfa shell -i $LFA_CODEC_INSTANCE --user" + echo " sudo apt install mpv" + return 1 + fi + lfa_codec_guest_run "$_user" bash -lc ' + . /usr/local/lib/lfa-codec/env.sh + exec mpv --hwdec=vaapi-copy --vo=x11 "$@" + ' _ "$_file" "$@" +} + +lfa_codec_env() { + lfa_codec_state_load || { + echo "[!] Install the bridge first: lfa codec install -i NAME" >&2 + return 1 + } + cat <&2; return 2 ;; + esac + done + select_installed_instance || return 1 + [ -n "${INSTANCE_NAME:-}" ] || return 1 + local _src _user + _src="$(lfa_codec_source_dir)" + if [ ! -f "$_src/daemon/termux-va.c" ] || [ ! -f "$_src/vaapi/Makefile" ]; then + echo "[!] codec sources are missing under $_src." >&2 + echo " Re-run the installer or update the runtime copy." >&2 + return 1 + fi + if [ "$_force" != "1" ] && lfa_codec_state_load && [ "$LFA_CODEC_INSTALLED" = "1" ]; then + echo "The codec bridge is already installed for ${LFA_CODEC_INSTANCE:-$INSTANCE_NAME}." + echo "Use --force to rebuild it." + return 0 + fi + command -v proot-distro >/dev/null 2>&1 || { + echo "[!] proot-distro is not available." >&2 + return 1 + } + LFA_CODEC_INSTANCE="$INSTANCE_NAME" + _user="$(lfa_codec_guest_user)" + [ -n "$_user" ] || _user="user" + LFA_CODEC_USER="$_user" + echo "Installing the codec bridge for $LFA_CODEC_INSTANCE (user $_user)." + # A rebuild must not leave the old daemon serving the old binary. + lfa_codec_stop >/dev/null 2>&1 || true + lfa_codec_build_daemon "$_src" || return 1 + lfa_codec_guest_install_pkgs || { + echo "[!] Could not install the container build packages." >&2 + return 1 + } + lfa_codec_build_driver "$_src" || return 1 + lfa_codec_write_guest_env || return 1 + mkdir -p "$LFA_CODEC_STATE_DIR" || return 1 + { + echo "installed=1" + echo "instance=$LFA_CODEC_INSTANCE" + echo "user=$_user" + echo "pid=" + echo "driver=$LFA_CODEC_DRIVER_NAME" + } > "$LFA_CODEC_STATE" + if [ -f "$(dirname "$_src")/lib/lfa-codec.sh" ]; then + cp -f "$(dirname "$_src")/lib/lfa-codec.sh" "$PREFIX/bin/lfa-codec.sh" 2>/dev/null || true + chmod +x "$PREFIX/bin/lfa-codec.sh" 2>/dev/null || true + fi + lfa_codec_patch_launchers + echo "[ok] Installed for $LFA_CODEC_INSTANCE." + echo " daemon: $LFA_CODEC_DAEMON" + echo " driver: $LFA_CODEC_GUEST_DRIVER_DIR/${LFA_CODEC_DRIVER_NAME}_drv_video.so" + if [ "$_no_start" != "1" ]; then + lfa_codec_start || true + fi + echo + echo "Next:" + echo " lfa codec test" + echo " lfa codec play /path/to/video.mp4" +} + +lfa_codec_usage() { + cat <<'HELP' +Hardware video decode with Android MediaCodec + +Usage: lfa codec [options] + + install [--force] [--no-start] build and install the daemon and VA-API driver + status show daemon, socket, and driver state + start start the MediaCodec daemon + stop stop the MediaCodec daemon + doctor check the whole bridge + test [FILE] decode a file (or a small sample) and compare + the hardware result with software decode + play FILE [mpv options] play a file with mpv --hwdec=vaapi-copy + env print the environment for the container + run -- COMMAND... run a command in the container with that + environment + +Options: + -i, --instance NAME select the distribution (default: the only one) + +Examples: + lfa codec install -i ubuntu + lfa codec doctor + lfa codec play ~/Videos/sample.mp4 + lfa codec run -- ffmpeg -hwaccel vaapi -vaapi_device :1 -i in.mp4 -f null - + +Notes: + FILE may be a path in the container, a URL, or a file in Termux. A + Termux-local file is copied into the shared /tmp before playback. + H.264, HEVC, VP9, and VP8 decode are supported. The bridge copies frames + through the CPU, so use vaapi-copy players (mpv, ffmpeg). Chromium and + Firefox need dmabuf export, which the container usually cannot provide. +HELP +} + +lfa_cli_codec() { + local _cmd="${1:-help}" + [ $# -gt 0 ] && shift || true + case "$_cmd" in + install) lfa_codec_install "$@" ;; + status|st) lfa_codec_status ;; + start|up) lfa_codec_start ;; + stop|down) lfa_codec_stop ;; + doctor|check) lfa_codec_doctor ;; + test) lfa_codec_test "$@" ;; + play) lfa_codec_play "$@" ;; + env) lfa_codec_env ;; + run) + if [ "${1:-}" = "--" ]; then + shift + fi + [ $# -gt 0 ] || { echo "Usage: lfa codec run -- COMMAND..." >&2; return 2; } + lfa_codec_state_load || { echo "[!] Install the bridge first." >&2; return 1; } + lfa_codec_start >/dev/null || return 1 + local _user="${LFA_CODEC_USER:-}" + [ -n "$_user" ] || _user="$(lfa_codec_guest_user)" + [ -n "$_user" ] || _user="user" + lfa_codec_guest_run "$_user" bash -lc ' + . /usr/local/lib/lfa-codec/env.sh + exec "$@" + ' _ "$@" ;; + help|-h|--help) lfa_codec_usage ;; + *) echo "Unknown codec command: $_cmd" >&2; lfa_codec_usage >&2; return 2 ;; + esac +} diff --git a/tests/test-all.sh b/tests/test-all.sh index 4212db9..5b8d672 100755 --- a/tests/test-all.sh +++ b/tests/test-all.sh @@ -2649,6 +2649,83 @@ bash "$REPO/install_linux.sh" --cli web stop --all -i web1 > "$T/y14all.log" 2>& [ "$rc" = "2" ] && pass=$((pass+1)) || { fail=$((fail+1)); echo "FAIL: Y14 stop --all with -i exit $rc"; } check "Y14 stop --all with -i refused" 'cannot be used together' "$T/y14all.log" +echo "===== Y15: lfa codec (MediaCodec VA-API bridge) =====" +fresh_env +CODECLIB="$REPO/lib/lfa-codec.sh" +[ -f "$CODECLIB" ] && pass=$((pass+1)) || { fail=$((fail+1)); echo "FAIL: Y15 codec helper missing"; } +[ -f "$REPO/codec/daemon/termux-va.c" ] && pass=$((pass+1)) || { fail=$((fail+1)); echo "FAIL: Y15 daemon source missing"; } +[ -f "$REPO/codec/vaapi/Makefile" ] && pass=$((pass+1)) || { fail=$((fail+1)); echo "FAIL: Y15 VA-API driver missing"; } +[ -f "$REPO/codec/README.md" ] && pass=$((pass+1)) || { fail=$((fail+1)); echo "FAIL: Y15 codec README missing"; } + +bash "$REPO/install_linux.sh" --cli codec --help > "$T/y15help.log" 2>&1; rc=$? +[ "$rc" = "0" ] && pass=$((pass+1)) || { fail=$((fail+1)); echo "FAIL: Y15 help exit $rc"; } +check "Y15 help install" 'install [--force] [--no-start]' "$T/y15help.log" +check "Y15 help play" 'play FILE [mpv options]' "$T/y15help.log" +check "Y15 help codecs" 'H.264, HEVC, VP9, and VP8' "$T/y15help.log" + +bash "$REPO/install_linux.sh" --cli codec bogus > "$T/y15bogus.log" 2>&1; rc=$? +[ "$rc" = "2" ] && pass=$((pass+1)) || { fail=$((fail+1)); echo "FAIL: Y15 unknown command exit $rc"; } +check "Y15 unknown command" 'Unknown codec command' "$T/y15bogus.log" + +bash "$REPO/install_linux.sh" --cli codec status > "$T/y15status.log" 2>&1 || true +check "Y15 status not installed" 'not installed' "$T/y15status.log" +check "Y15 status install hint" 'lfa codec install -i NAME' "$T/y15status.log" + +bash "$REPO/install_linux.sh" --cli codec play > "$T/y15play.log" 2>&1; rc=$? +[ "$rc" = "2" ] && pass=$((pass+1)) || { fail=$((fail+1)); echo "FAIL: Y15 play without file exit $rc"; } +check "Y15 play usage" 'Usage: lfa codec play FILE' "$T/y15play.log" + +_src="$(bash -c 'PREFIX="$1"; LFA_DIR="$2"; . "$3"; lfa_codec_source_dir' _ "$T/prefix" "$REPO" "$CODECLIB")" +[ "$_src" = "$REPO/codec" ] && pass=$((pass+1)) || { fail=$((fail+1)); echo "FAIL: Y15 source dir [$_src]"; } + +mkdir -p "$T/prefix/var/lib/lfa-codec" +printf 'installed=1\ninstance=codec1\nuser=tester\npid=\n' > "$T/prefix/var/lib/lfa-codec/state" +_state="$(bash -c 'PREFIX="$1"; . "$2"; lfa_codec_state_load; printf "%s/%s" "$LFA_CODEC_INSTANCE" "$LFA_CODEC_USER"' _ "$T/prefix" "$CODECLIB")" +[ "$_state" = "codec1/tester" ] && pass=$((pass+1)) || { fail=$((fail+1)); echo "FAIL: Y15 state parse [$_state]"; } + +# Use a relative name: an absolute $T path is under /tmp on a Linux CI box, +# and /tmp is the shared directory the helper deliberately passes through. +printf 'not a real video\n' > "$T/media.mp4" +_gf="$(cd "$T" && bash -c 'PREFIX="$1"; . "$2"; lfa_codec_guest_file "$3"' _ "$T/prefix" "$CODECLIB" "media.mp4")" +[ "$_gf" = "/tmp/lfa-codec-media/media.mp4" ] && [ -f "$T/prefix/tmp/lfa-codec-media/media.mp4" ] \ + && pass=$((pass+1)) || { fail=$((fail+1)); echo "FAIL: Y15 Termux file not staged [$_gf]"; } +_gf="$(bash -c 'PREFIX="$1"; . "$2"; lfa_codec_guest_file "$3"' _ "$T/prefix" "$CODECLIB" "/sdcard/Movies/x.mp4")" +[ "$_gf" = "/sdcard/Movies/x.mp4" ] && pass=$((pass+1)) \ + || { fail=$((fail+1)); echo "FAIL: Y15 shared path rewritten [$_gf]"; } + +# A live pid that is not the daemon must never be signalled. +sleep 60 & _spid=$! +printf 'installed=1\ninstance=codec1\nuser=tester\npid=%s\n' "$_spid" > "$T/prefix/var/lib/lfa-codec/state" +_pid="$(bash -c 'PREFIX="$1"; . "$2"; lfa_codec_pid' _ "$T/prefix" "$CODECLIB")" +[ -z "$_pid" ] && pass=$((pass+1)) || { fail=$((fail+1)); echo "FAIL: Y15 unrelated pid accepted [$_pid]"; } +bash -c 'PREFIX="$1"; . "$2"; lfa_codec_stop' _ "$T/prefix" "$CODECLIB" > "$T/y15stop.log" 2>&1 +check "Y15 stop ignores unrelated pid" 'not running' "$T/y15stop.log" +kill -0 "$_spid" 2>/dev/null && pass=$((pass+1)) \ + || { fail=$((fail+1)); echo "FAIL: Y15 stop killed an unrelated process"; } +kill "$_spid" 2>/dev/null || true + +check "Y15 daemon API target" 'aarch64-linux-android29' "$REPO/codec/daemon/Makefile" +check "Y15 driver target" 'lfa_codec_drv_video.so' "$REPO/codec/vaapi/Makefile" +check "Y15 driver path" '/usr/local/lib/lfa-codec/dri' "$REPO/codec/vaapi/Makefile" +check "Y15 driver vendor" 'LFA MediaCodec VA-API driver' "$REPO/codec/vaapi/src/driver.h" +check "Y15 env driver" 'LFA_CODEC_DRIVER_NAME="lfa_codec"' "$CODECLIB" +check "Y15 env endpoint" 'DMD_ENDPOINT=unix:/tmp/termux-va/termux-va.sock' "$CODECLIB" +check "Y15 runtime copy" 'for _d in lib plugins assets web codec' "$REPO/install_linux.sh" +check "Y15 start hook" 'lfa_codec_autostart' "$REPO/install_linux.sh" +check "Y15 stop hook" 'lfa_codec_stop' "$REPO/install_linux.sh" +check "Y15 daemon license" 'GNU GENERAL PUBLIC LICENSE' "$REPO/codec/daemon/LICENSE" +check "Y15 driver license" 'Apache License' "$REPO/codec/vaapi/LICENSE" + +mkdir -p "$T/prefix/bin" +printf '#!/bin/bash\nusage() { :; }\n' > "$T/prefix/bin/start-linux" +printf '#!/bin/bash\necho stop\n' > "$T/prefix/bin/stop-linux" +bash -c 'PREFIX="$1"; . "$2"; lfa_codec_patch_launchers' _ "$T/prefix" "$CODECLIB" +check "Y15 patch start hook" 'lfa_codec_autostart' "$T/prefix/bin/start-linux" +check "Y15 patch stop hook" 'lfa_codec_stop' "$T/prefix/bin/stop-linux" +bash -c 'PREFIX="$1"; . "$2"; lfa_codec_patch_launchers' _ "$T/prefix" "$CODECLIB" +[ "$(grep -c 'lfa_codec_autostart' "$T/prefix/bin/start-linux")" = "1" ] && pass=$((pass+1)) \ + || { fail=$((fail+1)); echo "FAIL: Y15 launcher patch is not idempotent"; } + echo "" echo "===== Z: documentation links =====" [ -s "$REPO/docs/TROUBLESHOOTING.md" ] && pass=$((pass+1)) || { fail=$((fail+1)); echo "FAIL: Z troubleshooting guide missing"; }