Compare commits
No files matched your search
+61
-2
@@ -47,8 +47,18 @@ jobs:
|
||||
# nasm, file and desktop-file-validate may be installed by the runner's
|
||||
# administrator in ~/.local/bin, outside the session PATH. When they
|
||||
# are missing there, the pipeline falls back on what the system provides.
|
||||
if [ -d "$HOME/.local/bin" ]; then
|
||||
echo "PATH=$HOME/.local/bin:$PATH" >> "$GITHUB_ENV"
|
||||
# rustup's ~/.cargo/bin likewise: the runner service does not always
|
||||
# read the profile that adds it.
|
||||
path="$PATH"
|
||||
for dir in "$HOME/.local/bin" "${CARGO_HOME:-$HOME/.cargo}/bin"; do
|
||||
if [ -d "$dir" ]; then
|
||||
path="$dir:$path"
|
||||
fi
|
||||
done
|
||||
echo "PATH=$path" >> "$GITHUB_ENV"
|
||||
if ! PATH="$path" command -v cargo >/dev/null; then
|
||||
echo "cargo not found (HOME=$HOME, PATH=$path): install rustup for the runner's user" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- name: Versions
|
||||
@@ -104,6 +114,11 @@ jobs:
|
||||
cd apps/viewer
|
||||
npm run build
|
||||
|
||||
- name: Licenses
|
||||
# Every shipped dependency stays compatible with Apache-2.0 (#59): a
|
||||
# new crate under GPL, or without a license, fails here.
|
||||
run: node scripts/check-licenses.mjs
|
||||
|
||||
- name: Formatting
|
||||
run: cargo fmt --all --check
|
||||
|
||||
@@ -130,6 +145,50 @@ jobs:
|
||||
echo "libpipewire-0.3 missing on the runner: Wayland capture not checked"
|
||||
fi
|
||||
|
||||
- name: Hardware encoding (VA-API)
|
||||
run: |
|
||||
set -euo pipefail
|
||||
# The `vaapi` feature links GStreamer (#57). Without its development
|
||||
# files the step says so and passes, like the PipeWire one. The
|
||||
# encoder tests skip themselves on a runner without a GPU.
|
||||
if pkg-config --exists gstreamer-app-1.0 gstreamer-video-1.0; then
|
||||
cargo clippy -p rs-codec -p rs-session --features rs-session/vaapi --all-targets -- -D warnings
|
||||
cargo test -p rs-codec --features vaapi
|
||||
else
|
||||
echo "GStreamer development files missing on the runner: hardware encoding not checked"
|
||||
fi
|
||||
|
||||
- name: Windows build (cross-compiled)
|
||||
run: |
|
||||
set -euo pipefail
|
||||
# Windows is built from Linux with mingw-w64 (#93). With Nix, the
|
||||
# `windows` shell of the flake brings everything. Without it, the
|
||||
# runner needs `gcc-mingw-w64-x86-64` and
|
||||
# `rustup target add x86_64-pc-windows-gnu`; libvpx for Windows is
|
||||
# then built once into the cache. Missing both, the step says so and
|
||||
# passes, like the PipeWire one.
|
||||
if command -v nix >/dev/null 2>&1; then
|
||||
nix develop .#windows -c cargo clippy --workspace --all-targets -- -D warnings
|
||||
nix develop .#windows -c cargo build -p rs-session --bin rustscreen-cli
|
||||
elif command -v x86_64-w64-mingw32-gcc >/dev/null 2>&1 \
|
||||
&& rustup target list --installed 2>/dev/null | grep -qx x86_64-pc-windows-gnu; then
|
||||
win_vpx="$(dirname "$VPX_PREFIX")/libvpx-windows"
|
||||
if [ ! -f "$win_vpx/lib/libvpx.a" ]; then
|
||||
LIBVPX_TARGET=x86_64-win64-gcc CROSS=x86_64-w64-mingw32- \
|
||||
./scripts/build-libvpx.sh "$win_vpx"
|
||||
fi
|
||||
export CARGO_BUILD_TARGET=x86_64-pc-windows-gnu
|
||||
export CARGO_TARGET_X86_64_PC_WINDOWS_GNU_LINKER=x86_64-w64-mingw32-gcc
|
||||
export CC_x86_64_pc_windows_gnu=x86_64-w64-mingw32-gcc
|
||||
export AR_x86_64_pc_windows_gnu=x86_64-w64-mingw32-ar
|
||||
export VPX_LIB_DIR="$win_vpx/lib" VPX_INCLUDE_DIR="$win_vpx/include" VPX_STATIC=1
|
||||
export CARGO_TARGET_DIR="$CARGO_TARGET_DIR/windows"
|
||||
cargo clippy --workspace --all-targets -- -D warnings
|
||||
cargo build -p rs-session --bin rustscreen-cli
|
||||
else
|
||||
echo "neither Nix nor mingw-w64 with the Windows rustup target: the Windows build is not checked"
|
||||
fi
|
||||
|
||||
- name: The binary starts
|
||||
run: |
|
||||
set -euo pipefail
|
||||
|
||||
@@ -3,7 +3,8 @@
|
||||
# Nothing else triggers this pipeline: no button, no command typed on a laptop,
|
||||
# and no version number written by hand in a file. The git tag is the single
|
||||
# source of the version; the binary and the AppImage follow from it, and the
|
||||
# release states what it contains.
|
||||
# release states what it contains. GoReleaser publishes it (#97); the builds
|
||||
# stay in the scripts, which know libvpx and PipeWire.
|
||||
#
|
||||
# It first checks that the tag matches the version declared in `Cargo.toml`: a
|
||||
# `v0.2.0` release built from a `Cargo.toml` at `0.1.0` would lie about its
|
||||
@@ -45,8 +46,18 @@ jobs:
|
||||
# nasm, file and desktop-file-validate may be installed by the runner's
|
||||
# administrator in ~/.local/bin, outside the session PATH. When they
|
||||
# are missing there, the pipeline falls back on what the system provides.
|
||||
if [ -d "$HOME/.local/bin" ]; then
|
||||
echo "PATH=$HOME/.local/bin:$PATH" >> "$GITHUB_ENV"
|
||||
# rustup's ~/.cargo/bin likewise: the runner service does not always
|
||||
# read the profile that adds it.
|
||||
path="$PATH"
|
||||
for dir in "$HOME/.local/bin" "${CARGO_HOME:-$HOME/.cargo}/bin"; do
|
||||
if [ -d "$dir" ]; then
|
||||
path="$dir:$path"
|
||||
fi
|
||||
done
|
||||
echo "PATH=$path" >> "$GITHUB_ENV"
|
||||
if ! PATH="$path" command -v cargo >/dev/null; then
|
||||
echo "cargo not found (HOME=$HOME, PATH=$path): install rustup for the runner's user" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- name: Version and tag
|
||||
@@ -101,22 +112,47 @@ jobs:
|
||||
set -euo pipefail
|
||||
./scripts/build-appimage.sh
|
||||
|
||||
- name: .deb and .rpm
|
||||
run: |
|
||||
set -euo pipefail
|
||||
./scripts/build-linux-packages.sh
|
||||
|
||||
- name: GoReleaser
|
||||
run: |
|
||||
set -euo pipefail
|
||||
# Pinned with its checksum, like appimagetool: the runner has neither
|
||||
# Nix nor a package for it, and a "latest" URL would change
|
||||
# underneath us.
|
||||
version=2.17.1
|
||||
sum=a99bbc7ae0d8d897b07c4c497a9b62f222558804715ef219d1af05a7e417bc80
|
||||
dir="${RUSTSCREEN_CACHE_DIR:-$HOME/.cache/rustscreen-ci}/goreleaser-$version"
|
||||
if [ ! -x "$dir/goreleaser" ]; then
|
||||
mkdir -p "$dir"
|
||||
curl -fsSL -o "$dir/goreleaser.tar.gz" \
|
||||
"https://github.com/goreleaser/goreleaser/releases/download/v$version/goreleaser_Linux_x86_64.tar.gz"
|
||||
echo "$sum $dir/goreleaser.tar.gz" | sha256sum -c -
|
||||
tar -xzf "$dir/goreleaser.tar.gz" -C "$dir" goreleaser
|
||||
rm "$dir/goreleaser.tar.gz"
|
||||
fi
|
||||
echo "$dir" >> "$GITHUB_PATH"
|
||||
|
||||
- name: Release
|
||||
env:
|
||||
# The pipeline token, with the write permission requested above.
|
||||
GITEA_TOKEN: ${{ github.token }}
|
||||
GITEA_REPO: ${{ github.repository }}
|
||||
GITEA_API: ${{ github.server_url }}/api/v1
|
||||
RELEASE_NOTES: docs/releases/${{ github.ref_name }}.md
|
||||
run: |
|
||||
set -euo pipefail
|
||||
# `RELEASE_NOTES` points to a versioned file when it exists; otherwise
|
||||
# the script writes a minimal note rather than failing.
|
||||
# GoReleaser publishes what was built above (`.goreleaser.yaml`): it
|
||||
# only globs inside the repository, hence `dist/release`.
|
||||
mkdir -p dist/release
|
||||
cp "dist-appimage/rustscreen-${VERSION}-x86_64.AppImage" dist/release/
|
||||
cp "$CARGO_TARGET_DIR/release/rustscreen-cli" dist/release/
|
||||
cp dist-packages/*.deb dist-packages/*.rpm dist/release/
|
||||
notes="docs/releases/${GITHUB_REF_NAME}.md"
|
||||
if [ ! -f "$notes" ]; then
|
||||
echo "no notes for ${GITHUB_REF_NAME}, minimal note" >&2
|
||||
export RELEASE_NOTES="$notes.absent"
|
||||
if [ -f "$notes" ]; then
|
||||
goreleaser release --clean --release-notes "$notes"
|
||||
else
|
||||
# Without written notes, the commits since the previous tag.
|
||||
echo "no notes for ${GITHUB_REF_NAME}, changelog from git" >&2
|
||||
goreleaser release --clean
|
||||
fi
|
||||
./scripts/publish-release.py "$GITHUB_REF_NAME" \
|
||||
"dist-appimage/rustscreen-${VERSION}-x86_64.AppImage" \
|
||||
"$CARGO_TARGET_DIR/release/rustscreen-cli"
|
||||
@@ -30,6 +30,7 @@ diag-*.zip
|
||||
|
||||
# Empaquetage local
|
||||
dist-appimage/
|
||||
dist-packages/
|
||||
.cache/
|
||||
SHA256SUMS
|
||||
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
# Release of a `vX.Y.Z` tag (#97), run by `.gitea/workflows/release.yml`.
|
||||
#
|
||||
# GoReleaser does not compile anything here: the Rust stack needs libvpx,
|
||||
# PipeWire and the viewer built first, which the pipeline does with its own
|
||||
# scripts. It takes the finished artifacts and publishes the release: Gitea
|
||||
# release, attachments, SHA256SUMS, notes. A rerun on the same tag replaces
|
||||
# them instead of stacking copies.
|
||||
#
|
||||
# Local check, without publishing:
|
||||
# goreleaser release --snapshot --clean --skip=publish
|
||||
version: 2
|
||||
|
||||
project_name: rustscreen
|
||||
|
||||
# Not `dist/`: `--clean` empties it, and the Windows installer is built there.
|
||||
dist: dist/goreleaser
|
||||
|
||||
# A skipped build, declared Rust so that GoReleaser does not look for a Go
|
||||
# module.
|
||||
builds:
|
||||
- builder: rust
|
||||
skip: true
|
||||
|
||||
gitea_urls:
|
||||
api: https://gitea-nubo.hopledge.com/api/v1
|
||||
download: https://gitea-nubo.hopledge.com
|
||||
|
||||
# The pipeline token is GITEA_TOKEN; a GITHUB_TOKEN set by the runner must not
|
||||
# send GoReleaser to GitHub.
|
||||
force_token: gitea
|
||||
|
||||
# What the release ships: the binary, the AppImage, the .deb and the .rpm,
|
||||
# built beforehand and gathered in `dist/release` (GoReleaser only globs
|
||||
# inside the repository). The packages come from nfpm directly: see
|
||||
# `scripts/build-linux-packages.sh` for why not GoReleaser's own. A missing
|
||||
# file fails the release rather than publishing an incomplete one.
|
||||
release:
|
||||
gitea:
|
||||
owner: heap
|
||||
name: rustscreen
|
||||
name_template: "v{{ .Version }}"
|
||||
mode: replace
|
||||
replace_existing_artifacts: true
|
||||
extra_files:
|
||||
- glob: "dist/release/rustscreen-{{ .Version }}-x86_64.AppImage"
|
||||
- glob: "dist/release/rustscreen-cli"
|
||||
- glob: "dist/release/rustscreen-cli_{{ .Version }}_amd64.deb"
|
||||
- glob: "dist/release/rustscreen-cli-{{ .Version }}-1.x86_64.rpm"
|
||||
|
||||
checksum:
|
||||
name_template: SHA256SUMS
|
||||
algorithm: sha256
|
||||
extra_files:
|
||||
- glob: "dist/release/rustscreen-{{ .Version }}-x86_64.AppImage"
|
||||
- glob: "dist/release/rustscreen-cli"
|
||||
- glob: "dist/release/rustscreen-cli_{{ .Version }}_amd64.deb"
|
||||
- glob: "dist/release/rustscreen-cli-{{ .Version }}-1.x86_64.rpm"
|
||||
|
||||
# `--snapshot` (local check): the artifacts are named after this version.
|
||||
snapshot:
|
||||
version_template: "{{ .Version }}-snapshot"
|
||||
|
||||
# Used when `docs/releases/vX.Y.Z.md` does not exist; otherwise the pipeline
|
||||
# passes that file with `--release-notes`.
|
||||
changelog:
|
||||
use: git
|
||||
sort: asc
|
||||
filters:
|
||||
exclude:
|
||||
- "^chore\\(deps\\)"
|
||||
@@ -14,12 +14,18 @@ dépendent pas d'un service en ligne.
|
||||
Ce qui tourne: capture Linux réelle (portail et PipeWire sous Wayland, X11 en repli, chaque
|
||||
moniteur RandR, une fenêtre seule), écran virtuel par le portail (GNOME 46, KDE), conversion BGRA
|
||||
vers I420, encodage VP8 ou VP9 temps réel qui suit les changements de résolution, session str0m par
|
||||
spectateur, serveur local avec jeton qui expire et code court, viewer React qui reprend seul après
|
||||
spectateur, serveur local avec jeton qui expire et code court, appareils de confiance qui reviennent sans lien
|
||||
par une clé Ed25519 (ADR 0011), changement de source en plein partage sans reconnexion, nom
|
||||
local `rustscreen.local` en mDNS, viewer React qui reprend seul après
|
||||
une coupure ou une veille, tourne l'image et suit le thème, coque desktop Tauri avec icône de
|
||||
barre système, réglages persistants, interface en français et en anglais, inhibition de veille,
|
||||
journal JSON local et archive de diagnostics.
|
||||
Ce qui manque: la capture Windows et macOS, l'encodeur matériel, et la traduction des messages
|
||||
produits par l'hôte (erreurs, avertissements), aujourd'hui en anglais seulement (#75).
|
||||
L'encodage matériel passe par VA-API et GStreamer sous Linux (fonctionnalité `vaapi`, ADR 0012), par
|
||||
Media Foundation sous Windows (#95). Ce qui manque: la duplication de bureau DXGI sous Windows
|
||||
(la capture y passe par GDI, #8), et tout le travail Windows reste à vérifier sur une vraie machine,
|
||||
il n'a tourné que sous Wine. macOS est hors périmètre comme hôte (#90). Les messages de l'hôte
|
||||
(erreurs, avertissements, refus de réglages) partent en codes (`Notice`) que la coque traduit sous
|
||||
`desktop.host` (#75); le test `notices` refuse un code sans traduction.
|
||||
|
||||
L'hôte tient dans `rs-session::Host`: démarrer, arrêter, déconnecter un spectateur, régler, et
|
||||
publier l'état complet à chaque changement. Lancer `rustscreen` ouvre l'application de bureau
|
||||
@@ -87,7 +93,7 @@ la capture ni le serveur.
|
||||
|
||||
- **La capture écran est le vrai sujet, pas WebRTC.** Chaque OS a sa contrainte : Wayland interdit
|
||||
la capture directe (portail PipeWire obligatoire, avec une boîte de dialogue de consentement),
|
||||
macOS exige la permission d'enregistrement d'écran et ScreenCaptureKit, Windows demande DXGI ou
|
||||
Windows demande DXGI ou
|
||||
Windows Graphics Capture. Un chemin de capture unique et portable n'existe pas.
|
||||
- **Le profil couleur casse les conversions.** Une frame BGRA 10 bits traitée comme du 8 bits donne
|
||||
des couleurs fausses ; préciser le format en entrée de chaque étape et le tester avec une mire.
|
||||
@@ -117,6 +123,21 @@ cargo test -p rs-proto export_bindings # régénère apps/viewer/src/proto
|
||||
Une fonctionnalité de capture ou d'encodage se prouve avec une mire de test et des mesures de
|
||||
latence, pas avec une capture d'écran de l'UI.
|
||||
|
||||
**Sans libvpx, rien ne compile.** `rs-codec` lie `env-libvpx-sys`, qui exige un préfixe explicite :
|
||||
sans lui, la compilation s'arrête sur `Package 'vpx' was not found in the pkg-config search path`,
|
||||
après deux minutes de dépendances. La CI construit libvpx une fois dans son cache et exporte quatre
|
||||
variables; les mêmes suffisent en local, avec le répertoire de cible de la CI déjà chaud pour éviter
|
||||
une reconstruction complète.
|
||||
|
||||
```bash
|
||||
export VPX_PREFIX=$HOME/.cache/rustscreen-ci/libvpx # ou ./scripts/build-libvpx.sh <préfixe>
|
||||
export VPX_LIB_DIR=$VPX_PREFIX/lib
|
||||
export VPX_INCLUDE_DIR=$VPX_PREFIX/include
|
||||
export VPX_VERSION=1.13.0
|
||||
export PKG_CONFIG_PATH=$VPX_PREFIX/lib/pkgconfig${PKG_CONFIG_PATH:+:$PKG_CONFIG_PATH}
|
||||
export CARGO_TARGET_DIR=$HOME/.cache/rustscreen-ci/cargo-target
|
||||
```
|
||||
|
||||
Le banc d'essai actuel est le binaire `rustscreen-cli` de `rs-session`: il assemble la vraie pile
|
||||
(capture, encodage, protocole, session, serveur) et sait aussi rejouer une mire IVF.
|
||||
|
||||
@@ -145,8 +166,30 @@ cargo run --release -p rs-session --features pipewire --bin rustscreen-cli -- --
|
||||
cargo run -p rs-session --bin rustscreen-cli -- --diagnostics
|
||||
# VP9 au lieu de VP8 (même qualité pour moins de débit, 1,6x le calcul), une fenêtre par le portail
|
||||
cargo run --release -p rs-session --features pipewire --bin rustscreen-cli -- --codec vp9 --pick-window
|
||||
# H.264 ou VP9 sur le GPU (VA-API, ADR 0012); --software force libvpx
|
||||
cargo run --release -p rs-session --features pipewire,vaapi --bin rustscreen-cli -- --codec h264
|
||||
```
|
||||
|
||||
Windows se compile depuis Linux (#93): le shell `.#windows` fournit un rustc pour la cible
|
||||
`x86_64-pc-windows-gnu`, mingw-w64 et une libvpx statique, et range sa cible sous `target/windows`.
|
||||
Wine fait tourner le `.exe` et les tests, sans machine Windows. Les tests de Media Foundation y
|
||||
passent par la transformée H.264 de Wine (GStreamer, `x264enc`), logicielle et sans basse latence:
|
||||
ils encodent assez d'images pour franchir sa file d'attente. La capture GDI (#8) s'y vérifie sur
|
||||
un Xvfb **à la taille d'un moniteur que Wine annonce** (1920 × 1080): plus petit, X refuse de lire
|
||||
la zone et l'image sort noire.
|
||||
|
||||
```bash
|
||||
nix develop .#windows -c cargo clippy --workspace --all-targets -- -D warnings
|
||||
nix develop .#windows -c cargo build -p rs-session --bin rustscreen-cli
|
||||
# tests et binaire sous Wine (nix shell nixpkgs#wine64)
|
||||
CARGO_TARGET_X86_64_PC_WINDOWS_GNU_RUNNER=wine nix develop .#windows -c cargo test --workspace
|
||||
```
|
||||
|
||||
Sous Windows, les réglages vont dans `%APPDATA%\rustscreen`, le journal dans
|
||||
`%LOCALAPPDATA%\rustscreen\logs`. Le portail n'existe pas: `rs_platform::portal` y répond
|
||||
`Unsupported`, et le code propre à un système vit dans un sous-module par OS (`sleep/linux.rs`,
|
||||
`sleep/windows.rs`).
|
||||
|
||||
La coque desktop demande WebKitGTK au build: elle a son propre workspace Cargo et son shell Nix.
|
||||
|
||||
```bash
|
||||
@@ -159,7 +202,7 @@ make desktop-lint # biome, vitest, rustfmt et clippy de la coque
|
||||
En debug, le binaire embarque `apps/desktop/dist` (feature `custom-protocol` par défaut);
|
||||
`--no-default-features` charge le serveur Vite (`pnpm --dir apps/desktop dev`) à la place.
|
||||
|
||||
Le chemin se force avec `RUSTSCREEN_CAPTURE=portal|x11|synthetic`. Le test X11 réel se lance
|
||||
Le chemin se force avec `RUSTSCREEN_CAPTURE=portal|x11|gdi|synthetic`. Le test X11 réel se lance
|
||||
contre un serveur jetable: `Xephyr :5 & DISPLAY=:5 xeyes &` puis
|
||||
`RUSTSCREEN_X11_TEST=:5 cargo test -p rs-capture x11 -- --ignored`. Pour plusieurs moniteurs,
|
||||
lancer Xephyr avec `+extension RANDR` et en déclarer avec `xrandr --setmonitor` (voir le test).
|
||||
@@ -176,7 +219,9 @@ Le journal JSON (`~/.local/state/rustscreen/logs`) nomme les étapes d'une sessi
|
||||
(avec `cause`), `capture_revoked`, `capture_failed`, `encode_failed`, et côté hôte `share_started`,
|
||||
`share_ended`, `share_interrupted`, `viewer_disconnected`, `resolution_changed`, `sleep_inhibited`,
|
||||
`sleep_released`, `wake_detected`, `capture_restarted`, `address_changed`, `settings_changed`,
|
||||
`access_regenerated`, `code_accepted`, `code_rejected`. Avant la 0.6, ces noms étaient en français
|
||||
`access_regenerated`, `code_accepted`, `code_rejected`, `trust_changed`, `source_switched`,
|
||||
`source_switch_failed`, `local_name_failed`, et côté serveur `trusted_device_admitted`,
|
||||
`local_name_announced`, `local_name_renamed`, `local_name_confirmed`. Avant la 0.6, ces noms étaient en français
|
||||
(champ `evenement`). Ne jamais y écrire un titre de fenêtre ni une image (ADR 0008).
|
||||
|
||||
Le spike historique `spikes/str0m-mire` reste pour comparer les mesures:
|
||||
|
||||
Generated
+542
-5
@@ -125,6 +125,12 @@ version = "1.1.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0"
|
||||
|
||||
[[package]]
|
||||
name = "atomic_refcell"
|
||||
version = "0.1.14"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "21e4227379beff4205943696e6c3e0cd809bacdf3f0edd6e3dd153e2269571a4"
|
||||
|
||||
[[package]]
|
||||
name = "autocfg"
|
||||
version = "1.5.1"
|
||||
@@ -266,7 +272,7 @@ dependencies = [
|
||||
"bitflags",
|
||||
"cexpr",
|
||||
"clang-sys",
|
||||
"itertools",
|
||||
"itertools 0.13.0",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"regex",
|
||||
@@ -541,6 +547,32 @@ dependencies = [
|
||||
"cipher",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "curve25519-dalek"
|
||||
version = "5.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b5eed333089e2e1c1ac8c6c0398e5e2497b4c9926ca6d0365ed1e099afa5bc23"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"cpufeatures 0.3.1",
|
||||
"curve25519-dalek-derive",
|
||||
"digest 0.11.3",
|
||||
"fiat-crypto",
|
||||
"rustc_version",
|
||||
"subtle",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "curve25519-dalek-derive"
|
||||
version = "0.1.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f46882e17999c6cc590af592290432be3bce0428cb0d5f8b6715e4dc7b383eb3"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "data-encoding"
|
||||
version = "2.11.1"
|
||||
@@ -630,7 +662,7 @@ dependencies = [
|
||||
"rand 0.9.5",
|
||||
"rcgen",
|
||||
"sec1",
|
||||
"signature",
|
||||
"signature 2.2.0",
|
||||
"spki",
|
||||
"subtle",
|
||||
"time",
|
||||
@@ -654,6 +686,27 @@ version = "1.0.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813"
|
||||
|
||||
[[package]]
|
||||
name = "ed25519"
|
||||
version = "3.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "29fcf32e6c73d1079f83ab4d782de2d81620346a5f38c6237a86a22f8368980a"
|
||||
dependencies = [
|
||||
"signature 3.0.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ed25519-dalek"
|
||||
version = "3.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6ebaa1a2bf1290ab3bfe5a7b771d050ebffab2711c19a81691c683a5144a25de"
|
||||
dependencies = [
|
||||
"curve25519-dalek",
|
||||
"ed25519",
|
||||
"sha2",
|
||||
"subtle",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "either"
|
||||
version = "1.19.0"
|
||||
@@ -706,6 +759,12 @@ dependencies = [
|
||||
"simd-adler32",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fiat-crypto"
|
||||
version = "0.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "64cd1e32ddd350061ae6edb1b082d7c54915b5c672c389143b9a63403a109f24"
|
||||
|
||||
[[package]]
|
||||
name = "find-msvc-tools"
|
||||
version = "0.1.15"
|
||||
@@ -729,6 +788,15 @@ dependencies = [
|
||||
"zlib-rs",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "flume"
|
||||
version = "0.12.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5e139bc46ca777eb5efaf62df0ab8cc5fd400866427e56c68b22e414e53bd3be"
|
||||
dependencies = [
|
||||
"spin",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fnv"
|
||||
version = "1.0.7"
|
||||
@@ -781,12 +849,34 @@ version = "0.3.34"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e"
|
||||
|
||||
[[package]]
|
||||
name = "futures-executor"
|
||||
version = "0.3.34"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "031b47cf1a3c6cc8bc2fc76cd437f521619387907d469316e7c0bc278f1f5432"
|
||||
dependencies = [
|
||||
"futures-core",
|
||||
"futures-task",
|
||||
"futures-util",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "futures-io"
|
||||
version = "0.3.34"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed"
|
||||
|
||||
[[package]]
|
||||
name = "futures-macro"
|
||||
version = "0.3.34"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 3.0.9",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "futures-sink"
|
||||
version = "0.3.34"
|
||||
@@ -806,6 +896,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc"
|
||||
dependencies = [
|
||||
"futures-core",
|
||||
"futures-macro",
|
||||
"futures-sink",
|
||||
"futures-task",
|
||||
"pin-project-lite",
|
||||
@@ -897,12 +988,202 @@ dependencies = [
|
||||
"wasm-bindgen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "gio-sys"
|
||||
version = "0.22.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6c28739f914c15b87a9856000bed9cbd5b3a8afbca5e982d9a299e1601422cb5"
|
||||
dependencies = [
|
||||
"glib-sys",
|
||||
"gobject-sys",
|
||||
"libc",
|
||||
"system-deps 9.0.1",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "glib"
|
||||
version = "0.22.10"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e4cf9e5bd8713f1990a92c422998826e0fb34824277b46bc59757373483c6694"
|
||||
dependencies = [
|
||||
"bitflags",
|
||||
"futures-channel",
|
||||
"futures-core",
|
||||
"futures-executor",
|
||||
"futures-task",
|
||||
"futures-util",
|
||||
"gio-sys",
|
||||
"glib-macros",
|
||||
"glib-sys",
|
||||
"gobject-sys",
|
||||
"libc",
|
||||
"memchr",
|
||||
"smallvec",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "glib-macros"
|
||||
version = "0.22.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c9597c68fa7bdf4154a3079642cd21c4dccac0b0bdd2897d82861523bf91e7b9"
|
||||
dependencies = [
|
||||
"heck",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 3.0.9",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "glib-sys"
|
||||
version = "0.22.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "99b38907e67e40dec9b60f858bcada952598719cb512a13eb13d6cdcd16f8295"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"system-deps 9.0.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "glob"
|
||||
version = "0.3.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e4eba85ea1d0a966a983acd07deee566e67395d2d96b6fb39e62b5a833f1eb0b"
|
||||
|
||||
[[package]]
|
||||
name = "gobject-sys"
|
||||
version = "0.22.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "07595c9ba696bd9819cb6a8df39f08078f3dd679508fe052dd558492c2053834"
|
||||
dependencies = [
|
||||
"glib-sys",
|
||||
"libc",
|
||||
"system-deps 9.0.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "gstreamer"
|
||||
version = "0.25.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f4237e2066a25ecb7e54be6c066409e30615920265b9799b8d560ef8ac9857c6"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"futures-channel",
|
||||
"futures-core",
|
||||
"futures-util",
|
||||
"glib",
|
||||
"gstreamer-sys",
|
||||
"itertools 0.15.0",
|
||||
"kstring",
|
||||
"libc",
|
||||
"muldiv",
|
||||
"num-integer",
|
||||
"num-rational",
|
||||
"option-operations",
|
||||
"pastey",
|
||||
"pin-project-lite",
|
||||
"smallvec",
|
||||
"thiserror",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "gstreamer-app"
|
||||
version = "0.25.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "97f8ae9238c2352398dcc084de28df3f7099af216ac6c160b52318d23f25c010"
|
||||
dependencies = [
|
||||
"futures-core",
|
||||
"futures-sink",
|
||||
"glib",
|
||||
"gstreamer",
|
||||
"gstreamer-app-sys",
|
||||
"gstreamer-base",
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "gstreamer-app-sys"
|
||||
version = "0.25.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0798b8aef6694341d40bb81edc759f8979b896b59f9f0f45d8cfa3bb7bf2e743"
|
||||
dependencies = [
|
||||
"glib-sys",
|
||||
"gstreamer-base-sys",
|
||||
"gstreamer-sys",
|
||||
"libc",
|
||||
"system-deps 9.0.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "gstreamer-base"
|
||||
version = "0.25.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "17cbd8f59586a369c40d4b0d2f3a61cf9e9287b3cf5503cdcd8e7c5faa99265e"
|
||||
dependencies = [
|
||||
"atomic_refcell",
|
||||
"cfg-if",
|
||||
"glib",
|
||||
"gstreamer",
|
||||
"gstreamer-base-sys",
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "gstreamer-base-sys"
|
||||
version = "0.25.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3b05f77bfd76b5afee6b29c27dae19eaf5018b5cf8d0d17520f3de44c6385c32"
|
||||
dependencies = [
|
||||
"glib-sys",
|
||||
"gobject-sys",
|
||||
"gstreamer-sys",
|
||||
"libc",
|
||||
"system-deps 9.0.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "gstreamer-sys"
|
||||
version = "0.25.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "436d9532847489a8285d57b8c3670762c12a18f777fdc2ab159b52e0e6f521b9"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"glib-sys",
|
||||
"gobject-sys",
|
||||
"libc",
|
||||
"system-deps 9.0.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "gstreamer-video"
|
||||
version = "0.25.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ffe4d77b2a5e679973d9c6b6c052da8cda86b83f5c268872f8691fde693fde84"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"futures-channel",
|
||||
"glib",
|
||||
"gstreamer",
|
||||
"gstreamer-base",
|
||||
"gstreamer-video-sys",
|
||||
"libc",
|
||||
"thiserror",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "gstreamer-video-sys"
|
||||
version = "0.25.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ef455da22edca97ac9299d682b868227f3d9217b303748ce0161b31ae82dc106"
|
||||
dependencies = [
|
||||
"glib-sys",
|
||||
"gobject-sys",
|
||||
"gstreamer-base-sys",
|
||||
"gstreamer-sys",
|
||||
"libc",
|
||||
"system-deps 9.0.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "h2"
|
||||
version = "0.4.20"
|
||||
@@ -1102,6 +1383,15 @@ dependencies = [
|
||||
"either",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "itertools"
|
||||
version = "0.15.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8b4baf93f58d4425749ca49a51c50ebab072c5df6994d08fed93541c331481dc"
|
||||
dependencies = [
|
||||
"either",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "itoa"
|
||||
version = "1.0.18"
|
||||
@@ -1129,6 +1419,15 @@ dependencies = [
|
||||
"wasm-bindgen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "kstring"
|
||||
version = "2.0.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "558bf9508a558512042d3095138b1f7b8fe90c5467d94f9f1da28b3731c5dbd1"
|
||||
dependencies = [
|
||||
"static_assertions",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "lazy_static"
|
||||
version = "1.5.1"
|
||||
@@ -1164,7 +1463,7 @@ dependencies = [
|
||||
"libspa-sys",
|
||||
"nom 8.0.0",
|
||||
"rustix",
|
||||
"system-deps",
|
||||
"system-deps 7.0.8",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1175,7 +1474,7 @@ checksum = "3b6e17bdaf63ed0d5e4144022624032b41fd9733112e8c74ac26fc9bf1291924"
|
||||
dependencies = [
|
||||
"bindgen",
|
||||
"cc",
|
||||
"system-deps",
|
||||
"system-deps 7.0.8",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1184,6 +1483,15 @@ version = "0.12.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53"
|
||||
|
||||
[[package]]
|
||||
name = "lock_api"
|
||||
version = "0.4.14"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965"
|
||||
dependencies = [
|
||||
"scopeguard",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "log"
|
||||
version = "0.4.34"
|
||||
@@ -1214,6 +1522,20 @@ version = "0.8.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "47e1ffaa40ddd1f3ed91f717a33c8c0ee23fff369e3aa8772b9605cc1d22f4c3"
|
||||
|
||||
[[package]]
|
||||
name = "mdns-sd"
|
||||
version = "0.21.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8562654710f72a9cbce4b0d5b7c366a2f94330ba1ce3740f15e932ea2d37b161"
|
||||
dependencies = [
|
||||
"fastrand",
|
||||
"flume",
|
||||
"if-addrs",
|
||||
"mio",
|
||||
"socket-pktinfo",
|
||||
"socket2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "memchr"
|
||||
version = "2.8.3"
|
||||
@@ -1278,6 +1600,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1788edb87fdc09c7e26304471e2f5be8cdefb1b6930d6e3985fc02ff53bf86ee"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"log",
|
||||
"wasi",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
@@ -1292,6 +1615,12 @@ dependencies = [
|
||||
"pxfm",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "muldiv"
|
||||
version = "1.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "956787520e75e9bd233246045d19f42fb73242759cc57fba9611d940ae96d4b0"
|
||||
|
||||
[[package]]
|
||||
name = "nix"
|
||||
version = "0.31.3"
|
||||
@@ -1357,6 +1686,16 @@ dependencies = [
|
||||
"num-traits",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "num-rational"
|
||||
version = "0.4.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f83d14da390562dca69fc84082e73e548e1ad308d24accdedd2720017cb37824"
|
||||
dependencies = [
|
||||
"num-integer",
|
||||
"num-traits",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "num-traits"
|
||||
version = "0.2.19"
|
||||
@@ -1381,6 +1720,15 @@ version = "1.21.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
|
||||
|
||||
[[package]]
|
||||
name = "option-operations"
|
||||
version = "0.6.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "aca39cf52b03268400c16eeb9b56382ea3c3353409309b63f5c8f0b1faf42754"
|
||||
dependencies = [
|
||||
"pastey",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ordered-stream"
|
||||
version = "0.2.0"
|
||||
@@ -1391,6 +1739,12 @@ dependencies = [
|
||||
"pin-project-lite",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pastey"
|
||||
version = "0.2.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2ee67f1008b1ba2321834326597b8e186293b049a023cdef258527550b9935b4"
|
||||
|
||||
[[package]]
|
||||
name = "pem"
|
||||
version = "4.0.0"
|
||||
@@ -1444,7 +1798,7 @@ checksum = "9ce653f53e63e5b93853218092ee9a8906a5d082c92f3f1db26316955dd63ce0"
|
||||
dependencies = [
|
||||
"bindgen",
|
||||
"libspa-sys",
|
||||
"system-deps",
|
||||
"system-deps 7.0.8",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1657,6 +2011,7 @@ dependencies = [
|
||||
"rustix",
|
||||
"thiserror",
|
||||
"tracing",
|
||||
"windows-sys 0.61.2",
|
||||
"x11rb",
|
||||
]
|
||||
|
||||
@@ -1665,10 +2020,15 @@ name = "rs-codec"
|
||||
version = "0.5.0"
|
||||
dependencies = [
|
||||
"env-libvpx-sys",
|
||||
"gstreamer",
|
||||
"gstreamer-app",
|
||||
"gstreamer-video",
|
||||
"rs-capture",
|
||||
"rs-proto",
|
||||
"thiserror",
|
||||
"tokio",
|
||||
"tracing",
|
||||
"windows",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1695,6 +2055,7 @@ dependencies = [
|
||||
"thiserror",
|
||||
"tokio",
|
||||
"tracing",
|
||||
"windows-sys 0.61.2",
|
||||
"zbus",
|
||||
]
|
||||
|
||||
@@ -1712,6 +2073,7 @@ dependencies = [
|
||||
name = "rs-rtc"
|
||||
version = "0.5.0"
|
||||
dependencies = [
|
||||
"if-addrs",
|
||||
"rs-codec",
|
||||
"str0m",
|
||||
"thiserror",
|
||||
@@ -1724,7 +2086,9 @@ name = "rs-session"
|
||||
version = "0.5.0"
|
||||
dependencies = [
|
||||
"base64 0.23.1",
|
||||
"ed25519-dalek",
|
||||
"futures-util",
|
||||
"hex",
|
||||
"png",
|
||||
"rs-capture",
|
||||
"rs-codec",
|
||||
@@ -1749,8 +2113,10 @@ version = "0.5.0"
|
||||
dependencies = [
|
||||
"axum",
|
||||
"axum-server",
|
||||
"ed25519-dalek",
|
||||
"hex",
|
||||
"image",
|
||||
"mdns-sd",
|
||||
"qrcode",
|
||||
"rand 0.10.3",
|
||||
"rcgen",
|
||||
@@ -1765,6 +2131,7 @@ dependencies = [
|
||||
"tokio",
|
||||
"tower-http",
|
||||
"tracing",
|
||||
"ts-rs",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1785,6 +2152,15 @@ version = "2.1.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d"
|
||||
|
||||
[[package]]
|
||||
name = "rustc_version"
|
||||
version = "0.4.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92"
|
||||
dependencies = [
|
||||
"semver",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rusticata-macros"
|
||||
version = "4.1.0"
|
||||
@@ -1854,6 +2230,12 @@ version = "1.0.23"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f"
|
||||
|
||||
[[package]]
|
||||
name = "scopeguard"
|
||||
version = "1.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
|
||||
|
||||
[[package]]
|
||||
name = "sctp-proto"
|
||||
version = "0.10.7"
|
||||
@@ -1881,6 +2263,12 @@ dependencies = [
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "semver"
|
||||
version = "1.0.28"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd"
|
||||
|
||||
[[package]]
|
||||
name = "serde"
|
||||
version = "1.0.229"
|
||||
@@ -2037,6 +2425,12 @@ version = "2.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de"
|
||||
|
||||
[[package]]
|
||||
name = "signature"
|
||||
version = "3.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "28d567dcbaf0049cb8ac2608a76cd95ff9e4412e1899d389ee400918ca7537f5"
|
||||
|
||||
[[package]]
|
||||
name = "simd-adler32"
|
||||
version = "0.3.10"
|
||||
@@ -2055,6 +2449,17 @@ version = "1.16.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d0d5d4b1981b8bbbb7aed204cae5726d683d5d6ac7e74ec54122ea28f315e7c8"
|
||||
|
||||
[[package]]
|
||||
name = "socket-pktinfo"
|
||||
version = "0.4.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "612942246d0cc239cfd83af1dfd39be47f649208a3524e5e9da651910128e0ac"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"socket2",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "socket2"
|
||||
version = "0.6.5"
|
||||
@@ -2065,6 +2470,15 @@ dependencies = [
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "spin"
|
||||
version = "0.9.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3763264f6b73151db08c50ff20d7d8a0b8796e021cdea7ceedad07b80155fa0e"
|
||||
dependencies = [
|
||||
"lock_api",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "spki"
|
||||
version = "0.7.3"
|
||||
@@ -2075,6 +2489,12 @@ dependencies = [
|
||||
"der",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "static_assertions"
|
||||
version = "1.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f"
|
||||
|
||||
[[package]]
|
||||
name = "str0m"
|
||||
version = "0.24.1"
|
||||
@@ -2199,6 +2619,19 @@ dependencies = [
|
||||
"version-compare",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "system-deps"
|
||||
version = "9.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "db551ad38aac61d5e0343e0eeeb0163be3115c4e23b6a025959570ee0c03c67d"
|
||||
dependencies = [
|
||||
"cfg-expr",
|
||||
"heck",
|
||||
"pkg-config",
|
||||
"toml",
|
||||
"version-compare",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "target-lexicon"
|
||||
version = "0.13.5"
|
||||
@@ -2746,12 +3179,107 @@ dependencies = [
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows"
|
||||
version = "0.62.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "527fadee13e0c05939a6a05d5bd6eec6cd2e3dbd648b9f8e447c6518133d8580"
|
||||
dependencies = [
|
||||
"windows-collections",
|
||||
"windows-core",
|
||||
"windows-future",
|
||||
"windows-numerics",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-collections"
|
||||
version = "0.3.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "23b2d95af1a8a14a3c7367e1ed4fc9c20e0a26e79551b1454d72583c97cc6610"
|
||||
dependencies = [
|
||||
"windows-core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-core"
|
||||
version = "0.62.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb"
|
||||
dependencies = [
|
||||
"windows-implement",
|
||||
"windows-interface",
|
||||
"windows-link",
|
||||
"windows-result",
|
||||
"windows-strings",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-future"
|
||||
version = "0.3.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e1d6f90251fe18a279739e78025bd6ddc52a7e22f921070ccdc67dde84c605cb"
|
||||
dependencies = [
|
||||
"windows-core",
|
||||
"windows-link",
|
||||
"windows-threading",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-implement"
|
||||
version = "0.60.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-interface"
|
||||
version = "0.59.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-link"
|
||||
version = "0.2.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
|
||||
|
||||
[[package]]
|
||||
name = "windows-numerics"
|
||||
version = "0.3.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6e2e40844ac143cdb44aead537bbf727de9b044e107a0f1220392177d15b0f26"
|
||||
dependencies = [
|
||||
"windows-core",
|
||||
"windows-link",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-result"
|
||||
version = "0.4.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5"
|
||||
dependencies = [
|
||||
"windows-link",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-strings"
|
||||
version = "0.5.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091"
|
||||
dependencies = [
|
||||
"windows-link",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-sys"
|
||||
version = "0.52.0"
|
||||
@@ -2786,6 +3314,15 @@ dependencies = [
|
||||
"windows_x86_64_msvc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-threading"
|
||||
version = "0.2.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3949bd5b99cafdf1c7ca86b43ca564028dfe27d66958f2470940f73d86d75b37"
|
||||
dependencies = [
|
||||
"windows-link",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows_aarch64_gnullvm"
|
||||
version = "0.52.6"
|
||||
|
||||
@@ -23,7 +23,7 @@ test:
|
||||
# They are excluded from the formatter and the linter (see biome.json): their
|
||||
# format belongs to ts-rs, otherwise every `make` leaves a diff in the repository.
|
||||
proto:
|
||||
cargo test -p rs-proto -p rs-store -p rs-session export_bindings
|
||||
cargo test -p rs-proto -p rs-store -p rs-session -p rs-signaling export_bindings
|
||||
|
||||
build:
|
||||
cargo build --workspace
|
||||
@@ -42,6 +42,7 @@ desktop:
|
||||
cd apps/desktop/src-tauri && CARGO_TARGET_DIR=../../../target cargo build --release --features pipewire
|
||||
|
||||
desktop-lint:
|
||||
node scripts/check-licenses.mjs --desktop
|
||||
pnpm --dir apps/desktop lint
|
||||
pnpm --dir apps/desktop test
|
||||
cd apps/desktop/src-tauri && cargo fmt --check && CARGO_TARGET_DIR=../../../target cargo clippy --features pipewire -- -D warnings
|
||||
|
||||
@@ -8,34 +8,30 @@
|
||||
côté spectateur. Réimplémentation de [Deskreen](https://deskreen.com) (Electron + WebRTC) avec un
|
||||
hôte en Rust, un client web en TypeScript et une interface desktop Tauri.
|
||||
|
||||
État : **jalon 0.3 « Voir l'écran »**. Ce qui tourne aujourd'hui, vérifié le 26 octobre 2026:
|
||||
État : **jalon 0.6 « Parité Pro »**, Linux seulement. Pour s'en servir, lire le
|
||||
[guide de l'utilisateur](docs/guide/README.md). Ce qui tourne:
|
||||
|
||||
- workspace Rust de neuf crates, protocole partagé avec types TypeScript générés
|
||||
- `rs-capture`: capture Linux réelle, portail et PipeWire sous Wayland, X11 (XShm) en repli, plus
|
||||
une mire synthétique
|
||||
- **écran virtuel** par le portail du bureau (`--virtual`): la tablette devient un second écran,
|
||||
vérifié sur GNOME 46
|
||||
- `rs-diag`: journal JSON local en rotation, archive de diagnostics expurgée (`--diagnostics`)
|
||||
- `rs-codec`: conversion BGRA vers I420 en BT.709, encodeur VP8 libvpx, pont vers la session
|
||||
- `rs-rtc`: session str0m par spectateur, avec sa boucle testée
|
||||
- `rs-signaling`: serveur local, jeton de room, WebSocket de signalement, TLS auto-signé
|
||||
- `rs-session`: l'hôte (partage, spectateurs, réglages, veille, réseau) et le binaire `rustscreen`
|
||||
- `rs-store`: réglages persistants, écriture atomique, fichier corrompu mis de côté
|
||||
- `apps/desktop`: coque Tauri, choix de la source avec vignettes, QR, spectateurs, réglages
|
||||
- `apps/viewer`: viewer React avec machine à états, reprise après coupure ou veille, statistiques
|
||||
- une session complète de bout en bout: capture synthétique, encodage en direct, VP8 dans le
|
||||
navigateur, couleurs vérifiées à l'écran (voir `docs/perf.md` pour les mesures)
|
||||
- capture Linux réelle: portail et PipeWire sous Wayland, X11 en repli, chaque écran, une fenêtre
|
||||
seule, et un **second écran virtuel** créé par le bureau (GNOME 46, KDE Plasma);
|
||||
- encodage VP8 ou VP9 temps réel jusqu'à 60 images par seconde, une session WebRTC par spectateur;
|
||||
- application de bureau Tauri: choix de la source, QR code et code court, spectateurs, réglages,
|
||||
icône de barre système, français et anglais;
|
||||
- page du spectateur sans installation: reprise après coupure ou veille, rotation, miroir, plein
|
||||
écran;
|
||||
- appareils de confiance qui reviennent sans QR code, nom local `rustscreen.local`, lien à usage
|
||||
unique, changement de source sans couper les spectateurs;
|
||||
- journal local et archive de diagnostics expurgée, aucun appel sortant.
|
||||
|
||||
Restent à écrire: la capture Windows (#8, après la 1.0), l'icône de barre système (#22), et
|
||||
l'encodeur matériel (#57). Les prérequis de build hors Rust sont libvpx (`scripts/build-libvpx.sh`)
|
||||
et, pour la capture Wayland, libpipewire-0.3 et libclang (`nix develop` fournit tout): voir
|
||||
AGENTS.md.
|
||||
Reste à écrire: Windows (capture, encodeur matériel, intégration système). macOS n'est pas pris
|
||||
en charge comme hôte (#90); un Mac reste un spectateur comme un autre, par son navigateur. Les prérequis de build
|
||||
hors Rust sont libvpx (`scripts/build-libvpx.sh`) et, pour la capture Wayland, libpipewire-0.3 et
|
||||
libclang (`nix develop` fournit tout): voir AGENTS.md.
|
||||
|
||||
## Pourquoi
|
||||
|
||||
Deskreen fonctionne, mais son hôte Electron coûte 210 Mo sur disque, ~250 Mo de RAM par session et
|
||||
repose sur Chromium pour capturer et encoder. Un hôte Rust permet de capturer au plus près du
|
||||
système (DXGI, ScreenCaptureKit, PipeWire), d'encoder en VP8/H.264 matériel, et de servir un client
|
||||
système (PipeWire, DXGI), d'encoder en VP8/H.264 matériel, et de servir un client
|
||||
web minimal. Le spectateur reste un simple onglet, comme dans Deskreen.
|
||||
|
||||
Objectifs mesurables :
|
||||
@@ -83,8 +79,7 @@ docs architecture, ADR, matrice de fonctionnalités, backlog
|
||||
- Rust stable (édition 2024), `cargo`
|
||||
- Node 22+, npm pour `apps/viewer`, pnpm pour `apps/desktop` (`nix develop .#desktop`)
|
||||
- Linux : PipeWire et `xdg-desktop-portal` (Wayland), X11 accepté en repli
|
||||
- macOS : 12.3+ pour ScreenCaptureKit
|
||||
- Windows : 10 1809+ pour la duplications de bureau DXGI
|
||||
- Windows : 10 1809+ pour la duplication de bureau DXGI (en cours, pas encore utilisable)
|
||||
|
||||
## Installer
|
||||
|
||||
@@ -102,6 +97,12 @@ capturent l'écran sous Wayland (portail) et X11; `--synthetic` reste là pour e
|
||||
Apache-2.0, voir [LICENSE](LICENSE). Licence permissive avec clause de brevets explicite: elle
|
||||
laisse réutiliser le code, y compris dans un produit commercial, sans imposer de partager le reste.
|
||||
|
||||
Les dépendances livrées sont compatibles, et la CI le vérifie à chaque commit
|
||||
(`scripts/check-licenses.mjs`): MIT, Apache-2.0, BSD, ISC, Zlib pour l'essentiel; libvpx est en
|
||||
BSD-3-Clause; `env-libvpx-sys` et quelques crates de la coque (`cssparser`, `selectors`) sont en
|
||||
MPL-2.0, dont le copyleft porte sur leurs propres fichiers, livrés sans modification. WebKitGTK
|
||||
(LGPL-2.1) et PipeWire sont des bibliothèques du système, liées dynamiquement.
|
||||
|
||||
## Feuille de route
|
||||
|
||||
[docs/ROADMAP.md](docs/ROADMAP.md) dit ce qui doit exister pour une 1.0 honnête, dans quel ordre, et
|
||||
|
||||
Generated
+429
-51
@@ -156,7 +156,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "241b621213072e993be4f6f3a9e4b45f65b7e6faad43001be957184b7bb1824b"
|
||||
dependencies = [
|
||||
"atk-sys",
|
||||
"glib",
|
||||
"glib 0.18.5",
|
||||
"libc",
|
||||
]
|
||||
|
||||
@@ -166,8 +166,8 @@ version = "0.18.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c5e48b684b0ca77d2bbadeef17424c2ea3c897d44d566a1617e7e8f30614d086"
|
||||
dependencies = [
|
||||
"glib-sys",
|
||||
"gobject-sys",
|
||||
"glib-sys 0.18.1",
|
||||
"gobject-sys 0.18.0",
|
||||
"libc",
|
||||
"system-deps 6.2.2",
|
||||
]
|
||||
@@ -178,6 +178,12 @@ version = "1.1.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0"
|
||||
|
||||
[[package]]
|
||||
name = "atomic_refcell"
|
||||
version = "0.1.14"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "21e4227379beff4205943696e6c3e0cd809bacdf3f0edd6e3dd153e2269571a4"
|
||||
|
||||
[[package]]
|
||||
name = "autocfg"
|
||||
version = "1.5.1"
|
||||
@@ -325,7 +331,7 @@ dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"cexpr",
|
||||
"clang-sys",
|
||||
"itertools",
|
||||
"itertools 0.13.0",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"regex",
|
||||
@@ -471,7 +477,7 @@ checksum = "8ca26ef0159422fb77631dc9d17b102f253b876fe1586b03b803e63a309b4ee2"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"cairo-sys-rs",
|
||||
"glib",
|
||||
"glib 0.18.5",
|
||||
"libc",
|
||||
"once_cell",
|
||||
"thiserror 1.0.69",
|
||||
@@ -483,7 +489,7 @@ version = "0.18.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "685c9fa8e590b8b3d678873528d83411db17242a73fccaed827770ea0fedda51"
|
||||
dependencies = [
|
||||
"glib-sys",
|
||||
"glib-sys 0.18.1",
|
||||
"libc",
|
||||
"system-deps 6.2.2",
|
||||
]
|
||||
@@ -858,6 +864,32 @@ dependencies = [
|
||||
"cipher",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "curve25519-dalek"
|
||||
version = "5.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b5eed333089e2e1c1ac8c6c0398e5e2497b4c9926ca6d0365ed1e099afa5bc23"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"cpufeatures 0.3.1",
|
||||
"curve25519-dalek-derive",
|
||||
"digest 0.11.3",
|
||||
"fiat-crypto",
|
||||
"rustc_version",
|
||||
"subtle",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "curve25519-dalek-derive"
|
||||
version = "0.1.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f46882e17999c6cc590af592290432be3bce0428cb0d5f8b6715e4dc7b383eb3"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "darling"
|
||||
version = "0.24.1"
|
||||
@@ -1047,7 +1079,7 @@ dependencies = [
|
||||
"rand 0.9.5",
|
||||
"rcgen",
|
||||
"sec1",
|
||||
"signature",
|
||||
"signature 2.2.0",
|
||||
"spki",
|
||||
"subtle",
|
||||
"time",
|
||||
@@ -1172,6 +1204,27 @@ version = "1.0.20"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555"
|
||||
|
||||
[[package]]
|
||||
name = "ed25519"
|
||||
version = "3.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "29fcf32e6c73d1079f83ab4d782de2d81620346a5f38c6237a86a22f8368980a"
|
||||
dependencies = [
|
||||
"signature 3.0.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ed25519-dalek"
|
||||
version = "3.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6ebaa1a2bf1290ab3bfe5a7b771d050ebffab2711c19a81691c683a5144a25de"
|
||||
dependencies = [
|
||||
"curve25519-dalek",
|
||||
"ed25519",
|
||||
"sha2 0.11.1",
|
||||
"subtle",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "either"
|
||||
version = "1.19.0"
|
||||
@@ -1255,6 +1308,12 @@ dependencies = [
|
||||
"simd-adler32",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fiat-crypto"
|
||||
version = "0.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "64cd1e32ddd350061ae6edb1b082d7c54915b5c672c389143b9a63403a109f24"
|
||||
|
||||
[[package]]
|
||||
name = "field-offset"
|
||||
version = "0.3.6"
|
||||
@@ -1288,6 +1347,15 @@ dependencies = [
|
||||
"zlib-rs",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "flume"
|
||||
version = "0.12.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5e139bc46ca777eb5efaf62df0ab8cc5fd400866427e56c68b22e414e53bd3be"
|
||||
dependencies = [
|
||||
"spin",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fnv"
|
||||
version = "1.0.7"
|
||||
@@ -1433,7 +1501,7 @@ dependencies = [
|
||||
"gdk-pixbuf",
|
||||
"gdk-sys",
|
||||
"gio",
|
||||
"glib",
|
||||
"glib 0.18.5",
|
||||
"libc",
|
||||
"pango",
|
||||
]
|
||||
@@ -1446,7 +1514,7 @@ checksum = "50e1f5f1b0bfb830d6ccc8066d18db35c487b1b2b1e8589b5dfe9f07e8defaec"
|
||||
dependencies = [
|
||||
"gdk-pixbuf-sys",
|
||||
"gio",
|
||||
"glib",
|
||||
"glib 0.18.5",
|
||||
"libc",
|
||||
"once_cell",
|
||||
]
|
||||
@@ -1457,9 +1525,9 @@ version = "0.18.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3f9839ea644ed9c97a34d129ad56d38a25e6756f99f3a88e15cd39c20629caf7"
|
||||
dependencies = [
|
||||
"gio-sys",
|
||||
"glib-sys",
|
||||
"gobject-sys",
|
||||
"gio-sys 0.18.1",
|
||||
"glib-sys 0.18.1",
|
||||
"gobject-sys 0.18.0",
|
||||
"libc",
|
||||
"system-deps 6.2.2",
|
||||
]
|
||||
@@ -1472,9 +1540,9 @@ checksum = "5c2d13f38594ac1e66619e188c6d5a1adb98d11b2fcf7894fc416ad76aa2f3f7"
|
||||
dependencies = [
|
||||
"cairo-sys-rs",
|
||||
"gdk-pixbuf-sys",
|
||||
"gio-sys",
|
||||
"glib-sys",
|
||||
"gobject-sys",
|
||||
"gio-sys 0.18.1",
|
||||
"glib-sys 0.18.1",
|
||||
"gobject-sys 0.18.0",
|
||||
"libc",
|
||||
"pango-sys",
|
||||
"pkg-config",
|
||||
@@ -1488,8 +1556,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "140071d506d223f7572b9f09b5e155afbd77428cd5cc7af8f2694c41d98dfe69"
|
||||
dependencies = [
|
||||
"gdk-sys",
|
||||
"glib-sys",
|
||||
"gobject-sys",
|
||||
"glib-sys 0.18.1",
|
||||
"gobject-sys 0.18.0",
|
||||
"libc",
|
||||
"pkg-config",
|
||||
"system-deps 6.2.2",
|
||||
@@ -1504,7 +1572,7 @@ dependencies = [
|
||||
"gdk",
|
||||
"gdkx11-sys",
|
||||
"gio",
|
||||
"glib",
|
||||
"glib 0.18.5",
|
||||
"libc",
|
||||
"x11",
|
||||
]
|
||||
@@ -1516,7 +1584,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6e2e7445fe01ac26f11601db260dd8608fe172514eb63b3b5e261ea6b0f4428d"
|
||||
dependencies = [
|
||||
"gdk-sys",
|
||||
"glib-sys",
|
||||
"glib-sys 0.18.1",
|
||||
"libc",
|
||||
"system-deps 6.2.2",
|
||||
"x11",
|
||||
@@ -1589,8 +1657,8 @@ dependencies = [
|
||||
"futures-core",
|
||||
"futures-io",
|
||||
"futures-util",
|
||||
"gio-sys",
|
||||
"glib",
|
||||
"gio-sys 0.18.1",
|
||||
"glib 0.18.5",
|
||||
"libc",
|
||||
"once_cell",
|
||||
"pin-project-lite",
|
||||
@@ -1604,13 +1672,26 @@ version = "0.18.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "37566df850baf5e4cb0dfb78af2e4b9898d817ed9263d1090a2df958c64737d2"
|
||||
dependencies = [
|
||||
"glib-sys",
|
||||
"gobject-sys",
|
||||
"glib-sys 0.18.1",
|
||||
"gobject-sys 0.18.0",
|
||||
"libc",
|
||||
"system-deps 6.2.2",
|
||||
"winapi",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "gio-sys"
|
||||
version = "0.22.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6c28739f914c15b87a9856000bed9cbd5b3a8afbca5e982d9a299e1601422cb5"
|
||||
dependencies = [
|
||||
"glib-sys 0.22.9",
|
||||
"gobject-sys 0.22.9",
|
||||
"libc",
|
||||
"system-deps 9.0.1",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "glib"
|
||||
version = "0.18.5"
|
||||
@@ -1623,10 +1704,10 @@ dependencies = [
|
||||
"futures-executor",
|
||||
"futures-task",
|
||||
"futures-util",
|
||||
"gio-sys",
|
||||
"glib-macros",
|
||||
"glib-sys",
|
||||
"gobject-sys",
|
||||
"gio-sys 0.18.1",
|
||||
"glib-macros 0.18.5",
|
||||
"glib-sys 0.18.1",
|
||||
"gobject-sys 0.18.0",
|
||||
"libc",
|
||||
"memchr",
|
||||
"once_cell",
|
||||
@@ -1634,6 +1715,27 @@ dependencies = [
|
||||
"thiserror 1.0.69",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "glib"
|
||||
version = "0.22.10"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e4cf9e5bd8713f1990a92c422998826e0fb34824277b46bc59757373483c6694"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"futures-channel",
|
||||
"futures-core",
|
||||
"futures-executor",
|
||||
"futures-task",
|
||||
"futures-util",
|
||||
"gio-sys 0.22.9",
|
||||
"glib-macros 0.22.9",
|
||||
"glib-sys 0.22.9",
|
||||
"gobject-sys 0.22.9",
|
||||
"libc",
|
||||
"memchr",
|
||||
"smallvec",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "glib-macros"
|
||||
version = "0.18.5"
|
||||
@@ -1648,6 +1750,18 @@ dependencies = [
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "glib-macros"
|
||||
version = "0.22.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c9597c68fa7bdf4154a3079642cd21c4dccac0b0bdd2897d82861523bf91e7b9"
|
||||
dependencies = [
|
||||
"heck 0.5.0",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 3.0.9",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "glib-sys"
|
||||
version = "0.18.1"
|
||||
@@ -1658,6 +1772,16 @@ dependencies = [
|
||||
"system-deps 6.2.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "glib-sys"
|
||||
version = "0.22.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "99b38907e67e40dec9b60f858bcada952598719cb512a13eb13d6cdcd16f8295"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"system-deps 9.0.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "glob"
|
||||
version = "0.3.4"
|
||||
@@ -1670,11 +1794,145 @@ version = "0.18.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0850127b514d1c4a4654ead6dedadb18198999985908e6ffe4436f53c785ce44"
|
||||
dependencies = [
|
||||
"glib-sys",
|
||||
"glib-sys 0.18.1",
|
||||
"libc",
|
||||
"system-deps 6.2.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "gobject-sys"
|
||||
version = "0.22.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "07595c9ba696bd9819cb6a8df39f08078f3dd679508fe052dd558492c2053834"
|
||||
dependencies = [
|
||||
"glib-sys 0.22.9",
|
||||
"libc",
|
||||
"system-deps 9.0.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "gstreamer"
|
||||
version = "0.25.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f4237e2066a25ecb7e54be6c066409e30615920265b9799b8d560ef8ac9857c6"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"futures-channel",
|
||||
"futures-core",
|
||||
"futures-util",
|
||||
"glib 0.22.10",
|
||||
"gstreamer-sys",
|
||||
"itertools 0.15.0",
|
||||
"kstring",
|
||||
"libc",
|
||||
"muldiv",
|
||||
"num-integer",
|
||||
"num-rational",
|
||||
"option-operations",
|
||||
"pastey",
|
||||
"pin-project-lite",
|
||||
"smallvec",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "gstreamer-app"
|
||||
version = "0.25.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "97f8ae9238c2352398dcc084de28df3f7099af216ac6c160b52318d23f25c010"
|
||||
dependencies = [
|
||||
"futures-core",
|
||||
"futures-sink",
|
||||
"glib 0.22.10",
|
||||
"gstreamer",
|
||||
"gstreamer-app-sys",
|
||||
"gstreamer-base",
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "gstreamer-app-sys"
|
||||
version = "0.25.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0798b8aef6694341d40bb81edc759f8979b896b59f9f0f45d8cfa3bb7bf2e743"
|
||||
dependencies = [
|
||||
"glib-sys 0.22.9",
|
||||
"gstreamer-base-sys",
|
||||
"gstreamer-sys",
|
||||
"libc",
|
||||
"system-deps 9.0.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "gstreamer-base"
|
||||
version = "0.25.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "17cbd8f59586a369c40d4b0d2f3a61cf9e9287b3cf5503cdcd8e7c5faa99265e"
|
||||
dependencies = [
|
||||
"atomic_refcell",
|
||||
"cfg-if",
|
||||
"glib 0.22.10",
|
||||
"gstreamer",
|
||||
"gstreamer-base-sys",
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "gstreamer-base-sys"
|
||||
version = "0.25.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3b05f77bfd76b5afee6b29c27dae19eaf5018b5cf8d0d17520f3de44c6385c32"
|
||||
dependencies = [
|
||||
"glib-sys 0.22.9",
|
||||
"gobject-sys 0.22.9",
|
||||
"gstreamer-sys",
|
||||
"libc",
|
||||
"system-deps 9.0.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "gstreamer-sys"
|
||||
version = "0.25.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "436d9532847489a8285d57b8c3670762c12a18f777fdc2ab159b52e0e6f521b9"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"glib-sys 0.22.9",
|
||||
"gobject-sys 0.22.9",
|
||||
"libc",
|
||||
"system-deps 9.0.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "gstreamer-video"
|
||||
version = "0.25.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ffe4d77b2a5e679973d9c6b6c052da8cda86b83f5c268872f8691fde693fde84"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"futures-channel",
|
||||
"glib 0.22.10",
|
||||
"gstreamer",
|
||||
"gstreamer-base",
|
||||
"gstreamer-video-sys",
|
||||
"libc",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "gstreamer-video-sys"
|
||||
version = "0.25.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ef455da22edca97ac9299d682b868227f3d9217b303748ce0161b31ae82dc106"
|
||||
dependencies = [
|
||||
"glib-sys 0.22.9",
|
||||
"gobject-sys 0.22.9",
|
||||
"gstreamer-base-sys",
|
||||
"gstreamer-sys",
|
||||
"libc",
|
||||
"system-deps 9.0.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "gtk"
|
||||
version = "0.18.2"
|
||||
@@ -1688,7 +1946,7 @@ dependencies = [
|
||||
"gdk",
|
||||
"gdk-pixbuf",
|
||||
"gio",
|
||||
"glib",
|
||||
"glib 0.18.5",
|
||||
"gtk-sys",
|
||||
"gtk3-macros",
|
||||
"libc",
|
||||
@@ -1706,9 +1964,9 @@ dependencies = [
|
||||
"cairo-sys-rs",
|
||||
"gdk-pixbuf-sys",
|
||||
"gdk-sys",
|
||||
"gio-sys",
|
||||
"glib-sys",
|
||||
"gobject-sys",
|
||||
"gio-sys 0.18.1",
|
||||
"glib-sys 0.18.1",
|
||||
"gobject-sys 0.18.0",
|
||||
"libc",
|
||||
"pango-sys",
|
||||
"system-deps 6.2.2",
|
||||
@@ -2128,6 +2386,15 @@ dependencies = [
|
||||
"either",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "itertools"
|
||||
version = "0.15.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8b4baf93f58d4425749ca49a51c50ebab072c5df6994d08fed93541c331481dc"
|
||||
dependencies = [
|
||||
"either",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "itoa"
|
||||
version = "1.0.18"
|
||||
@@ -2141,7 +2408,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ca5671e9ffce8ffba57afc24070e906da7fc4b1ba66f2cabebf61bf2ea257fcc"
|
||||
dependencies = [
|
||||
"bitflags 1.3.2",
|
||||
"glib",
|
||||
"glib 0.18.5",
|
||||
"javascriptcore-rs-sys",
|
||||
]
|
||||
|
||||
@@ -2151,8 +2418,8 @@ version = "1.1.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "af1be78d14ffa4b75b66df31840478fef72b51f8c2465d4ca7c194da9f7a5124"
|
||||
dependencies = [
|
||||
"glib-sys",
|
||||
"gobject-sys",
|
||||
"glib-sys 0.18.1",
|
||||
"gobject-sys 0.18.0",
|
||||
"libc",
|
||||
"system-deps 6.2.2",
|
||||
]
|
||||
@@ -2308,6 +2575,15 @@ dependencies = [
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "kstring"
|
||||
version = "2.0.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "558bf9508a558512042d3095138b1f7b8fe90c5467d94f9f1da28b3731c5dbd1"
|
||||
dependencies = [
|
||||
"static_assertions",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "lazy_static"
|
||||
version = "1.5.1"
|
||||
@@ -2320,7 +2596,7 @@ version = "0.9.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "03589b9607c868cc7ae54c0b2a22c8dc03dd41692d48f2d7df73615c6a95dc0a"
|
||||
dependencies = [
|
||||
"glib",
|
||||
"glib 0.18.5",
|
||||
"gtk",
|
||||
"gtk-sys",
|
||||
"libappindicator-sys",
|
||||
@@ -2462,6 +2738,20 @@ version = "0.8.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "47e1ffaa40ddd1f3ed91f717a33c8c0ee23fff369e3aa8772b9605cc1d22f4c3"
|
||||
|
||||
[[package]]
|
||||
name = "mdns-sd"
|
||||
version = "0.21.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8562654710f72a9cbce4b0d5b7c366a2f94330ba1ce3740f15e932ea2d37b161"
|
||||
dependencies = [
|
||||
"fastrand",
|
||||
"flume",
|
||||
"if-addrs",
|
||||
"mio",
|
||||
"socket-pktinfo",
|
||||
"socket2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "memchr"
|
||||
version = "2.8.3"
|
||||
@@ -2526,6 +2816,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1788edb87fdc09c7e26304471e2f5be8cdefb1b6930d6e3985fc02ff53bf86ee"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"log",
|
||||
"wasi",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
@@ -2561,6 +2852,12 @@ dependencies = [
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "muldiv"
|
||||
version = "1.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "956787520e75e9bd233246045d19f42fb73242759cc57fba9611d940ae96d4b0"
|
||||
|
||||
[[package]]
|
||||
name = "ndk"
|
||||
version = "0.9.0"
|
||||
@@ -2662,6 +2959,16 @@ dependencies = [
|
||||
"num-traits",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "num-rational"
|
||||
version = "0.4.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f83d14da390562dca69fc84082e73e548e1ad308d24accdedd2720017cb37824"
|
||||
dependencies = [
|
||||
"num-integer",
|
||||
"num-traits",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "num-traits"
|
||||
version = "0.2.19"
|
||||
@@ -2910,6 +3217,15 @@ version = "0.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d"
|
||||
|
||||
[[package]]
|
||||
name = "option-operations"
|
||||
version = "0.6.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "aca39cf52b03268400c16eeb9b56382ea3c3353409309b63f5c8f0b1faf42754"
|
||||
dependencies = [
|
||||
"pastey",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ordered-stream"
|
||||
version = "0.2.0"
|
||||
@@ -2927,7 +3243,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7ca27ec1eb0457ab26f3036ea52229edbdb74dee1edd29063f5b9b010e7ebee4"
|
||||
dependencies = [
|
||||
"gio",
|
||||
"glib",
|
||||
"glib 0.18.5",
|
||||
"libc",
|
||||
"once_cell",
|
||||
"pango-sys",
|
||||
@@ -2939,8 +3255,8 @@ version = "0.18.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "436737e391a843e5933d6d9aa102cb126d501e815b83601365a948a518555dc5"
|
||||
dependencies = [
|
||||
"glib-sys",
|
||||
"gobject-sys",
|
||||
"glib-sys 0.18.1",
|
||||
"gobject-sys 0.18.0",
|
||||
"libc",
|
||||
"system-deps 6.2.2",
|
||||
]
|
||||
@@ -2968,6 +3284,12 @@ dependencies = [
|
||||
"windows-link",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pastey"
|
||||
version = "0.2.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2ee67f1008b1ba2321834326597b8e186293b049a023cdef258527550b9935b4"
|
||||
|
||||
[[package]]
|
||||
name = "pem"
|
||||
version = "4.0.0"
|
||||
@@ -3460,6 +3782,7 @@ dependencies = [
|
||||
"rustix",
|
||||
"thiserror 2.0.21",
|
||||
"tracing",
|
||||
"windows-sys 0.61.2",
|
||||
"x11rb",
|
||||
]
|
||||
|
||||
@@ -3468,8 +3791,12 @@ name = "rs-codec"
|
||||
version = "0.5.0"
|
||||
dependencies = [
|
||||
"env-libvpx-sys",
|
||||
"gstreamer",
|
||||
"gstreamer-app",
|
||||
"gstreamer-video",
|
||||
"rs-capture",
|
||||
"thiserror 2.0.21",
|
||||
"tokio",
|
||||
"tracing",
|
||||
]
|
||||
|
||||
@@ -3497,6 +3824,7 @@ dependencies = [
|
||||
"thiserror 2.0.21",
|
||||
"tokio",
|
||||
"tracing",
|
||||
"windows-sys 0.61.2",
|
||||
"zbus",
|
||||
]
|
||||
|
||||
@@ -3514,6 +3842,7 @@ dependencies = [
|
||||
name = "rs-rtc"
|
||||
version = "0.5.0"
|
||||
dependencies = [
|
||||
"if-addrs",
|
||||
"rs-codec",
|
||||
"str0m",
|
||||
"thiserror 2.0.21",
|
||||
@@ -3549,7 +3878,9 @@ version = "0.5.0"
|
||||
dependencies = [
|
||||
"axum",
|
||||
"axum-server",
|
||||
"ed25519-dalek",
|
||||
"hex",
|
||||
"mdns-sd",
|
||||
"qrcode",
|
||||
"rand 0.10.3",
|
||||
"rcgen",
|
||||
@@ -3563,6 +3894,7 @@ dependencies = [
|
||||
"tokio",
|
||||
"tower-http 0.7.1",
|
||||
"tracing",
|
||||
"ts-rs",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -3655,6 +3987,7 @@ version = "0.5.0"
|
||||
dependencies = [
|
||||
"libloading 0.8.9",
|
||||
"rs-diag",
|
||||
"rs-platform",
|
||||
"rs-session",
|
||||
"rs-store",
|
||||
"serde",
|
||||
@@ -4049,6 +4382,12 @@ version = "2.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de"
|
||||
|
||||
[[package]]
|
||||
name = "signature"
|
||||
version = "3.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "28d567dcbaf0049cb8ac2608a76cd95ff9e4412e1899d389ee400918ca7537f5"
|
||||
|
||||
[[package]]
|
||||
name = "simd-adler32"
|
||||
version = "0.3.10"
|
||||
@@ -4073,6 +4412,17 @@ version = "1.16.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d0d5d4b1981b8bbbb7aed204cae5726d683d5d6ac7e74ec54122ea28f315e7c8"
|
||||
|
||||
[[package]]
|
||||
name = "socket-pktinfo"
|
||||
version = "0.4.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "612942246d0cc239cfd83af1dfd39be47f649208a3524e5e9da651910128e0ac"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"socket2",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "socket2"
|
||||
version = "0.6.5"
|
||||
@@ -4113,7 +4463,7 @@ checksum = "471f924a40f31251afc77450e781cb26d55c0b650842efafc9c6cbd2f7cc4f9f"
|
||||
dependencies = [
|
||||
"futures-channel",
|
||||
"gio",
|
||||
"glib",
|
||||
"glib 0.18.5",
|
||||
"libc",
|
||||
"soup3-sys",
|
||||
]
|
||||
@@ -4124,13 +4474,22 @@ version = "0.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7ebe8950a680a12f24f15ebe1bf70db7af98ad242d9db43596ad3108aab86c27"
|
||||
dependencies = [
|
||||
"gio-sys",
|
||||
"glib-sys",
|
||||
"gobject-sys",
|
||||
"gio-sys 0.18.1",
|
||||
"glib-sys 0.18.1",
|
||||
"gobject-sys 0.18.0",
|
||||
"libc",
|
||||
"system-deps 6.2.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "spin"
|
||||
version = "0.9.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3763264f6b73151db08c50ff20d7d8a0b8796e021cdea7ceedad07b80155fa0e"
|
||||
dependencies = [
|
||||
"lock_api",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "spki"
|
||||
version = "0.7.3"
|
||||
@@ -4147,6 +4506,12 @@ version = "1.2.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596"
|
||||
|
||||
[[package]]
|
||||
name = "static_assertions"
|
||||
version = "1.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f"
|
||||
|
||||
[[package]]
|
||||
name = "static_vcruntime"
|
||||
version = "3.0.0"
|
||||
@@ -4342,6 +4707,19 @@ dependencies = [
|
||||
"version-compare",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "system-deps"
|
||||
version = "9.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "db551ad38aac61d5e0343e0eeeb0163be3115c4e23b6a025959570ee0c03c67d"
|
||||
dependencies = [
|
||||
"cfg-expr 0.20.10",
|
||||
"heck 0.5.0",
|
||||
"pkg-config",
|
||||
"toml 1.1.8+spec-1.1.0",
|
||||
"version-compare",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tao"
|
||||
version = "0.37.2"
|
||||
@@ -4627,7 +5005,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"
|
||||
dependencies = [
|
||||
"fastrand",
|
||||
"getrandom 0.4.3",
|
||||
"getrandom 0.3.4",
|
||||
"once_cell",
|
||||
"rustix",
|
||||
"windows-sys 0.61.2",
|
||||
@@ -5422,10 +5800,10 @@ dependencies = [
|
||||
"gdk",
|
||||
"gdk-sys",
|
||||
"gio",
|
||||
"gio-sys",
|
||||
"glib",
|
||||
"glib-sys",
|
||||
"gobject-sys",
|
||||
"gio-sys 0.18.1",
|
||||
"glib 0.18.5",
|
||||
"glib-sys 0.18.1",
|
||||
"gobject-sys 0.18.0",
|
||||
"gtk",
|
||||
"gtk-sys",
|
||||
"javascriptcore-rs",
|
||||
@@ -5444,9 +5822,9 @@ dependencies = [
|
||||
"bitflags 1.3.2",
|
||||
"cairo-sys-rs",
|
||||
"gdk-sys",
|
||||
"gio-sys",
|
||||
"glib-sys",
|
||||
"gobject-sys",
|
||||
"gio-sys 0.18.1",
|
||||
"glib-sys 0.18.1",
|
||||
"gobject-sys 0.18.0",
|
||||
"gtk-sys",
|
||||
"javascriptcore-rs-sys",
|
||||
"libc",
|
||||
|
||||
@@ -26,9 +26,12 @@ default = ["custom-protocol"]
|
||||
custom-protocol = ["tauri/custom-protocol"]
|
||||
# Real Wayland capture (ADR 0009), like the command-line binary.
|
||||
pipewire = ["rs-session/pipewire"]
|
||||
# Hardware encoding (#57), like the command-line binary.
|
||||
vaapi = ["rs-session/vaapi"]
|
||||
|
||||
[dependencies]
|
||||
rs-diag = { path = "../../../crates/rs-diag" }
|
||||
rs-platform = { path = "../../../crates/rs-platform" }
|
||||
rs-session = { path = "../../../crates/rs-session" }
|
||||
rs-store = { path = "../../../crates/rs-store" }
|
||||
# `tray-icon`: system tray icon (#22); `image-png`: its icons.
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 361 KiB |
@@ -14,7 +14,7 @@ use rs_session::{
|
||||
Config, Host, HostState, InterfaceOption, Overrides, Phase, SettingsOutcome, SourceChoice,
|
||||
SourceOption,
|
||||
};
|
||||
use rs_store::{CloseAction, Rejection, Settings};
|
||||
use rs_store::{CloseAction, Notice, Rejection, Settings};
|
||||
use tauri::{Emitter, Manager, RunEvent, State, WindowEvent};
|
||||
|
||||
/// The last started source, so that the system tray menu can restart a share
|
||||
@@ -60,7 +60,7 @@ async fn start(
|
||||
host: State<'_, Host>,
|
||||
last: State<'_, LastSource>,
|
||||
choice: SourceChoice,
|
||||
) -> Result<(), String> {
|
||||
) -> Result<(), Notice> {
|
||||
*last.0.lock().unwrap_or_else(|e| e.into_inner()) = Some(choice.clone());
|
||||
host.start(choice).await
|
||||
}
|
||||
@@ -81,6 +81,36 @@ fn regenerate_access(host: State<'_, Host>) -> bool {
|
||||
host.regenerate_access()
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
async fn trust_device(host: State<'_, Host>, connection: u64) -> Result<(), Notice> {
|
||||
host.trust_device(connection).await
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
async fn switch_source(
|
||||
host: State<'_, Host>,
|
||||
last: State<'_, LastSource>,
|
||||
choice: SourceChoice,
|
||||
) -> Result<(), Notice> {
|
||||
host.switch_source(choice.clone()).await?;
|
||||
*last.0.lock().unwrap_or_else(|e| e.into_inner()) = Some(choice);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
async fn rename_device(
|
||||
host: State<'_, Host>,
|
||||
connection: u64,
|
||||
alias: Option<String>,
|
||||
) -> Result<(), Notice> {
|
||||
host.rename_device(connection, alias).await
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
async fn revoke_device(host: State<'_, Host>, key: String) -> Result<(), Notice> {
|
||||
host.revoke_device(&key).await
|
||||
}
|
||||
|
||||
/// The texts of the system tray menu, in the language of the interface.
|
||||
#[tauri::command]
|
||||
fn translate_tray(
|
||||
@@ -228,12 +258,23 @@ fn main() {
|
||||
// mount: its file is what must be relaunched.
|
||||
let executable = std::env::var_os("APPIMAGE")
|
||||
.map(PathBuf::from)
|
||||
.or_else(|| std::env::current_exe().ok());
|
||||
.or_else(|| std::env::current_exe().ok())
|
||||
.map(|exe| rs_platform::autostart::launcher(&exe, std::env::var_os("PATH").as_deref()));
|
||||
// An update may have moved the binary: the autostart entry follows (#32).
|
||||
if let (Some(exe), Some(dir)) = (&executable, rs_platform::autostart::directory()) {
|
||||
match rs_platform::autostart::refresh(&dir, exe, AUTOSTARTED) {
|
||||
Ok(true) => tracing::info!(event = "autostart_refreshed", "autostart entry updated"),
|
||||
Ok(false) => {}
|
||||
Err(error) => tracing::warn!(%error, "autostart entry not updated"),
|
||||
}
|
||||
}
|
||||
let autostarted = std::env::args().any(|a| a == AUTOSTARTED || a == AUTOSTARTED_LEGACY);
|
||||
|
||||
let host = tauri::async_runtime::block_on(Host::new(Config {
|
||||
version: env!("CARGO_PKG_VERSION").into(),
|
||||
viewer_dir: std::env::var_os("RUSTSCREEN_VIEWER").map(PathBuf::from),
|
||||
viewer_dir: std::env::var_os("RUSTSCREEN_VIEWER")
|
||||
.map(PathBuf::from)
|
||||
.or_else(rs_session::installed_viewer),
|
||||
tls: false,
|
||||
store: rs_store::Store::user_default(),
|
||||
overrides: Overrides::default(),
|
||||
@@ -251,6 +292,10 @@ fn main() {
|
||||
stop,
|
||||
disconnect,
|
||||
regenerate_access,
|
||||
trust_device,
|
||||
revoke_device,
|
||||
rename_device,
|
||||
switch_source,
|
||||
translate_tray,
|
||||
quit,
|
||||
settings,
|
||||
|
||||
@@ -25,6 +25,6 @@
|
||||
},
|
||||
"bundle": {
|
||||
"active": false,
|
||||
"icon": ["icons/icon.png"]
|
||||
"icon": ["icons/icon.png", "icons/icon.ico"]
|
||||
}
|
||||
}
|
||||
+88
-11
@@ -8,8 +8,8 @@ import { SettingsDialog } from './components/SettingsDialog';
|
||||
import { SharePanel } from './components/SharePanel';
|
||||
import { SourcePicker } from './components/SourcePicker';
|
||||
import { effectiveLanguage, I18nProvider, useI18n } from './i18n';
|
||||
import type { Host } from './lib/host';
|
||||
import { actions, key, status, trayTexts } from './lib/view';
|
||||
import { type Host, rejectionsOf } from './lib/host';
|
||||
import { actions, isVirtual, key, say, status, trayTexts, withSize } from './lib/view';
|
||||
|
||||
/**
|
||||
* The language comes from the host settings, or from the desktop. Changing it
|
||||
@@ -37,6 +37,8 @@ function Shell({ host, onLanguage }: { host: Host; onLanguage: (code: string | n
|
||||
const [sending, setSending] = useState(false);
|
||||
const [settingsOpen, setSettingsOpen] = useState(false);
|
||||
const [confirmQuit, setConfirmQuit] = useState(false);
|
||||
// Picking another source while sharing (#26): viewers stay connected.
|
||||
const [switching, setSwitching] = useState(false);
|
||||
const [theme, setTheme] = useState<Theme>('system');
|
||||
|
||||
// The state comes from the host, always complete: subscribe before reading,
|
||||
@@ -88,6 +90,31 @@ function Shell({ host, onLanguage }: { host: Host; onLanguage: (code: string | n
|
||||
});
|
||||
}, [host]);
|
||||
|
||||
// The size is a setting (#89): saved at once, it applies to the next start
|
||||
// or, while sharing, to the next "Switch to".
|
||||
const changeVirtualSize = useCallback(
|
||||
async (size: [number, number]) => {
|
||||
const settings = await host.settings();
|
||||
try {
|
||||
await host.updateSettings({ ...settings, virtual_size: size });
|
||||
} catch (e) {
|
||||
throw rejectionsOf(e)
|
||||
.map((r) => say(r.message, t))
|
||||
.join('; ');
|
||||
}
|
||||
setSelection((choice) => choice && withSize(choice, size));
|
||||
setSources(
|
||||
(list) =>
|
||||
list?.map((s) =>
|
||||
isVirtual(s.choice)
|
||||
? { ...s, choice: withSize(s.choice, size), width: size[0], height: size[1] }
|
||||
: s,
|
||||
) ?? null,
|
||||
);
|
||||
},
|
||||
[host, t],
|
||||
);
|
||||
|
||||
const phase = state?.phase;
|
||||
useEffect(() => {
|
||||
if (phase === 'stopped') {
|
||||
@@ -112,6 +139,13 @@ function Shell({ host, onLanguage }: { host: Host; onLanguage: (code: string | n
|
||||
}
|
||||
};
|
||||
const portal = selection?.type === 'portal';
|
||||
const live = state.phase === 'live' && state.share !== null;
|
||||
const picking = switching && live;
|
||||
const switchTo = (choice: SourceChoice) =>
|
||||
send(async () => {
|
||||
await host.switchSource(choice);
|
||||
setSwitching(false);
|
||||
});
|
||||
|
||||
return (
|
||||
<div className='app'>
|
||||
@@ -134,30 +168,68 @@ function Shell({ host, onLanguage }: { host: Host; onLanguage: (code: string | n
|
||||
<main className='content'>
|
||||
<Banners state={state} />
|
||||
|
||||
{state.phase === 'live' && state.share ? (
|
||||
{state.phase === 'live' && state.share && !picking ? (
|
||||
<SharePanel
|
||||
share={state.share}
|
||||
onDisconnect={(connection) => send(() => host.disconnect(connection))}
|
||||
onNewCode={() => send(() => host.regenerateAccess())}
|
||||
onTrust={(connection) => send(() => host.trustDevice(connection))}
|
||||
onRename={(connection, alias) => send(() => host.renameDevice(connection, alias))}
|
||||
/>
|
||||
) : (
|
||||
<SourcePicker
|
||||
sources={sources}
|
||||
selection={selection}
|
||||
enabled={buttons.pick}
|
||||
enabled={buttons.pick || picking}
|
||||
onPick={setSelection}
|
||||
onRefresh={refresh}
|
||||
onVirtualSize={changeVirtualSize}
|
||||
/>
|
||||
)}
|
||||
</main>
|
||||
|
||||
<footer className='action-bar'>
|
||||
{state.phase === 'starting' && (
|
||||
{(state.phase === 'starting' || (picking && sending)) && (
|
||||
<p className='waiting' role='status'>
|
||||
{portal ? t('waitingDesktop') : t('waiting')}
|
||||
</p>
|
||||
)}
|
||||
<span className='spacer' />
|
||||
{picking && (
|
||||
<>
|
||||
<button
|
||||
type='button'
|
||||
className='button'
|
||||
disabled={sending}
|
||||
onClick={() => setSwitching(false)}
|
||||
>
|
||||
{t('cancel')}
|
||||
</button>
|
||||
<button
|
||||
type='button'
|
||||
className='button primary'
|
||||
disabled={!selection || sending}
|
||||
onClick={() => selection && switchTo(selection)}
|
||||
>
|
||||
{t('switchTo')}
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
{live && !picking && (
|
||||
<button
|
||||
type='button'
|
||||
className='button'
|
||||
title={t('switchHelp')}
|
||||
disabled={sending}
|
||||
onClick={() => {
|
||||
setSelection(null);
|
||||
refresh();
|
||||
setSwitching(true);
|
||||
}}
|
||||
>
|
||||
{t('switchSource')}
|
||||
</button>
|
||||
)}
|
||||
{buttons.start.visible && (
|
||||
<button
|
||||
type='button'
|
||||
@@ -207,6 +279,8 @@ function Shell({ host, onLanguage }: { host: Host; onLanguage: (code: string | n
|
||||
onSaved={(s) => {
|
||||
setTheme(s.theme);
|
||||
onLanguage(s.language);
|
||||
// The test pattern comes and goes with its setting (#91).
|
||||
if (buttons.pick) refresh();
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
@@ -220,23 +294,26 @@ function Banners({ state }: { state: HostState }) {
|
||||
<>
|
||||
{state.error && state.phase === 'stopped' && (
|
||||
<div className='banner error' role='alert'>
|
||||
<strong>{t('startFailed')}</strong> {state.error}
|
||||
<strong>{t('startFailed')}</strong> {say(state.error, t)}
|
||||
</div>
|
||||
)}
|
||||
{state.stop && state.phase === 'stopped' && (
|
||||
<div className='banner error' role='alert'>
|
||||
<strong>{t('stoppedByDesktop')}</strong> {state.stop.reason}
|
||||
<strong>{t('stoppedByDesktop')}</strong> {say(state.stop.reason, t)}
|
||||
</div>
|
||||
)}
|
||||
{state.settings_recovered && <div className='banner warning'>{state.settings_recovered}</div>}
|
||||
{state.settings_recovered && (
|
||||
<div className='banner warning'>{say(state.settings_recovered, t)}</div>
|
||||
)}
|
||||
{state.warnings.map((w) => (
|
||||
<div key={w} className='banner warning' role='alert'>
|
||||
{w}
|
||||
<div key={w.text} className='banner warning' role='alert'>
|
||||
{say(w, t)}
|
||||
</div>
|
||||
))}
|
||||
{state.pending_settings.length > 0 && (
|
||||
<div className='banner info'>
|
||||
<strong>{t('pendingSettings')}</strong> {state.pending_settings.join('; ')}
|
||||
<strong>{t('pendingSettings')}</strong>{' '}
|
||||
{state.pending_settings.map((n) => say(n, t)).join('; ')}
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
|
||||
@@ -4,4 +4,4 @@
|
||||
* Video codec of the shares (#67). VP9 keeps the same quality at a lower
|
||||
* bitrate, but costs 1.6x the CPU of VP8 (`docs/perf.md`).
|
||||
*/
|
||||
export type Codec = "vp8" | "vp9";
|
||||
export type Codec = "vp8" | "vp9" | "h264";
|
||||
@@ -0,0 +1,7 @@
|
||||
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
|
||||
import type { DeviceId } from "../../../viewer/src/proto/DeviceId";
|
||||
|
||||
/**
|
||||
* The host's name for a device (#37).
|
||||
*/
|
||||
export type DeviceAlias = { id: DeviceId, name: string, };
|
||||
@@ -1,5 +1,6 @@
|
||||
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
|
||||
import type { Capabilities } from "./Capabilities";
|
||||
import type { Notice } from "./Notice";
|
||||
import type { Phase } from "./Phase";
|
||||
import type { Share } from "./Share";
|
||||
import type { Stop } from "./Stop";
|
||||
@@ -9,14 +10,14 @@ import type { Stop } from "./Stop";
|
||||
*/
|
||||
export type HostState = { phase: Phase, share: Share | null,
|
||||
/**
|
||||
* Failure of the last start, to display as is.
|
||||
* Failure of the last start, translated by the interface (#75).
|
||||
*/
|
||||
error: string | null, stop: Stop | null,
|
||||
error: Notice | null, stop: Stop | null,
|
||||
/**
|
||||
* What still works but deserves to be known (interface down, address
|
||||
* changed).
|
||||
*/
|
||||
warnings: Array<string>,
|
||||
warnings: Array<Notice>,
|
||||
/**
|
||||
* Sleep inhibition mechanisms held (`login1`, `screensaver`): empty
|
||||
* outside a share, or if none could be taken.
|
||||
@@ -25,11 +26,11 @@ sleep_inhibited: Array<string>,
|
||||
/**
|
||||
* Settings changed during the share, applied to the next one.
|
||||
*/
|
||||
pending_settings: Array<string>,
|
||||
pending_settings: Array<Notice>,
|
||||
/**
|
||||
* The settings file was unusable at startup: what was done about it.
|
||||
*/
|
||||
settings_recovered: string | null,
|
||||
settings_recovered: Notice | null,
|
||||
/**
|
||||
* Capabilities of this machine, to offer only what works.
|
||||
*/
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
|
||||
|
||||
/**
|
||||
* The local name of the host, as the interface shows it (#25).
|
||||
*/
|
||||
export type LocalNameInfo = {
|
||||
/**
|
||||
* `rustscreen.local`, or `rustscreen-2.local` if the name was taken.
|
||||
*/
|
||||
host: string,
|
||||
/**
|
||||
* Home page by name, to type the short code: `http://rustscreen.local:8099/`.
|
||||
*/
|
||||
url: string,
|
||||
/**
|
||||
* Another machine answers over mDNS: the name most likely works. Until
|
||||
* then the interface puts the address first and says the name is a try.
|
||||
*/
|
||||
confirmed: boolean, };
|
||||
@@ -0,0 +1,16 @@
|
||||
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
|
||||
|
||||
export type Notice = {
|
||||
/**
|
||||
* Key under `desktop.host` in `locales/`, snake case (`port_in_use`).
|
||||
*/
|
||||
code: string,
|
||||
/**
|
||||
* Values of the placeholders: numbers, interface names, paths, and the
|
||||
* system's own words (`detail`), which no catalog can translate.
|
||||
*/
|
||||
params: { [key in string]: string },
|
||||
/**
|
||||
* The English sentence, for the command line and unknown codes.
|
||||
*/
|
||||
text: string, };
|
||||
@@ -0,0 +1,17 @@
|
||||
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
|
||||
import type { RefusalCause } from "./RefusalCause";
|
||||
|
||||
/**
|
||||
* A connection the host refused, kept for the interface and the diagnostics:
|
||||
* "who tried to get in, from where, and why it failed" answers most session
|
||||
* questions without reading a log (#35).
|
||||
*/
|
||||
export type Refusal = {
|
||||
/**
|
||||
* When, in milliseconds since the Unix epoch.
|
||||
*/
|
||||
at_ms: number, address: string,
|
||||
/**
|
||||
* Device name announced by the viewer, empty if it never said.
|
||||
*/
|
||||
device: string, cause: RefusalCause, };
|
||||
@@ -0,0 +1,6 @@
|
||||
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
|
||||
|
||||
/**
|
||||
* Why a connection was refused, as the host interface names it (#35).
|
||||
*/
|
||||
export type RefusalCause = "bad_token" | "token_used" | "expired_token" | "kicked" | "room_full" | "not_trusted" | "no_media_port";
|
||||
@@ -1,7 +1,8 @@
|
||||
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
|
||||
import type { Notice } from "./Notice";
|
||||
|
||||
/**
|
||||
* A rejected value, named by its field: the interface places it next to the
|
||||
* faulty field, and the message reads as is.
|
||||
*/
|
||||
export type Rejection = { field: string, message: string, };
|
||||
export type Rejection = { field: string, message: Notice, };
|
||||
@@ -2,6 +2,7 @@
|
||||
import type { QualityPreset } from "../../../viewer/src/proto/QualityPreset";
|
||||
import type { CloseAction } from "./CloseAction";
|
||||
import type { Codec } from "./Codec";
|
||||
import type { DeviceAlias } from "./DeviceAlias";
|
||||
import type { Theme } from "./Theme";
|
||||
import type { TrustedDevice } from "./TrustedDevice";
|
||||
|
||||
@@ -18,6 +19,11 @@ export type Settings = { version: number,
|
||||
* Listening port of the server (viewer and signaling).
|
||||
*/
|
||||
port: number,
|
||||
/**
|
||||
* First UDP port of the media (#88): one per viewer, [`MAX_LIMIT`] in a
|
||||
* row, the range to open in a firewall. `0`: right after `port`.
|
||||
*/
|
||||
media_port: number,
|
||||
/**
|
||||
* Name of the network interface to listen on (`wlp2s0`, `enp3s0`).
|
||||
* `None`: all interfaces.
|
||||
@@ -37,6 +43,11 @@ limit: number,
|
||||
* Quality offered when a share starts.
|
||||
*/
|
||||
quality: QualityPreset, codec: Codec,
|
||||
/**
|
||||
* Let the GPU encode when it can (#57): VP9 and H.264 through VA-API.
|
||||
* Off, libvpx encodes everything; H.264 then falls back on VP8.
|
||||
*/
|
||||
hardware_encoding: boolean,
|
||||
/**
|
||||
* Minutes during which the QR code and the short code let a new device in
|
||||
* (#19). `0`: no limit. Devices already admitted come back after the
|
||||
@@ -50,4 +61,18 @@ autostart: boolean, close_action: CloseAction,
|
||||
/**
|
||||
* Ask for confirmation before quitting during a share (#43).
|
||||
*/
|
||||
confirm_quit: boolean, trusted_devices: Array<TrustedDevice>, };
|
||||
confirm_quit: boolean, trusted_devices: Array<TrustedDevice>,
|
||||
/**
|
||||
* Names the host gave to devices, by device id (#37). They win over the
|
||||
* name a viewer announces, and survive a restart.
|
||||
*/
|
||||
aliases: Array<DeviceAlias>,
|
||||
/**
|
||||
* Width and height of the virtual screen the portal creates (#89).
|
||||
*/
|
||||
virtual_size: [number, number],
|
||||
/**
|
||||
* Offer the test pattern among the sources (#91): a debugging aid, off
|
||||
* by default. The command line's `--synthetic` does not depend on it.
|
||||
*/
|
||||
test_pattern: boolean, };
|
||||
@@ -1,4 +1,5 @@
|
||||
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
|
||||
import type { Notice } from "./Notice";
|
||||
|
||||
/**
|
||||
* What a settings change produces.
|
||||
@@ -9,6 +10,7 @@ export type SettingsOutcome = {
|
||||
*/
|
||||
immediate: Array<string>,
|
||||
/**
|
||||
* Fields waiting for the next share, with the reason.
|
||||
* Fields waiting for the next share, with the reason; `field` in the
|
||||
* parameters names the field.
|
||||
*/
|
||||
next_share: Array<string>, };
|
||||
next_share: Array<Notice>, };
|
||||
@@ -1,4 +1,6 @@
|
||||
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
|
||||
import type { LocalNameInfo } from "./LocalNameInfo";
|
||||
import type { Refusal } from "./Refusal";
|
||||
import type { SharedSource } from "./SharedSource";
|
||||
import type { ViewerDevice } from "./ViewerDevice";
|
||||
|
||||
@@ -39,4 +41,14 @@ listen: string,
|
||||
/**
|
||||
* Chosen interface, `None` if the host listens everywhere.
|
||||
*/
|
||||
interface: string | null, devices: Array<ViewerDevice>, limit: number, started_ms: number, };
|
||||
interface: string | null, devices: Array<ViewerDevice>,
|
||||
/**
|
||||
* Connections refused since the share started, newest first (#35): who
|
||||
* tried, from where, and why it did not work.
|
||||
*/
|
||||
refusals: Array<Refusal>,
|
||||
/**
|
||||
* `rustscreen.local`, when announced (#25). The QR code keeps the
|
||||
* address: the name is for whoever types.
|
||||
*/
|
||||
local_name: LocalNameInfo | null, limit: number, started_ms: number, };
|
||||
@@ -4,7 +4,7 @@
|
||||
* What the user chooses to share. The interface sends back the `choice` of a
|
||||
* [`SourceOption`] as is.
|
||||
*/
|
||||
export type SourceChoice = { "type": "synthetic", width: number, height: number, } | { "type": "x11", id: string, } | { "type": "portal", virtual_display: boolean,
|
||||
export type SourceChoice = { "type": "synthetic", width: number, height: number, } | { "type": "x11", id: string, } | { "type": "windows", id: string, } | { "type": "portal", virtual_display: boolean,
|
||||
/**
|
||||
* A window rather than a screen (#17), if the portal allows it.
|
||||
*/
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
|
||||
import type { Notice } from "./Notice";
|
||||
|
||||
/**
|
||||
* Why the last share stopped, when it was not the user.
|
||||
*/
|
||||
export type Stop = { reason: string,
|
||||
export type Stop = { reason: Notice,
|
||||
/**
|
||||
* Stopped from the desktop ("stop sharing" button, screen unplugged):
|
||||
* the command line then exits with code 3.
|
||||
|
||||
@@ -2,7 +2,18 @@
|
||||
import type { DeviceId } from "../../../viewer/src/proto/DeviceId";
|
||||
|
||||
/**
|
||||
* A device allowed to come back without scanning again (#34). The storage
|
||||
* exists already so that the format does not need a new version that day.
|
||||
* A device allowed to come back without scanning again (#34).
|
||||
*
|
||||
* The host keeps the public key only: the device proves it holds the private
|
||||
* one by signing a challenge, and the private key never leaves it.
|
||||
*/
|
||||
export type TrustedDevice = { id: DeviceId, name: string, };
|
||||
export type TrustedDevice = { id: DeviceId, name: string,
|
||||
/**
|
||||
* Ed25519 public key, 64 lowercase hex digits. Empty in a file written
|
||||
* before #34: such an entry lets nobody in.
|
||||
*/
|
||||
key: string,
|
||||
/**
|
||||
* When the host started trusting it, in milliseconds since the Unix epoch.
|
||||
*/
|
||||
added_ms: number, };
|
||||
@@ -7,8 +7,32 @@ export type ViewerDevice = {
|
||||
/**
|
||||
* Number to send back to disconnect it.
|
||||
*/
|
||||
connection: number, name: string, platform: string | null, address: string,
|
||||
connection: number,
|
||||
/**
|
||||
* The name to show: the host's alias if it gave one (#37), otherwise the
|
||||
* name the viewer announces (#36). Plain text, markup included.
|
||||
*/
|
||||
name: string,
|
||||
/**
|
||||
* The name the viewer announces, to show next to an alias and to go
|
||||
* back to.
|
||||
*/
|
||||
announced: string, aliased: boolean, platform: string | null, address: string,
|
||||
/**
|
||||
* MAC address from the neighbour table, `None` when unknown: behind a
|
||||
* router, over IPv6, or the host itself (#38). Never logged.
|
||||
*/
|
||||
mac: string | null,
|
||||
/**
|
||||
* Arrival, in Unix milliseconds.
|
||||
*/
|
||||
since_ms: number, };
|
||||
since_ms: number,
|
||||
/**
|
||||
* The host trusts its key: it comes back without a link (#34).
|
||||
*/
|
||||
trusted: boolean,
|
||||
/**
|
||||
* It announced a key the host could trust. A browser without storage, or
|
||||
* too old to sign, has none.
|
||||
*/
|
||||
can_trust: boolean, };
|
||||
@@ -9,10 +9,10 @@ import type { SettingsOutcome } from '../bindings/SettingsOutcome';
|
||||
import type { Theme } from '../bindings/Theme';
|
||||
import { LANGUAGES, useI18n } from '../i18n';
|
||||
import { type Host, rejectionsOf } from '../lib/host';
|
||||
import { outcomeSummary } from '../lib/view';
|
||||
import { noticeOf, outcomeSummary, say } from '../lib/view';
|
||||
|
||||
const QUALITIES: QualityPreset[] = ['saver', 'balanced', 'sharp'];
|
||||
const CODECS: Codec[] = ['vp8', 'vp9'];
|
||||
const CODECS: Codec[] = ['vp8', 'vp9', 'h264'];
|
||||
const THEMES: Theme[] = ['system', 'light', 'dark'];
|
||||
const CLOSE_ACTIONS: CloseAction[] = ['tray', 'quit'];
|
||||
|
||||
@@ -50,7 +50,10 @@ export function SettingsDialog({ host, autostart, onClose, onSaved }: Props) {
|
||||
setRejections((r) => r.filter((x) => x.field !== field));
|
||||
setMessage(null);
|
||||
};
|
||||
const error = (field: string) => rejections.find((r) => r.field === field)?.message;
|
||||
const error = (field: string) => {
|
||||
const found = rejections.find((r) => r.field === field);
|
||||
return found ? say(found.message, t) : undefined;
|
||||
};
|
||||
|
||||
const save = async () => {
|
||||
setSending(true);
|
||||
@@ -67,11 +70,26 @@ export function SettingsDialog({ host, autostart, onClose, onSaved }: Props) {
|
||||
}
|
||||
};
|
||||
|
||||
// Revoking acts at once, without waiting for "Save": a device must lose
|
||||
// its access within the second (#34).
|
||||
const revoke = async (key: string) => {
|
||||
try {
|
||||
await host.revokeDevice(key);
|
||||
setSettings({
|
||||
...settings,
|
||||
trusted_devices: settings.trusted_devices.filter((d) => d.key !== key),
|
||||
});
|
||||
setRejections((r) => r.filter((x) => x.field !== 'trusted_devices'));
|
||||
} catch (e) {
|
||||
setRejections([{ field: 'trusted_devices', message: noticeOf(e) }]);
|
||||
}
|
||||
};
|
||||
|
||||
const exportDiagnostics = async () => {
|
||||
try {
|
||||
setMessage({ type: 'diagnostics', path: await host.exportDiagnostics() });
|
||||
} catch (e) {
|
||||
setRejections([{ field: 'diagnostics', message: String(e) }]);
|
||||
setRejections([{ field: 'diagnostics', message: noticeOf(e) }]);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -112,6 +130,22 @@ export function SettingsDialog({ host, autostart, onClose, onSaved }: Props) {
|
||||
onChange={(e) => change('port', Number(e.target.value))}
|
||||
/>
|
||||
</Field>
|
||||
<Field
|
||||
id={`${id}-media-port`}
|
||||
label={t('mediaPortField')}
|
||||
help={t('mediaPortHelp', firewall(settings))}
|
||||
error={error('media_port')}
|
||||
>
|
||||
<input
|
||||
id={`${id}-media-port`}
|
||||
type='number'
|
||||
min={0}
|
||||
max={65516}
|
||||
placeholder={String(settings.port + 1)}
|
||||
value={settings.media_port || ''}
|
||||
onChange={(e) => change('media_port', Number(e.target.value) || 0)}
|
||||
/>
|
||||
</Field>
|
||||
<Field
|
||||
id={`${id}-interface`}
|
||||
label={t('interface')}
|
||||
@@ -187,6 +221,14 @@ export function SettingsDialog({ host, autostart, onClose, onSaved }: Props) {
|
||||
))}
|
||||
</select>
|
||||
</Field>
|
||||
<label className='checkbox' title={t('hardwareEncodingHelp')}>
|
||||
<input
|
||||
type='checkbox'
|
||||
checked={settings.hardware_encoding}
|
||||
onChange={(e) => change('hardware_encoding', e.target.checked)}
|
||||
/>
|
||||
{t('hardwareEncoding')}
|
||||
</label>
|
||||
<Field id={`${id}-theme`} label={t('theme')}>
|
||||
<select
|
||||
id={`${id}-theme`}
|
||||
@@ -246,6 +288,52 @@ export function SettingsDialog({ host, autostart, onClose, onSaved }: Props) {
|
||||
{error('autostart') && <span className='field-error'>{error('autostart')}</span>}
|
||||
</label>
|
||||
)}
|
||||
<div className='field'>
|
||||
<span>{t('trustedDevices')}</span>
|
||||
{settings.trusted_devices.filter((d) => d.key).length === 0 ? (
|
||||
<span className='help'>{t('trustedNone')}</span>
|
||||
) : (
|
||||
<ul className='devices'>
|
||||
{settings.trusted_devices
|
||||
.filter((d) => d.key)
|
||||
.map((device) => (
|
||||
<li key={device.key}>
|
||||
<span className='device-name'>{device.name}</span>
|
||||
<span className='muted'>{device.key.slice(0, 16)}</span>
|
||||
<button
|
||||
type='button'
|
||||
className='button muted danger'
|
||||
title={t('revokeHelp')}
|
||||
onClick={() => revoke(device.key)}
|
||||
>
|
||||
{t('revoke')}
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
{error('trusted_devices') && (
|
||||
<span className='field-error'>{error('trusted_devices')}</span>
|
||||
)}
|
||||
</div>
|
||||
<fieldset className='debug'>
|
||||
<legend>{t('debug')}</legend>
|
||||
<label className='checkbox' title={t('testPatternHelp')}>
|
||||
<input
|
||||
type='checkbox'
|
||||
checked={settings.test_pattern}
|
||||
onChange={(e) => change('test_pattern', e.target.checked)}
|
||||
/>
|
||||
{t('testPattern')}
|
||||
</label>
|
||||
<div className='field'>
|
||||
<button type='button' className='button muted' onClick={exportDiagnostics}>
|
||||
{t('diagnostics')}
|
||||
</button>
|
||||
<span className='help'>{t('diagnosticsHelp')}</span>
|
||||
{error('diagnostics') && <span className='field-error'>{error('diagnostics')}</span>}
|
||||
</div>
|
||||
</fieldset>
|
||||
{error('file') && <p className='field-error'>{error('file')}</p>}
|
||||
{message && (
|
||||
<p className='confirmation' role='status'>
|
||||
@@ -255,10 +343,6 @@ export function SettingsDialog({ host, autostart, onClose, onSaved }: Props) {
|
||||
</p>
|
||||
)}
|
||||
<div className='dialog-actions'>
|
||||
<button type='button' className='button muted' onClick={exportDiagnostics}>
|
||||
{t('diagnostics')}
|
||||
</button>
|
||||
<span className='spacer' />
|
||||
<button type='button' className='button muted' onClick={onClose}>
|
||||
{t('close')}
|
||||
</button>
|
||||
@@ -266,14 +350,24 @@ export function SettingsDialog({ host, autostart, onClose, onSaved }: Props) {
|
||||
{t('save')}
|
||||
</button>
|
||||
</div>
|
||||
<p className='help'>{t('diagnosticsHelp')}</p>
|
||||
{error('diagnostics') && <p className='field-error'>{error('diagnostics')}</p>}
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The firewall rule for these settings (#88): the HTTP port, and the UDP range
|
||||
* of the media, one port per viewer. Mirrors `Settings::media_ports`.
|
||||
*/
|
||||
function firewall(settings: Settings): { port: number; first: number; last: number } {
|
||||
const first = settings.media_port || settings.port + 1;
|
||||
return { port: settings.port, first, last: first + MEDIA_PORTS - 1 };
|
||||
}
|
||||
|
||||
/** `rs_store::MAX_LIMIT`: one media port per possible viewer. */
|
||||
const MEDIA_PORTS = 20;
|
||||
|
||||
function Field({
|
||||
id,
|
||||
label,
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import type { Share } from '../bindings/Share';
|
||||
import type { ViewerDevice } from '../bindings/ViewerDevice';
|
||||
import { useI18n } from '../i18n';
|
||||
import { displayCode, displayName, duration, expiry } from '../lib/view';
|
||||
|
||||
@@ -7,9 +8,11 @@ type Props = {
|
||||
share: Share;
|
||||
onDisconnect: (connection: number) => void;
|
||||
onNewCode: () => void;
|
||||
onTrust: (connection: number) => void;
|
||||
onRename: (connection: number, alias: string | null) => void;
|
||||
};
|
||||
|
||||
export function SharePanel({ share, onDisconnect, onNewCode }: Props) {
|
||||
export function SharePanel({ share, onDisconnect, onNewCode, onTrust, onRename }: Props) {
|
||||
const { t } = useI18n();
|
||||
const now = useNow();
|
||||
const [copied, setCopied] = useState(false);
|
||||
@@ -25,7 +28,11 @@ export function SharePanel({ share, onDisconnect, onNewCode }: Props) {
|
||||
};
|
||||
|
||||
const [address] = share.listen.split(':');
|
||||
const home = share.url.split('/r/')[0] ?? share.url;
|
||||
const byAddress = share.url.split('/r/')[0] ?? share.url;
|
||||
// The name is offered first only once another machine answered over mDNS
|
||||
// (#25): otherwise the address, which always works, comes first.
|
||||
const named = share.local_name;
|
||||
const home = named?.confirmed ? named.url.replace(/\/$/, '') : byAddress;
|
||||
const remaining = expiry(share.expires_ms, now, t);
|
||||
return (
|
||||
<section className='share'>
|
||||
@@ -52,6 +59,13 @@ export function SharePanel({ share, onDisconnect, onNewCode }: Props) {
|
||||
<span className='muted'>
|
||||
{t('code')} {t('codeHelp', { home })}
|
||||
</span>
|
||||
{named && (
|
||||
<span className='muted local-name'>
|
||||
{named.confirmed
|
||||
? t('localNameAddress', { address: byAddress })
|
||||
: t('localNameUnconfirmed', { url: named.url.replace(/\/$/, '') })}
|
||||
</span>
|
||||
)}
|
||||
<strong className='code-value' aria-live='polite'>
|
||||
{displayCode(share.code)}
|
||||
</strong>
|
||||
@@ -108,29 +122,128 @@ export function SharePanel({ share, onDisconnect, onNewCode }: Props) {
|
||||
<ul className='devices'>
|
||||
{share.devices.map((device) => (
|
||||
<li key={device.connection}>
|
||||
<span className='device-name'>{device.name}</span>
|
||||
<DeviceLabel device={device} onRename={onRename} />
|
||||
<span className='muted'>
|
||||
{[device.platform, device.address].filter(Boolean).join(' · ')}
|
||||
{' · '}
|
||||
<span title={t('macHelp')}>
|
||||
{device.mac ? t('mac', { mac: device.mac }) : t('macUnknown')}
|
||||
</span>
|
||||
{' · '}
|
||||
{duration(device.since_ms, now)}
|
||||
</span>
|
||||
<button
|
||||
type='button'
|
||||
className='button muted danger'
|
||||
title={t('disconnectHelp')}
|
||||
onClick={() => onDisconnect(device.connection)}
|
||||
>
|
||||
{t('disconnect')}
|
||||
</button>
|
||||
<span className='device-actions'>
|
||||
{device.can_trust && (
|
||||
<button
|
||||
type='button'
|
||||
className='button muted'
|
||||
title={t('trustHelp')}
|
||||
onClick={() => onTrust(device.connection)}
|
||||
>
|
||||
{t('trust')}
|
||||
</button>
|
||||
)}
|
||||
<button
|
||||
type='button'
|
||||
className='button muted danger'
|
||||
title={t('disconnectHelp')}
|
||||
onClick={() => onDisconnect(device.connection)}
|
||||
>
|
||||
{t('disconnect')}
|
||||
</button>
|
||||
</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{share.refusals.length > 0 && (
|
||||
<div className='card'>
|
||||
<h2 className='viewers-title'>
|
||||
{t('refused')}
|
||||
<span className='counter'>{share.refusals.length}</span>
|
||||
</h2>
|
||||
<ul className='devices'>
|
||||
{share.refusals.slice(0, 5).map((refusal) => (
|
||||
<li key={`${refusal.at_ms}-${refusal.address}-${refusal.cause}`}>
|
||||
<span className='device-name'>{refusal.device || t('unknownDevice')}</span>
|
||||
<span className='muted'>
|
||||
{t(`refusal.${refusal.cause}`)} · {refusal.address} ·{' '}
|
||||
{duration(refusal.at_ms, now)}
|
||||
</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The device name, renamed in place by the host (#37). React renders it as
|
||||
* text: a name with markup shows as typed. An alias shows the announced name
|
||||
* next to it, with the way back to it.
|
||||
*/
|
||||
function DeviceLabel({
|
||||
device,
|
||||
onRename,
|
||||
}: {
|
||||
device: ViewerDevice;
|
||||
onRename: (connection: number, alias: string | null) => void;
|
||||
}) {
|
||||
const { t } = useI18n();
|
||||
const [draft, setDraft] = useState<string | null>(null);
|
||||
if (draft !== null) {
|
||||
const commit = () => {
|
||||
const alias = draft.trim();
|
||||
setDraft(null);
|
||||
if (alias !== device.name) onRename(device.connection, alias || null);
|
||||
};
|
||||
return (
|
||||
<span className='device-name'>
|
||||
<input
|
||||
// biome-ignore lint/a11y/noAutofocus: the field opens on the user's click.
|
||||
autoFocus
|
||||
aria-label={t('rename')}
|
||||
value={draft}
|
||||
maxLength={40}
|
||||
onChange={(e) => setDraft(e.target.value)}
|
||||
onBlur={commit}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter') e.currentTarget.blur();
|
||||
if (e.key === 'Escape') setDraft(null);
|
||||
}}
|
||||
/>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<span className='device-name'>
|
||||
<button
|
||||
type='button'
|
||||
className='link-button'
|
||||
title={t('renameHelp')}
|
||||
onClick={() => setDraft(device.name)}
|
||||
>
|
||||
{device.name}
|
||||
</button>
|
||||
{device.trusted && <span className='trusted-mark'>{t('trusted')}</span>}
|
||||
{device.aliased && (
|
||||
<button
|
||||
type='button'
|
||||
className='link-button muted alias-reset'
|
||||
title={t('aliasResetHelp')}
|
||||
onClick={() => onRename(device.connection, null)}
|
||||
>
|
||||
{t('aliasReset', { name: device.announced })}
|
||||
</button>
|
||||
)}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
/** The current time, refreshed every second for the displayed durations. */
|
||||
function useNow(): number {
|
||||
const [now, setNow] = useState(() => Date.now());
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import { useMemo, useState } from 'react';
|
||||
import { useId, useMemo, useState } from 'react';
|
||||
import type { SourceChoice } from '../bindings/SourceChoice';
|
||||
import type { SourceOption } from '../bindings/SourceOption';
|
||||
import { useI18n } from '../i18n';
|
||||
import { displayName, filter, key } from '../lib/view';
|
||||
import { displayName, filter, isVirtual, isVirtualSize, key, VIRTUAL_SIZES } from '../lib/view';
|
||||
|
||||
type Props = {
|
||||
sources: SourceOption[] | null;
|
||||
@@ -10,12 +10,21 @@ type Props = {
|
||||
enabled: boolean;
|
||||
onPick: (choice: SourceChoice) => void;
|
||||
onRefresh: () => void;
|
||||
/** Saves a new size for the virtual screen (#89); rejects with its message. */
|
||||
onVirtualSize: (size: [number, number]) => Promise<void>;
|
||||
};
|
||||
|
||||
/** Beyond this, the list gets long to scan: the search field appears. */
|
||||
const SEARCH_THRESHOLD = 6;
|
||||
|
||||
export function SourcePicker({ sources, selection, enabled, onPick, onRefresh }: Props) {
|
||||
export function SourcePicker({
|
||||
sources,
|
||||
selection,
|
||||
enabled,
|
||||
onPick,
|
||||
onRefresh,
|
||||
onVirtualSize,
|
||||
}: Props) {
|
||||
const { t } = useI18n();
|
||||
const [search, setSearch] = useState('');
|
||||
const visible = useMemo(() => filter(sources ?? [], search, t), [sources, search, t]);
|
||||
@@ -78,6 +87,119 @@ export function SourcePicker({ sources, selection, enabled, onPick, onRefresh }:
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
{selection?.type === 'portal' && isVirtual(selection) && selection.size && (
|
||||
<VirtualSize size={selection.size} enabled={enabled} onChange={onVirtualSize} />
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
const CUSTOM = 'custom';
|
||||
const SEPARATOR = 'x';
|
||||
|
||||
/** The value of a size in the select, not a displayed text. */
|
||||
function sizeValue([width, height]: [number, number]): string {
|
||||
return [width, height].join(SEPARATOR);
|
||||
}
|
||||
|
||||
/** The size of the virtual screen: a common one, or any even size (#89). */
|
||||
function VirtualSize({
|
||||
size,
|
||||
enabled,
|
||||
onChange,
|
||||
}: {
|
||||
size: [number, number];
|
||||
enabled: boolean;
|
||||
onChange: (size: [number, number]) => Promise<void>;
|
||||
}) {
|
||||
const { t } = useI18n();
|
||||
const id = useId();
|
||||
const preset = VIRTUAL_SIZES.find(([w, h]) => w === size[0] && h === size[1]);
|
||||
const [custom, setCustom] = useState(!preset);
|
||||
const [width, setWidth] = useState(String(size[0]));
|
||||
const [height, setHeight] = useState(String(size[1]));
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const apply = async (next: [number, number]) => {
|
||||
if (!isVirtualSize(next)) {
|
||||
setError(t('virtualSizeInvalid'));
|
||||
return;
|
||||
}
|
||||
setError(null);
|
||||
try {
|
||||
await onChange(next);
|
||||
} catch (e) {
|
||||
setError(String(e));
|
||||
}
|
||||
};
|
||||
const typed: [number, number] = [Number(width), Number(height)];
|
||||
|
||||
return (
|
||||
<div className='virtual-size'>
|
||||
<label htmlFor={`${id}-size`}>{t('virtualSize')}</label>
|
||||
<select
|
||||
id={`${id}-size`}
|
||||
disabled={!enabled}
|
||||
value={custom || !preset ? CUSTOM : sizeValue(preset)}
|
||||
onChange={(e) => {
|
||||
if (e.target.value === CUSTOM) {
|
||||
setCustom(true);
|
||||
return;
|
||||
}
|
||||
setCustom(false);
|
||||
const [w, h] = e.target.value.split(SEPARATOR).map(Number);
|
||||
setWidth(String(w));
|
||||
setHeight(String(h));
|
||||
void apply([w ?? 0, h ?? 0]);
|
||||
}}
|
||||
>
|
||||
{VIRTUAL_SIZES.map(([w, h]) => (
|
||||
<option key={sizeValue([w, h])} value={sizeValue([w, h])}>
|
||||
{w} × {h}
|
||||
</option>
|
||||
))}
|
||||
<option value={CUSTOM}>{t('virtualSizeCustom')}</option>
|
||||
</select>
|
||||
{(custom || !preset) && (
|
||||
<>
|
||||
<input
|
||||
type='number'
|
||||
className='size-input'
|
||||
min={640}
|
||||
max={7680}
|
||||
step={2}
|
||||
aria-label={t('virtualWidth')}
|
||||
value={width}
|
||||
disabled={!enabled}
|
||||
onChange={(e) => setWidth(e.target.value)}
|
||||
/>
|
||||
<input
|
||||
type='number'
|
||||
className='size-input'
|
||||
min={480}
|
||||
max={4320}
|
||||
step={2}
|
||||
aria-label={t('virtualHeight')}
|
||||
value={height}
|
||||
disabled={!enabled}
|
||||
onChange={(e) => setHeight(e.target.value)}
|
||||
/>
|
||||
<button
|
||||
type='button'
|
||||
className='button muted'
|
||||
disabled={!enabled || (typed[0] === size[0] && typed[1] === size[1])}
|
||||
onClick={() => void apply(typed)}
|
||||
>
|
||||
{t('apply')}
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
<span className='help'>{t('virtualSizeHelp')}</span>
|
||||
{error && (
|
||||
<span className='field-error' role='alert'>
|
||||
{error}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -7,7 +7,7 @@ import type { Settings } from '../bindings/Settings';
|
||||
import type { SettingsOutcome } from '../bindings/SettingsOutcome';
|
||||
import type { SourceChoice } from '../bindings/SourceChoice';
|
||||
import type { SourceOption } from '../bindings/SourceOption';
|
||||
import type { TrayTexts } from './view';
|
||||
import { noticeOf, type TrayTexts } from './view';
|
||||
|
||||
/**
|
||||
* What the interface can ask of the host. A single real implementation,
|
||||
@@ -23,6 +23,14 @@ export type Host = {
|
||||
disconnect(connection: number): Promise<boolean>;
|
||||
/** New QR code and new short code (#19). */
|
||||
regenerateAccess(): Promise<boolean>;
|
||||
/** Trusts the device on this connection: it comes back without a link (#34). */
|
||||
trustDevice(connection: number): Promise<void>;
|
||||
/** Stops trusting a key; a device connected with it is sent away. */
|
||||
revokeDevice(key: string): Promise<void>;
|
||||
/** The host's name for a device (#37); `null` gives back the announced one. */
|
||||
renameDevice(connection: number, alias: string | null): Promise<void>;
|
||||
/** Shares another source without cutting viewers off (#26). */
|
||||
switchSource(choice: SourceChoice): Promise<void>;
|
||||
settings(): Promise<Settings>;
|
||||
/** Rejects with the list of refused values. */
|
||||
updateSettings(settings: Settings): Promise<SettingsOutcome>;
|
||||
@@ -44,6 +52,10 @@ export const tauriHost: Host = {
|
||||
stop: () => invoke<void>('stop'),
|
||||
disconnect: (connection) => invoke<boolean>('disconnect', { connection }),
|
||||
regenerateAccess: () => invoke<boolean>('regenerate_access'),
|
||||
trustDevice: (connection) => invoke<void>('trust_device', { connection }),
|
||||
revokeDevice: (key) => invoke<void>('revoke_device', { key }),
|
||||
switchSource: (choice) => invoke<void>('switch_source', { choice }),
|
||||
renameDevice: (connection, alias) => invoke<void>('rename_device', { connection, alias }),
|
||||
settings: () => invoke<Settings>('settings'),
|
||||
updateSettings: (settings) => invoke<SettingsOutcome>('update_settings', { settings }),
|
||||
interfaces: () => invoke<InterfaceOption[]>('interfaces'),
|
||||
@@ -58,5 +70,5 @@ export function rejectionsOf(error: unknown): Rejection[] {
|
||||
if (Array.isArray(error)) {
|
||||
return error as Rejection[];
|
||||
}
|
||||
return [{ field: 'file', message: String(error) }];
|
||||
return [{ field: 'file', message: noticeOf(error) }];
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import type { HostState } from '../bindings/HostState';
|
||||
import type { Share } from '../bindings/Share';
|
||||
import type { SourceChoice } from '../bindings/SourceChoice';
|
||||
import type { SourceOption } from '../bindings/SourceOption';
|
||||
import { effectiveLanguage, LANGUAGES, translatorFor } from '../i18n';
|
||||
import {
|
||||
@@ -10,10 +11,15 @@ import {
|
||||
duration,
|
||||
expiry,
|
||||
filter,
|
||||
isVirtualSize,
|
||||
key,
|
||||
noticeOf,
|
||||
outcomeSummary,
|
||||
say,
|
||||
status,
|
||||
trayTexts,
|
||||
VIRTUAL_SIZES,
|
||||
withSize,
|
||||
} from './view';
|
||||
|
||||
const t = translatorFor('fr');
|
||||
@@ -153,10 +159,32 @@ describe('texts', () => {
|
||||
|
||||
it('a pending setting is said', () => {
|
||||
expect(outcomeSummary({ immediate: ['limit'], next_share: [] }, t)).toContain('appliqués');
|
||||
expect(outcomeSummary({ immediate: [], next_share: ['port: would cut'] }, t)).toContain(
|
||||
const pending = {
|
||||
code: 'pending_port',
|
||||
params: { field: 'port' },
|
||||
text: 'port: changing the port would cut viewers off',
|
||||
};
|
||||
expect(outcomeSummary({ immediate: [], next_share: [pending] }, t)).toContain(
|
||||
'prochain partage',
|
||||
);
|
||||
});
|
||||
|
||||
it('a host text follows the interface language (#75)', () => {
|
||||
const busy = {
|
||||
code: 'port_in_use_free',
|
||||
params: { port: '8099', free: '8100' },
|
||||
text: 'port 8099 is already used by another program: port 8100 is free',
|
||||
};
|
||||
const en = translatorFor('en');
|
||||
expect(say(busy, en)).toContain('8100');
|
||||
expect(say(busy, t)).toContain('8100');
|
||||
expect(say(busy, t)).not.toBe(say(busy, en));
|
||||
// A code this shell does not know yet: the host's sentence, not nothing.
|
||||
const newer = { code: 'from_the_future', params: {}, text: 'A newer host speaks.' };
|
||||
expect(say(newer, t)).toBe('A newer host speaks.');
|
||||
expect(noticeOf('boom').text).toBe('boom');
|
||||
expect(noticeOf(busy)).toBe(busy);
|
||||
});
|
||||
});
|
||||
|
||||
describe('short code (#19)', () => {
|
||||
@@ -194,3 +222,32 @@ describe('language (#21)', () => {
|
||||
expect(tray.live.other).toBe('En direct, {count} spectateurs');
|
||||
});
|
||||
});
|
||||
|
||||
describe('virtual screen size (#89)', () => {
|
||||
it('every offered size is accepted, odd or out of bounds ones are not', () => {
|
||||
for (const size of VIRTUAL_SIZES) expect(isVirtualSize(size)).toBe(true);
|
||||
expect(isVirtualSize([1281, 800])).toBe(false);
|
||||
expect(isVirtualSize([320, 240])).toBe(false);
|
||||
expect(isVirtualSize([8192, 4320])).toBe(false);
|
||||
expect(isVirtualSize([Number.NaN, 800])).toBe(false);
|
||||
});
|
||||
|
||||
it('only a virtual screen changes size', () => {
|
||||
const virtual: SourceChoice = {
|
||||
type: 'portal',
|
||||
virtual_display: true,
|
||||
window: false,
|
||||
size: [1920, 1080],
|
||||
};
|
||||
expect(withSize(virtual, [1280, 800])).toEqual({ ...virtual, size: [1280, 800] });
|
||||
const screen: SourceChoice = {
|
||||
type: 'portal',
|
||||
virtual_display: false,
|
||||
window: false,
|
||||
size: null,
|
||||
};
|
||||
expect(withSize(screen, [1280, 800])).toBe(screen);
|
||||
// The identity does not depend on the size: the selection survives.
|
||||
expect(key(withSize(virtual, [1280, 800]))).toBe(key(virtual));
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,7 @@
|
||||
import type { Translate } from '../../../viewer/src/lib/i18n';
|
||||
import type { HostState } from '../bindings/HostState';
|
||||
import type { Label } from '../bindings/Label';
|
||||
import type { Notice } from '../bindings/Notice';
|
||||
import type { SettingsOutcome } from '../bindings/SettingsOutcome';
|
||||
import type { SourceChoice } from '../bindings/SourceChoice';
|
||||
import type { SourceOption } from '../bindings/SourceOption';
|
||||
@@ -65,11 +66,52 @@ export function status(state: HostState, t: Translate): Status {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Sizes offered for a virtual screen (#89): common tablet and monitor
|
||||
* resolutions, in landscape. Any other even size can be typed.
|
||||
*/
|
||||
export const VIRTUAL_SIZES: [number, number][] = [
|
||||
[1280, 800],
|
||||
[1920, 1080],
|
||||
[1920, 1200],
|
||||
[2048, 1536],
|
||||
[2360, 1640],
|
||||
[2560, 1600],
|
||||
[2732, 2048],
|
||||
[3840, 2160],
|
||||
];
|
||||
|
||||
/** Mirrors `rs_store::is_virtual_size`: even, from 640 × 480 to 7680 × 4320. */
|
||||
export function isVirtualSize([width, height]: [number, number]): boolean {
|
||||
return (
|
||||
Number.isInteger(width) &&
|
||||
Number.isInteger(height) &&
|
||||
width % 2 === 0 &&
|
||||
height % 2 === 0 &&
|
||||
width >= 640 &&
|
||||
width <= 7680 &&
|
||||
height >= 480 &&
|
||||
height <= 4320
|
||||
);
|
||||
}
|
||||
|
||||
/** Is this choice a virtual screen, whose size can be chosen? */
|
||||
export function isVirtual(choice: SourceChoice | null): boolean {
|
||||
return choice?.type === 'portal' && choice.virtual_display;
|
||||
}
|
||||
|
||||
/** The same virtual screen at another size; any other choice unchanged. */
|
||||
export function withSize(choice: SourceChoice, size: [number, number]): SourceChoice {
|
||||
return choice.type === 'portal' && choice.virtual_display ? { ...choice, size } : choice;
|
||||
}
|
||||
|
||||
/** Stable identity of a choice, for the selection and React keys. */
|
||||
export function key(choice: SourceChoice): string {
|
||||
switch (choice.type) {
|
||||
case 'x11':
|
||||
return `x11:${choice.id}`;
|
||||
case 'windows':
|
||||
return `windows:${choice.id}`;
|
||||
case 'portal':
|
||||
if (choice.virtual_display) return 'portal:virtual';
|
||||
return choice.window ? 'portal:window' : 'portal:screen';
|
||||
@@ -141,10 +183,29 @@ export function duration(sinceMs: number, nowMs: number): string {
|
||||
return `${hours} h ${String(minutes % 60).padStart(2, '0')}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* A text produced by the host, in the interface language (#75): the code is
|
||||
* looked up under `host`, the English sentence of the host stands in for a
|
||||
* code this shell does not know yet.
|
||||
*/
|
||||
export function say(notice: Notice, t: Translate): string {
|
||||
return t(`host.${notice.code}`, notice.params) || notice.text;
|
||||
}
|
||||
|
||||
/** Turns any failure into a notice: a command rejects with one, or with anything else. */
|
||||
export function noticeOf(error: unknown): Notice {
|
||||
if (error && typeof error === 'object' && 'code' in error && 'text' in error) {
|
||||
return error as Notice;
|
||||
}
|
||||
return { code: '', params: {}, text: String(error) };
|
||||
}
|
||||
|
||||
/** What is said after saving settings. */
|
||||
export function outcomeSummary(outcome: SettingsOutcome, t: Translate): string {
|
||||
if (outcome.next_share.length > 0) {
|
||||
return t('settingsPending', { fields: outcome.next_share.join('; ') });
|
||||
return t('settingsPending', {
|
||||
fields: outcome.next_share.map((n) => say(n, t)).join('; '),
|
||||
});
|
||||
}
|
||||
if (outcome.immediate.length > 0) {
|
||||
return t('settingsApplied');
|
||||
|
||||
@@ -455,10 +455,47 @@ h2 {
|
||||
grid-row: 1 / span 2;
|
||||
}
|
||||
|
||||
.devices li .device-actions {
|
||||
grid-column: 2;
|
||||
grid-row: 1 / span 2;
|
||||
display: flex;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.device-name {
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.link-button {
|
||||
padding: 0;
|
||||
border: 0;
|
||||
background: none;
|
||||
color: inherit;
|
||||
font: inherit;
|
||||
text-align: left;
|
||||
cursor: text;
|
||||
}
|
||||
|
||||
.alias-reset {
|
||||
margin-left: 0.5rem;
|
||||
font-size: 0.8rem;
|
||||
font-weight: 400;
|
||||
text-decoration: underline;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.device-name input {
|
||||
font: inherit;
|
||||
padding: 0.1rem 0.3rem;
|
||||
}
|
||||
|
||||
.trusted-mark {
|
||||
margin-left: 0.5rem;
|
||||
color: var(--live);
|
||||
font-size: 0.8rem;
|
||||
font-weight: 400;
|
||||
}
|
||||
|
||||
.overlay {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
@@ -505,6 +542,34 @@ h2 {
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.debug {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: flex-start;
|
||||
gap: 0.6rem;
|
||||
margin: 0;
|
||||
padding: 0.75rem;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius);
|
||||
}
|
||||
|
||||
.debug legend {
|
||||
padding: 0 0.3rem;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.virtual-size {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
margin-top: 0.9rem;
|
||||
}
|
||||
|
||||
.size-input {
|
||||
width: 5.5rem;
|
||||
}
|
||||
|
||||
.field-error {
|
||||
color: var(--danger);
|
||||
font-size: 0.85rem;
|
||||
@@ -534,6 +599,11 @@ h2 {
|
||||
flex-basis: 100%;
|
||||
}
|
||||
|
||||
.short-code > .local-name {
|
||||
flex-basis: 100%;
|
||||
order: 1;
|
||||
}
|
||||
|
||||
.code-value {
|
||||
font:
|
||||
700 1.6rem / 1.1 ui-monospace,
|
||||
|
||||
Generated
+21
-42
@@ -8,6 +8,8 @@
|
||||
"name": "@rustscreen/viewer",
|
||||
"version": "0.5.0",
|
||||
"dependencies": {
|
||||
"@noble/ed25519": "^3.2.0",
|
||||
"@noble/hashes": "^2.4.0",
|
||||
"react": "^19.2.0",
|
||||
"react-dom": "^19.2.0"
|
||||
},
|
||||
@@ -126,9 +128,6 @@
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"libc": [
|
||||
"glibc"
|
||||
],
|
||||
"license": "MIT OR Apache-2.0",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -146,9 +145,6 @@
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"libc": [
|
||||
"musl"
|
||||
],
|
||||
"license": "MIT OR Apache-2.0",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -166,9 +162,6 @@
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"libc": [
|
||||
"glibc"
|
||||
],
|
||||
"license": "MIT OR Apache-2.0",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -186,9 +179,6 @@
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"libc": [
|
||||
"musl"
|
||||
],
|
||||
"license": "MIT OR Apache-2.0",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -260,6 +250,25 @@
|
||||
"@jridgewell/sourcemap-codec": "^1.4.14"
|
||||
}
|
||||
},
|
||||
"node_modules/@noble/ed25519": {
|
||||
"version": "3.2.0",
|
||||
"resolved": "https://registry.npmjs.org/@noble/ed25519/-/ed25519-3.2.0.tgz",
|
||||
"integrity": "sha512-criDgRlnUA09hchYrTy/JUWPIEap5rZxQe6wDWzRx51oWWpDRcUpuNzlgPxDJaOK6AsW9c0wKcj3rKRv6t+bPQ==",
|
||||
"funding": {
|
||||
"url": "https://paulmillr.com/funding/"
|
||||
}
|
||||
},
|
||||
"node_modules/@noble/hashes": {
|
||||
"version": "2.4.0",
|
||||
"resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-2.4.0.tgz",
|
||||
"integrity": "sha512-X5XaVWZIBCT7HHZGm5I7ZQXDwLG+bGXuSrMQAW+7Zvl87h1kmc1ZB1VSRJcpUfoUrGQp4Fkoxm5kZ+Ms+aW+eA==",
|
||||
"engines": {
|
||||
"node": ">= 20.19.0"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://paulmillr.com/funding/"
|
||||
}
|
||||
},
|
||||
"node_modules/@oxc-project/types": {
|
||||
"version": "0.155.0",
|
||||
"resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.155.0.tgz",
|
||||
@@ -380,9 +389,6 @@
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"libc": [
|
||||
"glibc"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -400,9 +406,6 @@
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"libc": [
|
||||
"musl"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -420,9 +423,6 @@
|
||||
"ppc64"
|
||||
],
|
||||
"dev": true,
|
||||
"libc": [
|
||||
"glibc"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -440,9 +440,6 @@
|
||||
"s390x"
|
||||
],
|
||||
"dev": true,
|
||||
"libc": [
|
||||
"glibc"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -460,9 +457,6 @@
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"libc": [
|
||||
"glibc"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -480,9 +474,6 @@
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"libc": [
|
||||
"musl"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -1243,9 +1234,6 @@
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"libc": [
|
||||
"glibc"
|
||||
],
|
||||
"license": "MPL-2.0",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -1267,9 +1255,6 @@
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"libc": [
|
||||
"musl"
|
||||
],
|
||||
"license": "MPL-2.0",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -1291,9 +1276,6 @@
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"libc": [
|
||||
"glibc"
|
||||
],
|
||||
"license": "MPL-2.0",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -1315,9 +1297,6 @@
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"libc": [
|
||||
"musl"
|
||||
],
|
||||
"license": "MPL-2.0",
|
||||
"optional": true,
|
||||
"os": [
|
||||
|
||||
@@ -13,6 +13,8 @@
|
||||
"test": "vitest run"
|
||||
},
|
||||
"dependencies": {
|
||||
"@noble/ed25519": "^3.2.0",
|
||||
"@noble/hashes": "^2.4.0",
|
||||
"react": "^19.2.0",
|
||||
"react-dom": "^19.2.0"
|
||||
},
|
||||
|
||||
+86
-42
@@ -1,13 +1,21 @@
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
|
||||
import { ErrorPanel } from './components/ErrorPanel';
|
||||
import { LanguagePicker } from './components/LanguagePicker';
|
||||
import { Pairing } from './components/Pairing';
|
||||
import { SettingsPanel } from './components/SettingsPanel';
|
||||
import { StatsBar } from './components/StatsBar';
|
||||
import { StatusBadge } from './components/StatusBadge';
|
||||
import { VideoStage } from './components/VideoStage';
|
||||
import { useI18n } from './i18n';
|
||||
import { barsVisible, IDLE_DELAY_MS, isCompact, readPinned, savePinned } from './lib/controls';
|
||||
import {
|
||||
barsVisible,
|
||||
IDLE_DELAY_MS,
|
||||
isCompact,
|
||||
readPinned,
|
||||
readStatsShown,
|
||||
savePinned,
|
||||
saveStatsShown,
|
||||
} from './lib/controls';
|
||||
import { parseRoomLocation, signalingUrl } from './lib/room';
|
||||
import {
|
||||
nextRotation,
|
||||
@@ -18,8 +26,11 @@ import {
|
||||
saveRotation,
|
||||
} from './lib/rotation';
|
||||
import { type VideoStats, ViewerSession, type ViewerState } from './lib/session';
|
||||
import { applyTheme, nextTheme, readTheme, saveTheme, type Theme } from './lib/theme';
|
||||
import { isTrusted } from './lib/trust';
|
||||
import { useActivity } from './lib/useActivity';
|
||||
import type { SourceInfo } from './proto';
|
||||
|
||||
const SWITCH_NOTICE_MS = 2500;
|
||||
|
||||
export function App() {
|
||||
const { t } = useI18n();
|
||||
@@ -27,16 +38,24 @@ export function App() {
|
||||
() => parseRoomLocation(window.location.pathname, window.location.search, window.location.hash),
|
||||
[],
|
||||
);
|
||||
// A device the host trusts comes back from the bare home page, without a
|
||||
// link: it proves its key instead (#34).
|
||||
const byKey = useMemo(
|
||||
() => !location.ok && location.reason === 'missing_room' && isTrusted(),
|
||||
[location],
|
||||
);
|
||||
const [state, setState] = useState<ViewerState>({ kind: 'connecting', attempt: 0 });
|
||||
const [stream, setStream] = useState<MediaStream | null>(null);
|
||||
const [stats, setStats] = useState<VideoStats | null>(null);
|
||||
const [attemptKey, setAttemptKey] = useState(0);
|
||||
const [isFullscreen, setIsFullscreen] = useState(false);
|
||||
const [theme, setTheme] = useState<Theme>(() => readTheme());
|
||||
const [settingsOpen, setSettingsOpen] = useState(false);
|
||||
const [statsShown, setStatsShown] = useState(() => readStatsShown());
|
||||
const [rotation, setRotation] = useState<Rotation>(() => readRotation());
|
||||
const [mirror, setMirror] = useState(() => readMirror());
|
||||
const [pinned, setPinned] = useState(() => readPinned());
|
||||
const [held, setHeld] = useState(false);
|
||||
const [switched, setSwitched] = useState<SourceInfo | null>(null);
|
||||
const active = useActivity(IDLE_DELAY_MS);
|
||||
const sessionRef = useRef<ViewerSession | null>(null);
|
||||
const containerRef = useRef<HTMLDivElement | null>(null);
|
||||
@@ -45,13 +64,14 @@ export function App() {
|
||||
// mount of StrictMode opens two WebSockets and two negotiations.
|
||||
// biome-ignore lint/correctness/useExhaustiveDependencies: attemptKey is the restart key of the "retry" button, deliberately unused in the body.
|
||||
useEffect(() => {
|
||||
if (!location.ok) return;
|
||||
if (!location.ok && !byKey) return;
|
||||
const session = new ViewerSession({
|
||||
room: location.value.room,
|
||||
token: location.value.token,
|
||||
room: location.ok ? location.value.room : null,
|
||||
token: location.ok ? location.value.token : null,
|
||||
wsUrl: signalingUrl(window.location),
|
||||
onState: setState,
|
||||
onStream: setStream,
|
||||
onSourceChanged: setSwitched,
|
||||
});
|
||||
sessionRef.current = session;
|
||||
session.start();
|
||||
@@ -59,10 +79,10 @@ export function App() {
|
||||
session.stop();
|
||||
sessionRef.current = null;
|
||||
};
|
||||
}, [location, attemptKey]);
|
||||
}, [location, byKey, attemptKey]);
|
||||
|
||||
useEffect(() => {
|
||||
if (state.kind !== 'streaming') {
|
||||
if (state.kind !== 'streaming' || !statsShown) {
|
||||
setStats(null);
|
||||
return;
|
||||
}
|
||||
@@ -76,7 +96,14 @@ export function App() {
|
||||
cancelled = true;
|
||||
clearInterval(timer);
|
||||
};
|
||||
}, [state.kind]);
|
||||
}, [state.kind, statsShown]);
|
||||
|
||||
// The notice of a source switch stays briefly, then goes.
|
||||
useEffect(() => {
|
||||
if (!switched) return;
|
||||
const timer = setTimeout(() => setSwitched(null), SWITCH_NOTICE_MS);
|
||||
return () => clearTimeout(timer);
|
||||
}, [switched]);
|
||||
|
||||
useEffect(() => {
|
||||
const onChange = () => setIsFullscreen(Boolean(document.fullscreenElement));
|
||||
@@ -94,15 +121,13 @@ export function App() {
|
||||
}
|
||||
}, []);
|
||||
|
||||
const cycleTheme = useCallback(() => {
|
||||
setTheme((current) => {
|
||||
const next = nextTheme(current);
|
||||
applyTheme(next);
|
||||
saveTheme(next);
|
||||
return next;
|
||||
});
|
||||
const showStats = useCallback((shown: boolean) => {
|
||||
saveStatsShown(shown);
|
||||
setStatsShown(shown);
|
||||
}, []);
|
||||
|
||||
const rename = useCallback((name: string) => sessionRef.current?.rename(name), []);
|
||||
|
||||
const rotate = useCallback(() => {
|
||||
setRotation((current) => {
|
||||
const next = nextRotation(current);
|
||||
@@ -135,15 +160,18 @@ export function App() {
|
||||
setAttemptKey((key) => key + 1);
|
||||
}, []);
|
||||
|
||||
if (!location.ok) {
|
||||
const untrusted = state.kind === 'failed' && state.code === 'not_trusted';
|
||||
if (!location.ok && (!byKey || untrusted)) {
|
||||
// Without a session in the address, offer the short code (#19). The bare
|
||||
// home page is not an error: it is the way in without a camera.
|
||||
const notice = {
|
||||
missing_room: null,
|
||||
missing_token: t('missingToken'),
|
||||
malformed: t('missingUrl'),
|
||||
newer_link: t('newerLink'),
|
||||
}[location.reason];
|
||||
const notice = untrusted
|
||||
? t('errors.not_trusted')
|
||||
: {
|
||||
missing_room: null,
|
||||
missing_token: t('missingToken'),
|
||||
malformed: t('missingUrl'),
|
||||
newer_link: t('newerLink'),
|
||||
}[location.reason];
|
||||
return <Pairing notice={notice} />;
|
||||
}
|
||||
|
||||
@@ -179,25 +207,12 @@ export function App() {
|
||||
<header className='topbar' {...hold}>
|
||||
<span className='brand'>{t('appName')}</span>
|
||||
<StatusBadge state={state} />
|
||||
{location.value.fingerprint && (
|
||||
<span className='badge' title={`${t('fingerprint')}: ${location.value.fingerprint}`}>
|
||||
{location.value.fingerprint.slice(0, 11)}
|
||||
</span>
|
||||
)}
|
||||
{insecure && (
|
||||
<span className='badge badge-warn' title={t('insecureHint')}>
|
||||
{t('insecureBadge')}
|
||||
</span>
|
||||
)}
|
||||
<button
|
||||
type='button'
|
||||
className='button button-ghost button-theme'
|
||||
onClick={cycleTheme}
|
||||
aria-label={t('themeButton', { current: t(`themes.${theme}`) })}
|
||||
title={t('themeButton', { current: t(`themes.${theme}`) })}
|
||||
>
|
||||
{theme === 'dark' ? '☾' : theme === 'light' ? '☀' : '◐'}
|
||||
</button>
|
||||
<span className='spacer' />
|
||||
{live && (
|
||||
<button
|
||||
type='button'
|
||||
@@ -244,6 +259,16 @@ export function App() {
|
||||
{isFullscreen ? '⤡' : '⤢'}
|
||||
</button>
|
||||
)}
|
||||
<button
|
||||
type='button'
|
||||
className='button button-ghost'
|
||||
onClick={() => setSettingsOpen(true)}
|
||||
aria-haspopup='dialog'
|
||||
aria-label={t('settings')}
|
||||
title={t('settings')}
|
||||
>
|
||||
⚙
|
||||
</button>
|
||||
</header>
|
||||
|
||||
<main className='content'>
|
||||
@@ -254,13 +279,32 @@ export function App() {
|
||||
rotation={rotation}
|
||||
mirror={mirror}
|
||||
/>
|
||||
{switched && (
|
||||
<div className='switch-notice' role='status'>
|
||||
{t('sourceChanged', {
|
||||
kind: t(`sourceKinds.${switched.kind}`),
|
||||
width: switched.width,
|
||||
height: switched.height,
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
{state.kind === 'failed' && <ErrorPanel state={state} onRetry={retry} />}
|
||||
</main>
|
||||
|
||||
<footer className='footer' {...hold}>
|
||||
<StatsBar stats={stats} />
|
||||
<LanguagePicker />
|
||||
</footer>
|
||||
{statsShown && stats && (
|
||||
<footer className='footer' {...hold}>
|
||||
<StatsBar stats={stats} />
|
||||
</footer>
|
||||
)}
|
||||
{settingsOpen && (
|
||||
<SettingsPanel
|
||||
onClose={() => setSettingsOpen(false)}
|
||||
onRename={rename}
|
||||
stats={{ shown: statsShown, onChange: showStats }}
|
||||
fingerprint={location.ok ? location.value.fingerprint : null}
|
||||
trusted={isTrusted()}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
import { useId, useState } from 'react';
|
||||
|
||||
import { useI18n } from '../i18n';
|
||||
import { NAME_MAX, readName, saveName, suggestedName } from '../lib/deviceName';
|
||||
|
||||
type Props = {
|
||||
/** The name changed: the session tells the host. */
|
||||
onRename: (name: string) => void;
|
||||
/** Show the label instead of keeping it for screen readers. */
|
||||
label?: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
* The name of this device, as the host sees it (#36). Kept by the browser;
|
||||
* empty, it goes back to the suggestion. React shows it as text: markup typed
|
||||
* here stays visible as typed.
|
||||
*/
|
||||
export function DeviceName({ onRename, label = false }: Props) {
|
||||
const { t } = useI18n();
|
||||
const id = useId();
|
||||
const suggestion = suggestedName(navigator.userAgent);
|
||||
const [name, setName] = useState(() => readName() ?? '');
|
||||
|
||||
const commit = () => {
|
||||
saveName(name);
|
||||
const kept = readName() ?? '';
|
||||
setName(kept);
|
||||
onRename(kept || suggestion);
|
||||
};
|
||||
|
||||
return (
|
||||
<span className='device-name'>
|
||||
<label htmlFor={id} className={label ? undefined : 'visually-hidden'}>
|
||||
{t('deviceName')}
|
||||
</label>
|
||||
<input
|
||||
id={id}
|
||||
value={name}
|
||||
placeholder={suggestion}
|
||||
maxLength={NAME_MAX}
|
||||
title={t('deviceNameHelp')}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
onBlur={commit}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter') e.currentTarget.blur();
|
||||
}}
|
||||
/>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
@@ -1,27 +0,0 @@
|
||||
import { useId } from 'react';
|
||||
|
||||
import { useI18n } from '../i18n';
|
||||
|
||||
/**
|
||||
* Language picker (#21), among those the host serves. Each one shows in its
|
||||
* own language: whoever cannot read the current language finds their own.
|
||||
*/
|
||||
export function LanguagePicker() {
|
||||
const { t, language, languages, setLanguage } = useI18n();
|
||||
const id = useId();
|
||||
if (languages.length < 2) return null;
|
||||
return (
|
||||
<span className='language'>
|
||||
<label htmlFor={id} className='visually-hidden'>
|
||||
{t('language')}
|
||||
</label>
|
||||
<select id={id} value={language} onChange={(e) => setLanguage(e.target.value)}>
|
||||
{languages.map((l) => (
|
||||
<option key={l.code} value={l.code} lang={l.code}>
|
||||
{l.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
@@ -1,9 +1,8 @@
|
||||
import { type FormEvent, useCallback, useEffect, useRef, useState } from 'react';
|
||||
|
||||
import { exchangeCode, qrDetector } from '../lib/pairing';
|
||||
import { useI18n } from '../i18n';
|
||||
import { exchangeCode, qrDetector } from '../lib/pairing';
|
||||
import { isCompleteCode, normalizeCode, sessionFromScan } from '../lib/room';
|
||||
import { LanguagePicker } from './LanguagePicker';
|
||||
import { SettingsPanel } from './SettingsPanel';
|
||||
|
||||
/** A sample code, in the format the host shows: not a sentence. */
|
||||
const SAMPLE_CODE = 'K7M 4PQ';
|
||||
@@ -24,6 +23,7 @@ export function Pairing({ notice }: Props) {
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [scanning, setScanning] = useState(false);
|
||||
const [canScan] = useState(() => qrDetector() !== null);
|
||||
const [settingsOpen, setSettingsOpen] = useState(false);
|
||||
|
||||
const submit = useCallback(
|
||||
async (event: FormEvent) => {
|
||||
@@ -60,7 +60,19 @@ export function Pairing({ notice }: Props) {
|
||||
return (
|
||||
<div className='app app-centered'>
|
||||
<div className='panel pairing'>
|
||||
<h1>{t('appName')}</h1>
|
||||
<div className='pairing-header'>
|
||||
<h1>{t('appName')}</h1>
|
||||
<button
|
||||
type='button'
|
||||
className='button button-ghost'
|
||||
onClick={() => setSettingsOpen(true)}
|
||||
aria-haspopup='dialog'
|
||||
aria-label={t('settings')}
|
||||
title={t('settings')}
|
||||
>
|
||||
⚙
|
||||
</button>
|
||||
</div>
|
||||
{notice && <p role='alert'>{notice}</p>}
|
||||
<form onSubmit={submit} className='pairing-form'>
|
||||
<label htmlFor='code'>{t('codeLabel')}</label>
|
||||
@@ -93,8 +105,9 @@ export function Pairing({ notice }: Props) {
|
||||
</button>
|
||||
)}
|
||||
{scanning && <Scanner onClose={() => setScanning(false)} onError={setError} />}
|
||||
<LanguagePicker />
|
||||
</div>
|
||||
{/* The name is kept for the first connection; no session to tell yet. */}
|
||||
{settingsOpen && <SettingsPanel onClose={() => setSettingsOpen(false)} onRename={() => {}} />}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,139 @@
|
||||
import { useEffect, useId, useRef, useState } from 'react';
|
||||
|
||||
import { browserLanguage, useI18n } from '../i18n';
|
||||
import { applyTheme, readTheme, saveTheme, THEMES, type Theme } from '../lib/theme';
|
||||
import { DeviceName } from './DeviceName';
|
||||
|
||||
/** Value of the language select that follows the browser. */
|
||||
const BROWSER = '';
|
||||
|
||||
type Props = {
|
||||
onClose: () => void;
|
||||
/** The name changed: the session tells the host. */
|
||||
onRename: (name: string) => void;
|
||||
/** The statistics strip, when there is a stream to measure. */
|
||||
stats?: { shown: boolean; onChange: (shown: boolean) => void };
|
||||
/** Certificate fingerprint from the link, to compare with the host's. */
|
||||
fingerprint?: string | null;
|
||||
/** The host trusts this device (#34). */
|
||||
trusted?: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
* What this device can set (#92), behind the gear of the top bar: the page
|
||||
* itself only shows the shared screen. Every choice is kept by the browser.
|
||||
*/
|
||||
export function SettingsPanel({ onClose, onRename, stats, fingerprint, trusted }: Props) {
|
||||
const { t, languages, chosen, setLanguage } = useI18n();
|
||||
const id = useId();
|
||||
const [theme, setTheme] = useState<Theme>(() => readTheme());
|
||||
const dialog = useRef<HTMLDivElement | null>(null);
|
||||
|
||||
// The focus enters the panel, and goes back where it was when it closes.
|
||||
useEffect(() => {
|
||||
const previous = document.activeElement as HTMLElement | null;
|
||||
dialog.current?.querySelector<HTMLElement>('input, select, button')?.focus();
|
||||
return () => previous?.focus?.();
|
||||
}, []);
|
||||
|
||||
const changeTheme = (next: Theme) => {
|
||||
applyTheme(next);
|
||||
saveTheme(next);
|
||||
setTheme(next);
|
||||
};
|
||||
const browser = languages.find((l) => l.code === browserLanguage(languages));
|
||||
|
||||
return (
|
||||
<div
|
||||
className='overlay'
|
||||
onPointerDown={(e) => {
|
||||
if (e.target === e.currentTarget) onClose();
|
||||
}}
|
||||
>
|
||||
<div
|
||||
ref={dialog}
|
||||
className='settings-panel'
|
||||
role='dialog'
|
||||
aria-modal='true'
|
||||
aria-labelledby={`${id}-title`}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Escape') onClose();
|
||||
}}
|
||||
>
|
||||
<div className='settings-header'>
|
||||
<h2 id={`${id}-title`}>{t('settings')}</h2>
|
||||
<button type='button' className='button button-ghost' onClick={onClose}>
|
||||
{t('close')}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className='settings-field'>
|
||||
<DeviceName onRename={onRename} label />
|
||||
<span className='settings-help'>{t('deviceNameHelp')}</span>
|
||||
</div>
|
||||
|
||||
{languages.length > 1 && (
|
||||
<div className='settings-field'>
|
||||
<label htmlFor={`${id}-language`}>{t('language')}</label>
|
||||
<select
|
||||
id={`${id}-language`}
|
||||
value={chosen ?? BROWSER}
|
||||
onChange={(e) => setLanguage(e.target.value === BROWSER ? null : e.target.value)}
|
||||
>
|
||||
<option value={BROWSER}>{t('languageBrowser', { name: browser?.name ?? '' })}</option>
|
||||
{/* Each language in its own: whoever cannot read the current one finds theirs. */}
|
||||
{languages.map((l) => (
|
||||
<option key={l.code} value={l.code} lang={l.code}>
|
||||
{l.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className='settings-field'>
|
||||
<label htmlFor={`${id}-theme`}>{t('theme')}</label>
|
||||
<select
|
||||
id={`${id}-theme`}
|
||||
value={theme}
|
||||
onChange={(e) => changeTheme(e.target.value as Theme)}
|
||||
>
|
||||
{THEMES.map((th) => (
|
||||
<option key={th} value={th}>
|
||||
{t(`themes.${th}`)}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
{stats && (
|
||||
<label className='settings-check'>
|
||||
<input
|
||||
type='checkbox'
|
||||
checked={stats.shown}
|
||||
onChange={(e) => stats.onChange(e.target.checked)}
|
||||
/>
|
||||
{t('showStats')}
|
||||
</label>
|
||||
)}
|
||||
|
||||
{(fingerprint || trusted) && (
|
||||
<dl className='settings-info'>
|
||||
{trusted && (
|
||||
<div>
|
||||
<dt>{t('trustedBadge')}</dt>
|
||||
<dd>{t('trustedHint')}</dd>
|
||||
</div>
|
||||
)}
|
||||
{fingerprint && (
|
||||
<div>
|
||||
<dt>{t('fingerprint')}</dt>
|
||||
<dd className='mono'>{fingerprint}</dd>
|
||||
</div>
|
||||
)}
|
||||
</dl>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
|
||||
import { probeRequested, startProbe } from '../lib/perfProbe';
|
||||
import { type Rotation, rotatedBox } from '../lib/rotation';
|
||||
|
||||
type Props = {
|
||||
@@ -33,6 +34,13 @@ export function VideoStage({ stream, live, label, rotation, mirror }: Props) {
|
||||
}
|
||||
}, [stream]);
|
||||
|
||||
// Latency probe for the bench (#86), only when the URL asks for it.
|
||||
useEffect(() => {
|
||||
const video = videoRef.current;
|
||||
if (!video || !probeRequested(window.location.search)) return;
|
||||
return startProbe(video);
|
||||
}, []);
|
||||
|
||||
// The turned box depends on the stage size: full screen, switching to
|
||||
// portrait, the virtual keyboard all change it.
|
||||
useEffect(() => {
|
||||
|
||||
+43
-17
@@ -24,7 +24,10 @@ type Context = {
|
||||
t: Translate;
|
||||
language: string;
|
||||
languages: AvailableLanguage[];
|
||||
setLanguage: (code: string) => void;
|
||||
/** The language this device chose, `null` when it follows the browser. */
|
||||
chosen: string | null;
|
||||
/** A language served by the host, or `null` to follow the browser (#92). */
|
||||
setLanguage: (code: string | null) => void;
|
||||
};
|
||||
|
||||
const I18n = createContext<Context | null>(null);
|
||||
@@ -47,26 +50,33 @@ export function I18nProvider({
|
||||
children: ReactNode;
|
||||
}) {
|
||||
const [loaded, setLoaded] = useState(initial);
|
||||
const [chosen, setChosen] = useState(() => chosenLanguage(languages));
|
||||
|
||||
const setLanguage = useCallback((code: string) => {
|
||||
saveLanguage(code);
|
||||
// The change takes effect on the next render: no reload, the session
|
||||
// and the stream go on.
|
||||
void loadCatalogs(code).then((catalogs) => {
|
||||
if (catalogs.length === 0) return;
|
||||
document.documentElement.lang = code;
|
||||
setLoaded({ language: code, catalogs });
|
||||
});
|
||||
}, []);
|
||||
const setLanguage = useCallback(
|
||||
(choice: string | null) => {
|
||||
saveLanguage(choice);
|
||||
setChosen(choice);
|
||||
const code = choice ?? browserLanguage(languages);
|
||||
// The change takes effect on the next render: no reload, the session
|
||||
// and the stream go on.
|
||||
void loadCatalogs(code).then((catalogs) => {
|
||||
if (catalogs.length === 0) return;
|
||||
document.documentElement.lang = code;
|
||||
setLoaded({ language: code, catalogs });
|
||||
});
|
||||
},
|
||||
[languages],
|
||||
);
|
||||
|
||||
const value = useMemo(
|
||||
() => ({
|
||||
t: createTranslator(loaded.language, 'viewer', loaded.catalogs),
|
||||
language: loaded.language,
|
||||
languages,
|
||||
chosen,
|
||||
setLanguage,
|
||||
}),
|
||||
[loaded, languages, setLanguage],
|
||||
[loaded, languages, chosen, setLanguage],
|
||||
);
|
||||
return <I18n.Provider value={value}>{children}</I18n.Provider>;
|
||||
}
|
||||
@@ -100,10 +110,21 @@ export async function loadCatalogs(code: string): Promise<Catalog[]> {
|
||||
|
||||
/** The choice kept by the device, otherwise the browser language. */
|
||||
export function initialLanguage(available: AvailableLanguage[]): string {
|
||||
const codes = available.map((l) => l.code);
|
||||
return chosenLanguage(available) ?? browserLanguage(available);
|
||||
}
|
||||
|
||||
/** The language of the browser, among those the host serves. */
|
||||
export function browserLanguage(available: AvailableLanguage[]): string {
|
||||
return pickLanguage(
|
||||
navigator.languages ?? [navigator.language],
|
||||
available.map((l) => l.code),
|
||||
);
|
||||
}
|
||||
|
||||
/** The language this device chose, if the host still serves it. */
|
||||
function chosenLanguage(available: AvailableLanguage[]): string | null {
|
||||
const saved = readLanguage();
|
||||
if (saved && codes.includes(saved)) return saved;
|
||||
return pickLanguage(navigator.languages ?? [navigator.language], codes);
|
||||
return saved && available.some((l) => l.code === saved) ? saved : null;
|
||||
}
|
||||
|
||||
function readLanguage(): string | null {
|
||||
@@ -115,9 +136,14 @@ function readLanguage(): string | null {
|
||||
}
|
||||
}
|
||||
|
||||
function saveLanguage(code: string): void {
|
||||
function saveLanguage(code: string | null): void {
|
||||
try {
|
||||
window.localStorage.setItem(KEY, code);
|
||||
if (code === null) {
|
||||
window.localStorage.removeItem(KEY);
|
||||
window.localStorage.removeItem(LEGACY_KEY);
|
||||
} else {
|
||||
window.localStorage.setItem(KEY, code);
|
||||
}
|
||||
} catch {
|
||||
// Private browsing: the choice holds for the page only.
|
||||
}
|
||||
|
||||
@@ -0,0 +1,159 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import { ViewerSession, type ViewerState } from './session';
|
||||
import { fromSecret, isTrusted, rememberTrust } from './trust';
|
||||
|
||||
/** WebSocket that opens, records what is sent, and lets the test answer. */
|
||||
class ScriptedWebSocket {
|
||||
static readonly OPEN = 1;
|
||||
static readonly CLOSING = 2;
|
||||
static readonly CLOSED = 3;
|
||||
static last: ScriptedWebSocket | null = null;
|
||||
|
||||
readyState = 0;
|
||||
sent: Array<Record<string, unknown>> = [];
|
||||
private listeners = new Map<string, Array<(event: unknown) => void>>();
|
||||
|
||||
constructor(public readonly url: string) {
|
||||
ScriptedWebSocket.last = this;
|
||||
queueMicrotask(() => {
|
||||
this.readyState = ScriptedWebSocket.OPEN;
|
||||
this.emit('open', {});
|
||||
});
|
||||
}
|
||||
|
||||
addEventListener(type: string, listener: (event: unknown) => void): void {
|
||||
const list = this.listeners.get(type) ?? [];
|
||||
list.push(listener);
|
||||
this.listeners.set(type, list);
|
||||
}
|
||||
|
||||
send(data: string): void {
|
||||
this.sent.push(JSON.parse(data));
|
||||
}
|
||||
|
||||
close(): void {
|
||||
this.readyState = ScriptedWebSocket.CLOSED;
|
||||
}
|
||||
|
||||
answer(message: Record<string, unknown>): void {
|
||||
this.emit('message', { data: JSON.stringify(message) });
|
||||
}
|
||||
|
||||
private emit(type: string, event: unknown): void {
|
||||
for (const listener of this.listeners.get(type) ?? []) listener(event);
|
||||
}
|
||||
}
|
||||
|
||||
class StubPeerConnection {
|
||||
close(): void {}
|
||||
}
|
||||
|
||||
const SECRET = '9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60';
|
||||
const NONCE = '000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f';
|
||||
|
||||
function memoryStorage() {
|
||||
const map = new Map<string, string>();
|
||||
return {
|
||||
getItem: (k: string) => map.get(k) ?? null,
|
||||
setItem: (k: string, v: string) => void map.set(k, v),
|
||||
removeItem: (k: string) => void map.delete(k),
|
||||
};
|
||||
}
|
||||
|
||||
describe('coming back by key (#34)', () => {
|
||||
let storage: ReturnType<typeof memoryStorage>;
|
||||
|
||||
beforeEach(() => {
|
||||
storage = memoryStorage();
|
||||
vi.stubGlobal('WebSocket', ScriptedWebSocket);
|
||||
vi.stubGlobal('RTCPeerConnection', StubPeerConnection);
|
||||
vi.stubGlobal('window', { localStorage: storage });
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
function session(states: ViewerState[]) {
|
||||
return new ViewerSession({
|
||||
room: null,
|
||||
token: null,
|
||||
key: fromSecret(SECRET),
|
||||
wsUrl: 'ws://127.0.0.1:1/ws',
|
||||
watchLifecycle: false,
|
||||
onState: (state) => states.push(state),
|
||||
onStream: () => undefined,
|
||||
});
|
||||
}
|
||||
|
||||
it('announces its public key without a link, then signs the challenge', async () => {
|
||||
const viewer = session([]);
|
||||
viewer.start();
|
||||
await Promise.resolve();
|
||||
const ws = ScriptedWebSocket.last;
|
||||
expect(ws?.sent[0]).toMatchObject({
|
||||
type: 'hello',
|
||||
room: null,
|
||||
token: null,
|
||||
key: fromSecret(SECRET).publicKey,
|
||||
});
|
||||
ws?.answer({ type: 'challenge', nonce: NONCE });
|
||||
await Promise.resolve();
|
||||
expect(ws?.sent[1]).toEqual({ type: 'proof', signature: fromSecret(SECRET).sign(NONCE) });
|
||||
viewer.stop();
|
||||
});
|
||||
|
||||
it('forgets the trust when the host refuses the key', async () => {
|
||||
rememberTrust(true, storage);
|
||||
const states: ViewerState[] = [];
|
||||
const viewer = session(states);
|
||||
viewer.start();
|
||||
await Promise.resolve();
|
||||
ScriptedWebSocket.last?.answer({ type: 'error', code: 'not_trusted', message: '' });
|
||||
await Promise.resolve();
|
||||
expect(isTrusted(storage)).toBe(false);
|
||||
expect(states.at(-1)).toEqual({ kind: 'failed', code: 'not_trusted' });
|
||||
});
|
||||
});
|
||||
|
||||
describe('source switch (#26)', () => {
|
||||
beforeEach(() => {
|
||||
vi.stubGlobal('WebSocket', ScriptedWebSocket);
|
||||
vi.stubGlobal('RTCPeerConnection', StubPeerConnection);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
it('reports the new source without leaving the session', async () => {
|
||||
const states: ViewerState[] = [];
|
||||
const switched: unknown[] = [];
|
||||
const viewer = new ViewerSession({
|
||||
room: 'abc234',
|
||||
token: '0123456789abcdef0123456789abcdef',
|
||||
key: null,
|
||||
wsUrl: 'ws://127.0.0.1:1/ws',
|
||||
watchLifecycle: false,
|
||||
onState: (state) => states.push(state),
|
||||
onStream: () => undefined,
|
||||
onSourceChanged: (source) => switched.push(source),
|
||||
});
|
||||
viewer.start();
|
||||
await Promise.resolve();
|
||||
const source = {
|
||||
id: 'x11',
|
||||
kind: 'window',
|
||||
name: '',
|
||||
width: 800,
|
||||
height: 600,
|
||||
available: true,
|
||||
};
|
||||
ScriptedWebSocket.last?.answer({ type: 'source_changed', source });
|
||||
await Promise.resolve();
|
||||
expect(switched).toEqual([source]);
|
||||
expect(states.some((s) => s.kind === 'failed' || s.kind === 'reconnecting')).toBe(false);
|
||||
viewer.stop();
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,13 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
import { barsVisible, isCompact, readPinned, savePinned } from './controls';
|
||||
import {
|
||||
barsVisible,
|
||||
isCompact,
|
||||
readPinned,
|
||||
readStatsShown,
|
||||
savePinned,
|
||||
saveStatsShown,
|
||||
} from './controls';
|
||||
|
||||
describe('bars that fade out (#31, #81)', () => {
|
||||
const base = { compact: true, live: true, active: false, held: false };
|
||||
@@ -49,4 +56,12 @@ describe('pinned controls', () => {
|
||||
expect(storage.values.get('rustscreen.pinned-controls')).toBe('1');
|
||||
expect(storage.values.has('rustscreen.controles-epingles')).toBe(false);
|
||||
});
|
||||
|
||||
it('statistics are hidden until asked for, then kept (#92)', () => {
|
||||
const storage = memory();
|
||||
expect(readStatsShown(storage)).toBe(false);
|
||||
saveStatsShown(true, storage);
|
||||
expect(readStatsShown(storage)).toBe(true);
|
||||
expect(readStatsShown(null)).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -53,3 +53,25 @@ export function savePinned(
|
||||
// Private browsing: the choice holds for the page only.
|
||||
}
|
||||
}
|
||||
|
||||
/** Show the statistics strip (#92): off by default, the picture comes first. */
|
||||
const STATS_KEY = 'rustscreen.show-stats';
|
||||
|
||||
export function readStatsShown(storage: KeyValueStore | null = browserStorage()): boolean {
|
||||
try {
|
||||
return storage?.getItem(STATS_KEY) === '1';
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export function saveStatsShown(
|
||||
shown: boolean,
|
||||
storage: KeyValueStore | null = browserStorage(),
|
||||
): void {
|
||||
try {
|
||||
storage?.setItem(STATS_KEY, shown ? '1' : '0');
|
||||
} catch {
|
||||
// Private browsing: the choice holds for the page only.
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
import { cleanName, NAME_MAX, readName, saveName, suggestedName } from './deviceName';
|
||||
|
||||
function memory() {
|
||||
const map = new Map<string, string>();
|
||||
return {
|
||||
getItem: (k: string) => map.get(k) ?? null,
|
||||
setItem: (k: string, v: string) => void map.set(k, v),
|
||||
removeItem: (k: string) => void map.delete(k),
|
||||
};
|
||||
}
|
||||
|
||||
describe('device name (#36)', () => {
|
||||
it('is cleaned like the host does, markup kept as text', () => {
|
||||
expect(cleanName(' iPad\tdu\n salon ')).toBe('iPad du salon');
|
||||
expect(cleanName('<b>Kitchen</b>')).toBe('<b>Kitchen</b>');
|
||||
expect(cleanName('é'.repeat(60))).toHaveLength(NAME_MAX);
|
||||
});
|
||||
|
||||
it('is suggested from the device and the browser', () => {
|
||||
const ipad =
|
||||
'Mozilla/5.0 (iPad; CPU OS 17_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 Mobile/15E148 Safari/604.1';
|
||||
expect(suggestedName(ipad)).toBe('iPad Safari');
|
||||
const pixel =
|
||||
'Mozilla/5.0 (Linux; Android 14; Pixel 8) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0 Mobile Safari/537.36';
|
||||
expect(suggestedName(pixel)).toBe('Android Chrome');
|
||||
expect(
|
||||
suggestedName('Mozilla/5.0 (X11; Linux x86_64; rv:120.0) Gecko/20100101 Firefox/120.0'),
|
||||
).toBe('Linux Firefox');
|
||||
});
|
||||
|
||||
it('is kept, and an empty one goes back to the suggestion', () => {
|
||||
const storage = memory();
|
||||
expect(readName(storage)).toBeNull();
|
||||
saveName(' Salon ', storage);
|
||||
expect(readName(storage)).toBe('Salon');
|
||||
saveName(' ', storage);
|
||||
expect(readName(storage)).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,78 @@
|
||||
/**
|
||||
* The name this device gives itself (#36): chosen by the user, kept by the
|
||||
* browser, suggested from the device and the browser until then.
|
||||
*
|
||||
* The host may give its own name to the device (#37): that one shows on the
|
||||
* host side, this one stays the device's choice. The name is text: the host
|
||||
* cleans it the same way (`rs_proto::clean_name`), and every interface shows
|
||||
* markup literally.
|
||||
*/
|
||||
import { browserStorage, type KeyValueStore } from './storage';
|
||||
|
||||
const KEY = 'rustscreen.name';
|
||||
/** `rs_proto::DEVICE_NAME_MAX`. */
|
||||
export const NAME_MAX = 40;
|
||||
|
||||
/** Same rule as the host: control characters out, spaces collapsed, 40 at most. */
|
||||
export function cleanName(raw: string): string {
|
||||
return Array.from(
|
||||
raw
|
||||
// biome-ignore lint/suspicious/noControlCharactersInRegex: removing them is the point.
|
||||
.split(/[\s\u0000-\u001f\u007f-\u009f]+/)
|
||||
.filter(Boolean)
|
||||
.join(' '),
|
||||
)
|
||||
.slice(0, NAME_MAX)
|
||||
.join('')
|
||||
.trimEnd();
|
||||
}
|
||||
|
||||
/** A name from the device and the browser: proper nouns, readable in any language. */
|
||||
export function suggestedName(userAgent: string): string {
|
||||
const device = /iPad/.test(userAgent)
|
||||
? 'iPad'
|
||||
: /iPhone/.test(userAgent)
|
||||
? 'iPhone'
|
||||
: /Android/.test(userAgent)
|
||||
? 'Android'
|
||||
: /CrOS/.test(userAgent)
|
||||
? 'Chromebook'
|
||||
: /Mac OS X|Macintosh/.test(userAgent)
|
||||
? 'Mac'
|
||||
: /Windows/.test(userAgent)
|
||||
? 'Windows'
|
||||
: /Linux/.test(userAgent)
|
||||
? 'Linux'
|
||||
: '';
|
||||
const browser = /Edg\//.test(userAgent)
|
||||
? 'Edge'
|
||||
: /Firefox\//.test(userAgent)
|
||||
? 'Firefox'
|
||||
: /Chrome\//.test(userAgent)
|
||||
? 'Chrome'
|
||||
: /Safari\//.test(userAgent)
|
||||
? 'Safari'
|
||||
: '';
|
||||
return [device, browser].filter(Boolean).join(' ');
|
||||
}
|
||||
|
||||
/** The name the user chose, `null` if none. */
|
||||
export function readName(storage: KeyValueStore | null = browserStorage()): string | null {
|
||||
try {
|
||||
const name = cleanName(storage?.getItem(KEY) ?? '');
|
||||
return name || null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** Keeps the chosen name; an empty one goes back to the suggestion. */
|
||||
export function saveName(name: string, storage: KeyValueStore | null = browserStorage()): void {
|
||||
try {
|
||||
const clean = cleanName(name);
|
||||
if (clean) storage?.setItem(KEY, clean);
|
||||
else storage?.removeItem(KEY);
|
||||
} catch {
|
||||
// Private browsing: the name holds for this page only.
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
import { readStamp, STAMP_BITS, STAMP_BLOCK, STAMP_MARGIN, summarize } from './perfProbe';
|
||||
|
||||
function stripFor(millis: number): { rgba: Uint8ClampedArray; width: number } {
|
||||
const width = STAMP_MARGIN * 2 + STAMP_BITS * STAMP_BLOCK;
|
||||
const height = STAMP_MARGIN * 2 + 2 * STAMP_BLOCK;
|
||||
const rgba = new Uint8ClampedArray(width * height * 4);
|
||||
const paint = (bit: number, line: number, on: boolean) => {
|
||||
const y0 = STAMP_MARGIN + line * STAMP_BLOCK;
|
||||
const x0 = STAMP_MARGIN + bit * STAMP_BLOCK;
|
||||
for (let y = y0; y < y0 + STAMP_BLOCK; y++) {
|
||||
for (let x = x0; x < x0 + STAMP_BLOCK; x++) {
|
||||
rgba.fill(on ? 250 : 5, (y * width + x) * 4, (y * width + x) * 4 + 3);
|
||||
}
|
||||
}
|
||||
};
|
||||
for (let bit = 0; bit < STAMP_BITS; bit++) {
|
||||
const set = Math.floor(millis / 2 ** (STAMP_BITS - 1 - bit)) % 2 === 1;
|
||||
// Row 0: the bit; row 1: its complement, as the test pattern draws it.
|
||||
paint(bit, 0, set);
|
||||
paint(bit, 1, !set);
|
||||
}
|
||||
return { rgba, width };
|
||||
}
|
||||
|
||||
describe('latency probe (#86)', () => {
|
||||
it('reads back the capture instant written by the test pattern', () => {
|
||||
const millis = 1_793_034_067_276;
|
||||
const { rgba, width } = stripFor(millis);
|
||||
expect(readStamp(rgba, width)).toBe(millis);
|
||||
});
|
||||
|
||||
it('rejects a stamp blurred by compression instead of misreading it', () => {
|
||||
const { rgba, width } = stripFor(1_793_034_067_276);
|
||||
// Bit 11 (2048 ms) turns gray on its first row.
|
||||
const x = STAMP_MARGIN + 36 * STAMP_BLOCK + STAMP_BLOCK / 2;
|
||||
const y = STAMP_MARGIN + STAMP_BLOCK / 2;
|
||||
rgba.fill(128, (y * width + x) * 4, (y * width + x) * 4 + 3);
|
||||
expect(readStamp(rgba, width)).toBeNull();
|
||||
});
|
||||
|
||||
it('summarizes latency percentiles and displayed frames per second', () => {
|
||||
const times = Array.from({ length: 120 }, (_, i) => i * (1000 / 60));
|
||||
const summary = summarize([10, 20, 30, 40, 100], times, 2, 120, { width: 1920, height: 1080 });
|
||||
expect(summary.latencyMs).toEqual({ median: 30, p95: 100, max: 100 });
|
||||
expect(summary.fps).toBe(60);
|
||||
expect(summary.skipped).toBe(2);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,155 @@
|
||||
/**
|
||||
* Latency probe (#86), enabled with `?perf=1` in the session URL.
|
||||
*
|
||||
* The synthetic test pattern writes its capture instant (Unix milliseconds)
|
||||
* as a row of black and white blocks. For every displayed frame
|
||||
* (`requestVideoFrameCallback`), the probe reads that row back and measures
|
||||
* the end-to-end latency: capture, conversion, encoding, network, decoding
|
||||
* and display, on one clock when host and viewer share a machine. It also
|
||||
* counts displayed frames per second and skipped frames.
|
||||
*
|
||||
* The results are exposed on `window.__rustscreenPerf` for the bench script;
|
||||
* nothing is shown to the user.
|
||||
*/
|
||||
|
||||
/** Layout of the stamp, in step with `rs-capture/src/synthetic.rs`. */
|
||||
export const STAMP_BITS = 48;
|
||||
export const STAMP_BLOCK = 16;
|
||||
export const STAMP_MARGIN = 8;
|
||||
|
||||
/**
|
||||
* Reads the stamp from RGBA pixels of the top-left strip, `width` wide. The
|
||||
* second row holds the complement: a bit blurred by compression on either
|
||||
* row makes the whole stamp unreadable rather than wrong.
|
||||
*/
|
||||
export function readStamp(rgba: Uint8ClampedArray, width: number): number | null {
|
||||
let millis = 0;
|
||||
for (let bit = 0; bit < STAMP_BITS; bit++) {
|
||||
const x = STAMP_MARGIN + bit * STAMP_BLOCK + STAMP_BLOCK / 2;
|
||||
const at = (line: number) =>
|
||||
rgba[((STAMP_MARGIN + line * STAMP_BLOCK + STAMP_BLOCK / 2) * width + x) * 4 + 1];
|
||||
const value = at(0);
|
||||
const complement = at(1);
|
||||
if (value === undefined || complement === undefined) return null;
|
||||
if (Math.abs(value - complement) < 128) return null;
|
||||
millis = millis * 2 + (value > complement ? 1 : 0);
|
||||
}
|
||||
return millis;
|
||||
}
|
||||
|
||||
export type PerfSummary = {
|
||||
frames: number;
|
||||
/** Displayed frames per second over the last second. */
|
||||
fps: number;
|
||||
/** Frames the compositor never showed (`presentedFrames` gaps). */
|
||||
skipped: number;
|
||||
latencyMs: { median: number; p95: number; max: number } | null;
|
||||
width: number;
|
||||
height: number;
|
||||
};
|
||||
|
||||
const STAMP_MODULO = 2 ** STAMP_BITS;
|
||||
|
||||
export function summarize(
|
||||
latencies: number[],
|
||||
presentTimes: number[],
|
||||
skipped: number,
|
||||
frames: number,
|
||||
size: { width: number; height: number },
|
||||
): PerfSummary {
|
||||
const sorted = [...latencies].sort((a, b) => a - b);
|
||||
const pick = (q: number) =>
|
||||
sorted[Math.min(sorted.length - 1, Math.floor(q * sorted.length))] ?? 0;
|
||||
const last = presentTimes.at(-1) ?? 0;
|
||||
const fps = presentTimes.filter((t) => last - t < 1000).length;
|
||||
return {
|
||||
frames,
|
||||
fps,
|
||||
skipped,
|
||||
latencyMs: sorted.length
|
||||
? { median: pick(0.5), p95: pick(0.95), max: sorted.at(-1) ?? 0 }
|
||||
: null,
|
||||
width: size.width,
|
||||
height: size.height,
|
||||
};
|
||||
}
|
||||
|
||||
type FrameCallbackVideo = HTMLVideoElement & {
|
||||
requestVideoFrameCallback?: (
|
||||
callback: (
|
||||
now: number,
|
||||
metadata: { presentedFrames: number; expectedDisplayTime: number },
|
||||
) => void,
|
||||
) => number;
|
||||
cancelVideoFrameCallback?: (handle: number) => void;
|
||||
};
|
||||
|
||||
/** Starts the probe on `video`; returns the function that stops it. */
|
||||
export function startProbe(video: HTMLVideoElement): () => void {
|
||||
const target = video as FrameCallbackVideo;
|
||||
if (!target.requestVideoFrameCallback) return () => undefined;
|
||||
const canvas = document.createElement('canvas');
|
||||
const width = STAMP_MARGIN * 2 + STAMP_BITS * STAMP_BLOCK;
|
||||
const height = STAMP_MARGIN * 2 + 2 * STAMP_BLOCK;
|
||||
canvas.width = width;
|
||||
canvas.height = height;
|
||||
const context = canvas.getContext('2d', { willReadFrequently: true });
|
||||
const latencies: number[] = [];
|
||||
const presentTimes: number[] = [];
|
||||
let skipped = 0;
|
||||
let frames = 0;
|
||||
let lastPresented: number | null = null;
|
||||
let handle = 0;
|
||||
let stopped = false;
|
||||
|
||||
const onFrame = (
|
||||
_now: number,
|
||||
metadata: { presentedFrames: number; expectedDisplayTime: number },
|
||||
) => {
|
||||
if (stopped) return;
|
||||
frames++;
|
||||
if (lastPresented !== null && metadata.presentedFrames > lastPresented + 1) {
|
||||
skipped += metadata.presentedFrames - lastPresented - 1;
|
||||
}
|
||||
lastPresented = metadata.presentedFrames;
|
||||
presentTimes.push(metadata.expectedDisplayTime);
|
||||
if (presentTimes.length > 600) presentTimes.shift();
|
||||
if (context && video.videoWidth >= width) {
|
||||
context.drawImage(video, 0, 0, width, height, 0, 0, width, height);
|
||||
const stamp = readStamp(context.getImageData(0, 0, width, height).data, width);
|
||||
if (stamp !== null) {
|
||||
const shown = (performance.timeOrigin + metadata.expectedDisplayTime) % STAMP_MODULO;
|
||||
const latency = shown - stamp;
|
||||
if (latency > -50 && latency < 5000) {
|
||||
latencies.push(Math.max(0, latency));
|
||||
if (latencies.length > 3000) latencies.shift();
|
||||
}
|
||||
}
|
||||
}
|
||||
handle = target.requestVideoFrameCallback?.(onFrame) ?? 0;
|
||||
};
|
||||
handle = target.requestVideoFrameCallback(onFrame);
|
||||
|
||||
(window as unknown as { __rustscreenPerf?: unknown }).__rustscreenPerf = {
|
||||
summary: () =>
|
||||
summarize(latencies, presentTimes, skipped, frames, {
|
||||
width: video.videoWidth,
|
||||
height: video.videoHeight,
|
||||
}),
|
||||
reset: () => {
|
||||
latencies.length = 0;
|
||||
presentTimes.length = 0;
|
||||
skipped = 0;
|
||||
frames = 0;
|
||||
},
|
||||
};
|
||||
return () => {
|
||||
stopped = true;
|
||||
target.cancelVideoFrameCallback?.(handle);
|
||||
};
|
||||
}
|
||||
|
||||
/** The probe runs only when the URL asks for it. */
|
||||
export function probeRequested(search: string): boolean {
|
||||
return new URLSearchParams(search).get('perf') === '1';
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
import { createTranslator } from './i18n';
|
||||
import { backoffDelay, isRetryable, isTerminal, messageFor } from './session';
|
||||
import { backoffDelay, isRetryable, isTerminal, messageFor, minimizeJitterBuffer } from './session';
|
||||
|
||||
describe('backoffDelay', () => {
|
||||
it('doubles at each attempt then caps', () => {
|
||||
@@ -69,3 +69,15 @@ describe('messageFor', () => {
|
||||
expect(messageFor('something_new', t)).toBe('Connexion perdue.');
|
||||
});
|
||||
});
|
||||
|
||||
describe('minimizeJitterBuffer (#86)', () => {
|
||||
it('sets the standard target when the browser has it, the older hint otherwise', () => {
|
||||
const standard = { jitterBufferTarget: null } as unknown as RTCRtpReceiver;
|
||||
minimizeJitterBuffer(standard);
|
||||
expect((standard as unknown as { jitterBufferTarget: number }).jitterBufferTarget).toBe(0);
|
||||
const older = { playoutDelayHint: null } as unknown as RTCRtpReceiver;
|
||||
minimizeJitterBuffer(older);
|
||||
expect((older as unknown as { playoutDelayHint: number }).playoutDelayHint).toBe(0);
|
||||
expect(() => minimizeJitterBuffer({} as RTCRtpReceiver)).not.toThrow();
|
||||
});
|
||||
});
|
||||
@@ -7,21 +7,33 @@
|
||||
* testable and avoids inconsistent states such as "connected without picture".
|
||||
*/
|
||||
|
||||
import type {
|
||||
ClientMessage,
|
||||
DeviceInfo,
|
||||
ServerMessage,
|
||||
SourceInfo,
|
||||
StreamSettings,
|
||||
} from '../proto';
|
||||
import { PROTOCOL_VERSION } from '../proto';
|
||||
import type { ClientMessage, DeviceInfo, ServerMessage, StreamSettings } from '../proto';
|
||||
import type { Translate } from './i18n';
|
||||
import { deviceId } from './device';
|
||||
import { cleanName, readName, suggestedName } from './deviceName';
|
||||
import type { Translate } from './i18n';
|
||||
import { type WakeReason, watchLifecycle } from './lifecycle';
|
||||
import { type DeviceKey, deviceKey, rememberTrust } from './trust';
|
||||
|
||||
export type ViewerErrorCode =
|
||||
| 'bad_token'
|
||||
| 'token_expired'
|
||||
/** The link was valid but another device used it first (#35). */
|
||||
| 'token_used'
|
||||
| 'bad_version'
|
||||
| 'room_full'
|
||||
| 'protocol_violation'
|
||||
| 'internal'
|
||||
| 'kicked'
|
||||
| 'share_ended'
|
||||
/** Came back by its key, and the host does not (or no longer) trust it (#34). */
|
||||
| 'not_trusted'
|
||||
| 'network'
|
||||
| 'unsupported';
|
||||
|
||||
@@ -34,8 +46,11 @@ export type ViewerState =
|
||||
| { kind: 'ended'; reason: string };
|
||||
|
||||
export type SessionOptions = {
|
||||
room: string;
|
||||
token: string;
|
||||
/** The link's room and token; both `null` for a trusted device without a link (#34). */
|
||||
room: string | null;
|
||||
token: string | null;
|
||||
/** Key of this device; by default the one kept by the browser, drawn if needed. */
|
||||
key?: DeviceKey | null;
|
||||
wsUrl: string;
|
||||
deviceName?: string;
|
||||
maxAttempts?: number;
|
||||
@@ -48,16 +63,20 @@ export type SessionOptions = {
|
||||
watchLifecycle?: boolean;
|
||||
onState: (state: ViewerState) => void;
|
||||
onStream: (stream: MediaStream | null) => void;
|
||||
/** The host switched source during the share (#26): the stream stays. */
|
||||
onSourceChanged?: (source: SourceInfo) => void;
|
||||
};
|
||||
|
||||
/** Codes after which retrying is useless: the host refuses on principle. */
|
||||
const TERMINAL_CODES: ReadonlySet<string> = new Set([
|
||||
'bad_token',
|
||||
'token_expired',
|
||||
'token_used',
|
||||
'bad_version',
|
||||
'room_full',
|
||||
'kicked',
|
||||
'share_ended',
|
||||
'not_trusted',
|
||||
]);
|
||||
|
||||
/**
|
||||
@@ -105,6 +124,7 @@ export class ViewerSession {
|
||||
private pc: RTCPeerConnection | null = null;
|
||||
private retryTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
private attempt = 0;
|
||||
private readonly key: DeviceKey | null;
|
||||
/** Final stop: unmount, refusal on principle, end of session. */
|
||||
private stopped = false;
|
||||
/**
|
||||
@@ -122,6 +142,7 @@ export class ViewerSession {
|
||||
constructor(private readonly options: SessionOptions) {
|
||||
this.maxAttempts = options.maxAttempts ?? DEFAULT_MAX_ATTEMPTS;
|
||||
this.quality = options.quality ?? null;
|
||||
this.key = options.key === undefined ? deviceKey() : options.key;
|
||||
}
|
||||
|
||||
start(): void {
|
||||
@@ -285,6 +306,7 @@ export class ViewerSession {
|
||||
room: this.options.room,
|
||||
token: this.options.token,
|
||||
device,
|
||||
key: this.key?.publicKey ?? null,
|
||||
} as ClientMessage;
|
||||
}
|
||||
|
||||
@@ -299,7 +321,21 @@ export class ViewerSession {
|
||||
}
|
||||
|
||||
switch (message.type) {
|
||||
case 'challenge': {
|
||||
// The host trusts this key: prove it is here (#34).
|
||||
const signature = this.key?.sign(message.nonce);
|
||||
if (!signature) {
|
||||
this.fail('protocol_violation');
|
||||
return;
|
||||
}
|
||||
this.send({ type: 'proof', signature } as ClientMessage);
|
||||
break;
|
||||
}
|
||||
case 'trust':
|
||||
rememberTrust(message.trusted);
|
||||
break;
|
||||
case 'welcome':
|
||||
rememberTrust(message.trusted);
|
||||
// The chosen quality survives resumes: the host starts again from
|
||||
// its default setting at every session, so it is asked again.
|
||||
if (this.quality) {
|
||||
@@ -316,6 +352,7 @@ export class ViewerSession {
|
||||
}
|
||||
break;
|
||||
case 'error':
|
||||
if (message.code === 'not_trusted') rememberTrust(false);
|
||||
if (isTerminal(message.code)) {
|
||||
this.fail(message.code as ViewerErrorCode);
|
||||
} else {
|
||||
@@ -332,9 +369,11 @@ export class ViewerSession {
|
||||
// resume would overwrite the user's choice.
|
||||
break;
|
||||
case 'source_changed':
|
||||
// The frames switch on the host side, in the same track: no
|
||||
// renegotiation, the full screen and the stats go on (#26).
|
||||
this.options.onSourceChanged?.(message.source);
|
||||
break;
|
||||
case 'ice_candidate':
|
||||
// The stream is replaced on the host side; nothing to do here
|
||||
// before the issue on hot source switching.
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
@@ -350,6 +389,7 @@ export class ViewerSession {
|
||||
pc.addTransceiver('video', { direction: 'recvonly' });
|
||||
pc.addEventListener('track', (event) => {
|
||||
if (!current()) return;
|
||||
minimizeJitterBuffer(event.receiver);
|
||||
const [stream] = event.streams;
|
||||
this.options.onStream(stream ?? new MediaStream([event.track]));
|
||||
});
|
||||
@@ -380,6 +420,12 @@ export class ViewerSession {
|
||||
}
|
||||
}
|
||||
|
||||
/** Tells the host the new name of this device (#36), right away if connected. */
|
||||
rename(name: string): void {
|
||||
const clean = cleanName(name) || suggestedName(navigator.userAgent);
|
||||
this.send({ type: 'rename', name: clean } as ClientMessage);
|
||||
}
|
||||
|
||||
private send(message: ClientMessage): void {
|
||||
if (this.ws?.readyState === WebSocket.OPEN) {
|
||||
this.ws.send(JSON.stringify(message));
|
||||
@@ -487,10 +533,7 @@ export type VideoStats = {
|
||||
* `hello` and displayed by the host, kept as they were.
|
||||
*/
|
||||
function defaultDeviceName(): string {
|
||||
const ua = navigator.userAgent;
|
||||
if (/iPad|Tablet/i.test(ua)) return 'Tablette';
|
||||
if (/Mobile|Android/i.test(ua)) return 'Téléphone';
|
||||
return 'Navigateur';
|
||||
return readName() ?? suggestedName(navigator.userAgent);
|
||||
}
|
||||
|
||||
async function waitForIceGathering(pc: RTCPeerConnection, timeoutMs: number): Promise<void> {
|
||||
@@ -508,3 +551,21 @@ async function waitForIceGathering(pc: RTCPeerConnection, timeoutMs: number): Pr
|
||||
pc.addEventListener('icegatheringstatechange', check);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Asks the browser to hold as few frames as possible before display (#86).
|
||||
* Its jitter buffer is sized for calls over the Internet; on a local network
|
||||
* a screen share wants the frame on screen as soon as it is decoded.
|
||||
* `jitterBufferTarget` is the standard (Chrome 114+, Firefox 125+),
|
||||
* `playoutDelayHint` the older Chrome spelling. Unknown to the browser: no
|
||||
* effect.
|
||||
*/
|
||||
export function minimizeJitterBuffer(receiver: RTCRtpReceiver): void {
|
||||
const tunable = receiver as unknown as Record<string, unknown>;
|
||||
try {
|
||||
if ('jitterBufferTarget' in tunable) tunable.jitterBufferTarget = 0;
|
||||
else if ('playoutDelayHint' in tunable) tunable.playoutDelayHint = 0;
|
||||
} catch {
|
||||
// A browser refusing the value keeps its default.
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
import type { KeyValueStore } from './storage';
|
||||
import { nextTheme, readTheme, saveTheme } from './theme';
|
||||
import { readTheme, saveTheme } from './theme';
|
||||
|
||||
function memory(): KeyValueStore {
|
||||
const values = new Map<string, string>();
|
||||
@@ -47,12 +47,6 @@ describe('theme (#28)', () => {
|
||||
expect(() => saveTheme('light', denied)).not.toThrow();
|
||||
});
|
||||
|
||||
it('cycles through the three values', () => {
|
||||
expect(nextTheme('system')).toBe('light');
|
||||
expect(nextTheme('light')).toBe('dark');
|
||||
expect(nextTheme('dark')).toBe('system');
|
||||
});
|
||||
|
||||
it('translates and rewrites a value stored before #83', () => {
|
||||
for (const [legacy, theme] of [
|
||||
['systeme', 'system'],
|
||||
|
||||
@@ -11,7 +11,8 @@ import { browserStorage, type KeyValueStore } from './storage';
|
||||
export type Theme = 'system' | 'light' | 'dark';
|
||||
|
||||
const KEY = 'rustscreen.theme';
|
||||
const ORDER: readonly Theme[] = ['system', 'light', 'dark'];
|
||||
/** The three themes, in the order the settings offer them. */
|
||||
export const THEMES: readonly Theme[] = ['system', 'light', 'dark'];
|
||||
/** Values stored before #83, under the same key. */
|
||||
const LEGACY_VALUES: Readonly<Record<string, Theme>> = {
|
||||
systeme: 'system',
|
||||
@@ -22,7 +23,7 @@ const LEGACY_VALUES: Readonly<Record<string, Theme>> = {
|
||||
export function readTheme(storage: KeyValueStore | null = browserStorage()): Theme {
|
||||
try {
|
||||
const raw = storage?.getItem(KEY);
|
||||
if (raw && (ORDER as readonly string[]).includes(raw)) return raw as Theme;
|
||||
if (raw && (THEMES as readonly string[]).includes(raw)) return raw as Theme;
|
||||
const migrated = raw ? LEGACY_VALUES[raw] : undefined;
|
||||
if (migrated) {
|
||||
saveTheme(migrated, storage);
|
||||
@@ -42,11 +43,6 @@ export function saveTheme(theme: Theme, storage: KeyValueStore | null = browserS
|
||||
}
|
||||
}
|
||||
|
||||
/** The next theme, for a single button that cycles through all three. */
|
||||
export function nextTheme(theme: Theme): Theme {
|
||||
return ORDER[(ORDER.indexOf(theme) + 1) % ORDER.length] ?? 'system';
|
||||
}
|
||||
|
||||
/** Sets the theme on the root element: the style sheet does the rest. */
|
||||
export function applyTheme(theme: Theme, root: HTMLElement = document.documentElement): void {
|
||||
root.dataset.theme = theme;
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import { deviceKey, fromSecret, isTrusted, rememberTrust } from './trust';
|
||||
|
||||
/** `rs_proto::trust::TEST_VECTOR`: the host checks the same four values. */
|
||||
const VECTOR = {
|
||||
secret: '9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60',
|
||||
publicKey: 'd75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a',
|
||||
nonce: '000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f',
|
||||
signature:
|
||||
'76d5c3961e096b67f6932039110292bb727a9475552afe48961c0073c653001e8fba219441d9795a9aa721224353aa589049d2d1050e0f37ce32b7953ea86f0e',
|
||||
};
|
||||
|
||||
function memory(): Map<string, string> & Storage {
|
||||
const map = new Map<string, string>();
|
||||
return Object.assign(map, {
|
||||
getItem: (k: string) => map.get(k) ?? null,
|
||||
setItem: (k: string, v: string) => void map.set(k, v),
|
||||
removeItem: (k: string) => void map.delete(k),
|
||||
}) as unknown as Map<string, string> & Storage;
|
||||
}
|
||||
|
||||
describe('device key', () => {
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
it('signs exactly what the host checks', () => {
|
||||
const key = fromSecret(VECTOR.secret);
|
||||
expect(key.publicKey).toBe(VECTOR.publicKey);
|
||||
expect(key.sign(VECTOR.nonce)).toBe(VECTOR.signature);
|
||||
});
|
||||
|
||||
it('refuses to sign a malformed nonce', () => {
|
||||
expect(fromSecret(VECTOR.secret).sign('zz')).toBeNull();
|
||||
});
|
||||
|
||||
it('is drawn once and kept', () => {
|
||||
const storage = memory();
|
||||
const first = deviceKey(storage);
|
||||
const second = deviceKey(storage);
|
||||
expect(first?.publicKey).toMatch(/^[0-9a-f]{64}$/);
|
||||
expect(second?.publicKey).toBe(first?.publicKey);
|
||||
});
|
||||
|
||||
it('works without crypto.subtle, as on a page served over HTTP on the LAN', () => {
|
||||
const random = globalThis.crypto.getRandomValues.bind(globalThis.crypto);
|
||||
vi.stubGlobal('crypto', { getRandomValues: random });
|
||||
expect(globalThis.crypto.subtle).toBeUndefined();
|
||||
const key = deviceKey(memory());
|
||||
expect(key?.sign(VECTOR.nonce)).toMatch(/^[0-9a-f]{128}$/);
|
||||
});
|
||||
|
||||
it('is absent when the browser keeps nothing', () => {
|
||||
expect(deviceKey(null)).toBeNull();
|
||||
const forgetful = {
|
||||
getItem: () => null,
|
||||
setItem: () => undefined,
|
||||
removeItem: () => undefined,
|
||||
};
|
||||
expect(deviceKey(forgetful)).toBeNull();
|
||||
});
|
||||
|
||||
it('remembers what the host said', () => {
|
||||
const storage = memory();
|
||||
expect(isTrusted(storage)).toBe(false);
|
||||
rememberTrust(true, storage);
|
||||
expect(isTrusted(storage)).toBe(true);
|
||||
rememberTrust(false, storage);
|
||||
expect(isTrusted(storage)).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,102 @@
|
||||
/**
|
||||
* The key of this device, to come back without a link once the host trusts
|
||||
* it (#34).
|
||||
*
|
||||
* The page is served over HTTP on the LAN, which is not a secure context:
|
||||
* `crypto.subtle` does not exist there, `crypto.getRandomValues()` does. The
|
||||
* Ed25519 signature is therefore done in JavaScript (`@noble/ed25519`,
|
||||
* bundled, no network), and the private key lives in `localStorage` for this
|
||||
* origin. It is never sent, never logged: the host receives the public key
|
||||
* and signatures only.
|
||||
*
|
||||
* What is signed is fixed here, not chosen by the host: the context
|
||||
* `rustscreen-trust-v1`, a zero byte, then the nonce of the challenge. It
|
||||
* mirrors `rs_proto::trust`, and both test suites check the same vector.
|
||||
*/
|
||||
import * as ed from '@noble/ed25519';
|
||||
import { sha512 } from '@noble/hashes/sha2.js';
|
||||
|
||||
import { browserStorage, type KeyValueStore } from './storage';
|
||||
|
||||
ed.hashes.sha512 = sha512;
|
||||
|
||||
const SECRET_KEY = 'rustscreen.key';
|
||||
/** Set once the host said it trusts this device: the home page then connects. */
|
||||
const TRUSTED_KEY = 'rustscreen.trusted';
|
||||
const CONTEXT = new TextEncoder().encode('rustscreen-trust-v1');
|
||||
const HEX_32 = /^[0-9a-f]{64}$/;
|
||||
|
||||
export type DeviceKey = {
|
||||
/** Public key, 64 hex digits: what the host keeps. */
|
||||
publicKey: string;
|
||||
/** Signs the nonce of a challenge (64 hex digits), or `null` if malformed. */
|
||||
sign(nonce: string): string | null;
|
||||
};
|
||||
|
||||
/**
|
||||
* The key of this device, drawn on first use. `null` when the browser cannot
|
||||
* keep it (storage denied, or a browser too old for the signature code): the
|
||||
* device then goes through the link every time, as before #34.
|
||||
*/
|
||||
export function deviceKey(storage: KeyValueStore | null = browserStorage()): DeviceKey | null {
|
||||
if (!storage) return null;
|
||||
try {
|
||||
let secret = storage.getItem(SECRET_KEY);
|
||||
if (!secret || !HEX_32.test(secret)) {
|
||||
secret = toHex(ed.utils.randomSecretKey());
|
||||
storage.setItem(SECRET_KEY, secret);
|
||||
// Read back: a storage that accepts and forgets would draw a new
|
||||
// key on each visit, which the host could never trust.
|
||||
if (storage.getItem(SECRET_KEY) !== secret) return null;
|
||||
}
|
||||
return fromSecret(secret);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** The key for a known secret: exported for the shared test vector. */
|
||||
export function fromSecret(secretHex: string): DeviceKey {
|
||||
const secret = fromHex(secretHex);
|
||||
return {
|
||||
publicKey: toHex(ed.getPublicKey(secret)),
|
||||
sign(nonce: string) {
|
||||
if (!HEX_32.test(nonce)) return null;
|
||||
const message = new Uint8Array(CONTEXT.length + 1 + 32);
|
||||
message.set(CONTEXT, 0);
|
||||
message.set(fromHex(nonce), CONTEXT.length + 1);
|
||||
return toHex(ed.sign(message, secret));
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** Did the host say, last time, that it trusts this device? */
|
||||
export function isTrusted(storage: KeyValueStore | null = browserStorage()): boolean {
|
||||
try {
|
||||
return storage?.getItem(TRUSTED_KEY) === '1';
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/** Remembers what the host said, from the `welcome` or a `not_trusted`. */
|
||||
export function rememberTrust(trusted: boolean, storage: KeyValueStore | null = browserStorage()) {
|
||||
try {
|
||||
if (trusted) storage?.setItem(TRUSTED_KEY, '1');
|
||||
else storage?.removeItem(TRUSTED_KEY);
|
||||
} catch {
|
||||
// Storage denied: the home page will offer the code, as before.
|
||||
}
|
||||
}
|
||||
|
||||
function toHex(bytes: Uint8Array): string {
|
||||
return Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('');
|
||||
}
|
||||
|
||||
function fromHex(hex: string): Uint8Array {
|
||||
const bytes = new Uint8Array(hex.length / 2);
|
||||
for (let i = 0; i < bytes.length; i++) {
|
||||
bytes[i] = Number.parseInt(hex.slice(i * 2, i * 2 + 2), 16);
|
||||
}
|
||||
return bytes;
|
||||
}
|
||||
@@ -7,4 +7,8 @@ import type { StreamSettings } from "./StreamSettings";
|
||||
/**
|
||||
* What the viewer sends to the host.
|
||||
*/
|
||||
export type ClientMessage = { "type": "hello", version: number, room: RoomId, token: SessionToken, device: DeviceInfo, } | { "type": "offer", sdp: string, } | { "type": "ice_candidate", candidate: string, sdp_mid: string | null, sdp_mline_index: number | null, } | { "type": "quality_request", settings: StreamSettings, } | { "type": "bye" };
|
||||
export type ClientMessage = { "type": "hello", version: number, room: RoomId | null, token: SessionToken | null, device: DeviceInfo,
|
||||
/**
|
||||
* Ed25519 public key of the device, 64 hex digits. Never the private key.
|
||||
*/
|
||||
key: string | null, } | { "type": "proof", signature: string, } | { "type": "offer", sdp: string, } | { "type": "ice_candidate", candidate: string, sdp_mid: string | null, sdp_mline_index: number | null, } | { "type": "quality_request", settings: StreamSettings, } | { "type": "rename", name: string, } | { "type": "bye" };
|
||||
@@ -1,3 +1,3 @@
|
||||
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
|
||||
|
||||
export type ErrorCode = "bad_version" | "bad_token" | "token_expired" | "room_full" | "source_unavailable" | "protocol_violation" | "internal" | "kicked" | "share_ended";
|
||||
export type ErrorCode = "bad_version" | "bad_token" | "token_expired" | "token_used" | "room_full" | "source_unavailable" | "protocol_violation" | "internal" | "kicked" | "share_ended" | "not_trusted";
|
||||
@@ -11,4 +11,8 @@ export type ServerMessage = { "type": "welcome", version: number, room: RoomId,
|
||||
/**
|
||||
* Number of viewers already connected, and the limit.
|
||||
*/
|
||||
connected: number, limit: number, } | { "type": "answer", sdp: string, } | { "type": "ice_candidate", candidate: string, sdp_mid: string | null, sdp_mline_index: number | null, } | { "type": "source_changed", source: SourceInfo, } | { "type": "settings_applied", settings: StreamSettings, } | { "type": "error", code: ErrorCode, message: string, } | { "type": "bye", reason: string, };
|
||||
connected: number, limit: number,
|
||||
/**
|
||||
* The device got in by its key: it may come back without a link (#34).
|
||||
*/
|
||||
trusted: boolean, } | { "type": "challenge", nonce: string, } | { "type": "trust", trusted: boolean, } | { "type": "answer", sdp: string, } | { "type": "ice_candidate", candidate: string, sdp_mid: string | null, sdp_mline_index: number | null, } | { "type": "source_changed", source: SourceInfo, } | { "type": "settings_applied", settings: StreamSettings, } | { "type": "error", code: ErrorCode, message: string, } | { "type": "bye", reason: string, };
|
||||
+102
-12
@@ -229,8 +229,8 @@ body {
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.topbar .button-theme {
|
||||
margin-left: auto;
|
||||
.spacer {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.button-ghost {
|
||||
@@ -256,26 +256,102 @@ body {
|
||||
background: var(--surface);
|
||||
}
|
||||
|
||||
/* Language picker (#21): discreet, at the end of the footer. */
|
||||
.language {
|
||||
margin-left: auto;
|
||||
padding: 0 1rem;
|
||||
/* Settings behind the gear (#92): the page shows the screen, nothing else. */
|
||||
.overlay {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
z-index: 10;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
padding: 1rem;
|
||||
background: rgb(0 0 0 / 45%);
|
||||
}
|
||||
|
||||
.language select {
|
||||
padding: 0.25rem 0.4rem;
|
||||
.settings-panel {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 1rem;
|
||||
width: min(24rem, 100%);
|
||||
max-height: 100%;
|
||||
overflow: auto;
|
||||
padding: 1.25rem;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius);
|
||||
background: var(--surface);
|
||||
color: var(--fg);
|
||||
}
|
||||
|
||||
.settings-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 1rem;
|
||||
}
|
||||
|
||||
.settings-header h2 {
|
||||
margin: 0;
|
||||
font-size: 1.05rem;
|
||||
}
|
||||
|
||||
.settings-field,
|
||||
.device-name {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.35rem;
|
||||
}
|
||||
|
||||
.settings-field label {
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.settings-field input,
|
||||
.settings-field select {
|
||||
padding: 0.45rem 0.55rem;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 6px;
|
||||
background: var(--surface);
|
||||
color: var(--fg);
|
||||
font: inherit;
|
||||
}
|
||||
|
||||
.settings-help {
|
||||
color: var(--muted);
|
||||
font-size: 0.82rem;
|
||||
}
|
||||
|
||||
.pairing .language {
|
||||
display: block;
|
||||
margin-top: 1rem;
|
||||
padding: 0;
|
||||
.settings-check {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.settings-info {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.6rem;
|
||||
margin: 0;
|
||||
font-size: 0.82rem;
|
||||
}
|
||||
|
||||
.settings-info dt {
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.settings-info dd {
|
||||
margin: 0.15rem 0 0;
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
.mono {
|
||||
font-family: ui-monospace, monospace;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.pairing-header {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
gap: 1rem;
|
||||
}
|
||||
|
||||
.visually-hidden {
|
||||
@@ -425,3 +501,17 @@ body {
|
||||
transition: none;
|
||||
}
|
||||
}
|
||||
|
||||
/* Brief notice of a source switch (#26): over the picture, never in the way. */
|
||||
.switch-notice {
|
||||
position: absolute;
|
||||
top: 1rem;
|
||||
left: 50%;
|
||||
transform: translateX(-50%);
|
||||
padding: 0.4rem 0.9rem;
|
||||
border-radius: 999px;
|
||||
background: var(--veil);
|
||||
color: var(--fg);
|
||||
font-size: 0.9rem;
|
||||
pointer-events: none;
|
||||
}
|
||||
@@ -24,4 +24,15 @@ pipewire = { version = "0.10.1", optional = true, features = ["v0_3_44"] }
|
||||
x11rb = { version = "0.14.0", features = ["shm", "composite", "randr"] }
|
||||
rustix = { version = "1", features = ["fs", "mm", "shm"] }
|
||||
|
||||
# Windows (#8): GDI for every monitor and window, pointer included.
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
windows-sys = { version = "0.61.2", features = [
|
||||
"Win32_Foundation",
|
||||
"Win32_Graphics_Dwm",
|
||||
"Win32_Graphics_Gdi",
|
||||
"Win32_Storage_Xps",
|
||||
"Win32_UI_HiDpi",
|
||||
"Win32_UI_WindowsAndMessaging",
|
||||
] }
|
||||
|
||||
[dev-dependencies]
|
||||
@@ -10,6 +10,7 @@
|
||||
pub enum DisplaySession {
|
||||
Wayland,
|
||||
X11,
|
||||
Windows,
|
||||
Headless,
|
||||
}
|
||||
|
||||
@@ -20,6 +21,8 @@ pub enum Backend {
|
||||
Portal,
|
||||
/// Direct X11, MIT-SHM when the server offers it.
|
||||
X11,
|
||||
/// Windows, through GDI (#8).
|
||||
Gdi,
|
||||
/// Generated test pattern, no screen.
|
||||
Synthetic,
|
||||
}
|
||||
@@ -29,6 +32,7 @@ impl Backend {
|
||||
match self {
|
||||
Self::Portal => "portal",
|
||||
Self::X11 => "x11",
|
||||
Self::Gdi => "gdi",
|
||||
Self::Synthetic => "synthetic",
|
||||
}
|
||||
}
|
||||
@@ -36,7 +40,7 @@ impl Backend {
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
|
||||
pub enum BackendChoiceError {
|
||||
#[error("unknown RUSTSCREEN_CAPTURE={0}: expected portal, x11 or synthetic")]
|
||||
#[error("unknown RUSTSCREEN_CAPTURE={0}: expected portal, x11, gdi or synthetic")]
|
||||
Unknown(String),
|
||||
#[error("no graphical session: nothing to capture (use --synthetic for a test pattern)")]
|
||||
NoSession,
|
||||
@@ -58,6 +62,7 @@ pub fn choose(
|
||||
return match value.to_ascii_lowercase().as_str() {
|
||||
"portail" | "portal" | "pipewire" | "wayland" => Ok(Backend::Portal),
|
||||
"x11" | "xshm" => Ok(Backend::X11),
|
||||
"gdi" | "windows" => Ok(Backend::Gdi),
|
||||
"synthetique" | "synthétique" | "synthetic" => Ok(Backend::Synthetic),
|
||||
_ => Err(BackendChoiceError::Unknown(value.to_string())),
|
||||
};
|
||||
@@ -68,6 +73,7 @@ pub fn choose(
|
||||
// path.
|
||||
DisplaySession::Wayland => Ok(Backend::Portal),
|
||||
DisplaySession::X11 => Ok(Backend::X11),
|
||||
DisplaySession::Windows => Ok(Backend::Gdi),
|
||||
DisplaySession::Headless => Err(BackendChoiceError::NoSession),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,9 +11,15 @@ use std::time::Instant;
|
||||
pub struct CapturedFrame {
|
||||
pub width: u32,
|
||||
pub height: u32,
|
||||
/// Width * height * 4 bytes, in B, G, R, A order.
|
||||
pub bgra: Vec<u8>,
|
||||
/// Width * height * 4 bytes, in B, G, R, A order. Shared: a source that
|
||||
/// repeats its last image hands out the same buffer, without a copy.
|
||||
pub bgra: std::sync::Arc<Vec<u8>>,
|
||||
pub captured_at: Instant,
|
||||
/// The image changed since the previous frame. A compositor that sends
|
||||
/// images only on change (GNOME) makes most frames of an idle screen
|
||||
/// repeats: the encoder can skip them (#86). A source that cannot tell
|
||||
/// says `true`.
|
||||
pub fresh: bool,
|
||||
/// Sequence number, to detect a skipped or duplicated frame.
|
||||
pub sequence: u64,
|
||||
}
|
||||
|
||||
@@ -3,8 +3,8 @@
|
||||
//! One [`ScreenCapturer`] interface, one implementation per system, and a
|
||||
//! synthetic test pattern to test the rest of the pipeline without a screen.
|
||||
//! On Linux: the portal and PipeWire for Wayland ([`pipewire`], `pipewire`
|
||||
//! feature), X11 as a fallback ([`x11`]). The choice of path lives in
|
||||
//! [`backend`].
|
||||
//! feature), X11 as a fallback ([`x11`]). On Windows: GDI ([`windows`]). The
|
||||
//! choice of path lives in [`backend`].
|
||||
//!
|
||||
//! Output: BGRA frames with a monotonic timestamp. Conversion to I420 and
|
||||
//! encoding belong to `rs-codec`.
|
||||
@@ -18,6 +18,8 @@ pub mod synthetic;
|
||||
|
||||
#[cfg(all(target_os = "linux", feature = "pipewire"))]
|
||||
pub mod pipewire;
|
||||
#[cfg(windows)]
|
||||
pub mod windows;
|
||||
#[cfg(target_os = "linux")]
|
||||
pub mod x11;
|
||||
|
||||
|
||||
@@ -102,8 +102,12 @@ pub struct PipeWireCapturer {
|
||||
/// Size negotiated at start, to describe the source. Images then follow
|
||||
/// the current size of the stream.
|
||||
output: Option<(u32, u32)>,
|
||||
last: Vec<u8>,
|
||||
fitted: Vec<u8>,
|
||||
/// Last image from the compositor, shared with the encoder: repeating
|
||||
/// it costs no copy.
|
||||
last: Arc<Vec<u8>>,
|
||||
/// The same image trimmed to even dimensions, when the stream has an odd
|
||||
/// one; computed once per new image.
|
||||
fitted: Option<Arc<Vec<u8>>>,
|
||||
started: bool,
|
||||
}
|
||||
|
||||
@@ -155,8 +159,8 @@ impl PipeWireCapturer {
|
||||
cadence: Cadence::new(options.fps),
|
||||
sequence: 0,
|
||||
output: None,
|
||||
last: Vec::new(),
|
||||
fitted: Vec::new(),
|
||||
last: Arc::new(Vec::new()),
|
||||
fitted: None,
|
||||
started: false,
|
||||
})
|
||||
}
|
||||
@@ -263,8 +267,12 @@ impl ScreenCapturer for PipeWireCapturer {
|
||||
}
|
||||
|
||||
let (w, h) = state.size;
|
||||
if state.fresh {
|
||||
std::mem::swap(&mut self.last, &mut state.bgra);
|
||||
// The compositor sends an image only when the screen changes (GNOME):
|
||||
// without one, this frame repeats the last, and says so (#86).
|
||||
let fresh = state.fresh;
|
||||
if fresh {
|
||||
self.last = Arc::new(std::mem::take(&mut state.bgra));
|
||||
self.fitted = None;
|
||||
state.fresh = false;
|
||||
}
|
||||
drop(state);
|
||||
@@ -274,16 +282,20 @@ impl ScreenCapturer for PipeWireCapturer {
|
||||
// Only an odd dimension is trimmed.
|
||||
let output = pixels::even((w, h));
|
||||
let bgra = if (w, h) == output {
|
||||
self.last.clone()
|
||||
Arc::clone(&self.last)
|
||||
} else {
|
||||
pixels::fit(
|
||||
&self.last,
|
||||
w as usize,
|
||||
h as usize,
|
||||
(output.0 as usize, output.1 as usize),
|
||||
&mut self.fitted,
|
||||
);
|
||||
self.fitted.clone()
|
||||
let last = &self.last;
|
||||
Arc::clone(self.fitted.get_or_insert_with(|| {
|
||||
let mut fitted = Vec::new();
|
||||
pixels::fit(
|
||||
last,
|
||||
w as usize,
|
||||
h as usize,
|
||||
(output.0 as usize, output.1 as usize),
|
||||
&mut fitted,
|
||||
);
|
||||
Arc::new(fitted)
|
||||
}))
|
||||
};
|
||||
|
||||
let frame = CapturedFrame {
|
||||
@@ -291,6 +303,7 @@ impl ScreenCapturer for PipeWireCapturer {
|
||||
height: output.1,
|
||||
bgra,
|
||||
captured_at: Instant::now(),
|
||||
fresh,
|
||||
sequence: self.sequence,
|
||||
};
|
||||
self.sequence += 1;
|
||||
|
||||
@@ -4,8 +4,8 @@ use rs_proto::{SourceId, SourceInfo, SourceKind};
|
||||
|
||||
use crate::frame::{CaptureError, CapturedFrame};
|
||||
|
||||
/// One implementation per system: DXGI or WGC on Windows, ScreenCaptureKit on
|
||||
/// macOS, the PipeWire portal or X11 on Linux.
|
||||
/// One implementation per system: DXGI or WGC on Windows, the PipeWire portal
|
||||
/// or X11 on Linux. macOS is not a host platform (#90).
|
||||
pub trait ScreenCapturer: Send {
|
||||
/// Sources available right now. May change between two calls.
|
||||
fn sources(&mut self) -> Result<Vec<SourceInfo>, CaptureError>;
|
||||
|
||||
@@ -4,8 +4,17 @@
|
||||
//! It draws three bands (red, green, blue) and a moving white square. This is
|
||||
//! what lets you check in a browser that the colors land in the right place
|
||||
//! and that the image moves, instead of merely seeing bytes flow.
|
||||
//!
|
||||
//! The top rows carry a latency stamp (#86): the capture instant, in Unix
|
||||
//! milliseconds, as [`STAMP_BITS`] black or white blocks, then the same bits
|
||||
//! inverted on a second row. A reader accepts a stamp only when both rows
|
||||
//! disagree clearly on every bit, so a block blurred by compression is
|
||||
//! rejected instead of misread. The viewer reads it
|
||||
//! back when the frame is displayed, which measures the whole chain (capture,
|
||||
//! conversion, encoding, network, decoding, display) on one clock.
|
||||
|
||||
use std::time::{Duration, Instant};
|
||||
use std::sync::Arc;
|
||||
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
|
||||
|
||||
use rs_proto::{SourceId, SourceInfo, SourceKind};
|
||||
|
||||
@@ -16,6 +25,14 @@ pub const SOURCE_ID: &str = "synthetic";
|
||||
|
||||
const SQUARE: usize = 120;
|
||||
|
||||
/// Bits of the latency stamp: Unix milliseconds modulo 2^48 (8900 years).
|
||||
pub const STAMP_BITS: usize = 48;
|
||||
/// Side of one stamp block, in pixels: large enough to survive compression
|
||||
/// at any bitrate the encoder uses.
|
||||
pub const STAMP_BLOCK: usize = 16;
|
||||
/// Left and top margin of the stamp, in pixels.
|
||||
pub const STAMP_MARGIN: usize = 8;
|
||||
|
||||
pub struct SyntheticCapturer {
|
||||
width: usize,
|
||||
height: usize,
|
||||
@@ -23,8 +40,10 @@ pub struct SyntheticCapturer {
|
||||
sequence: u64,
|
||||
next_at: Option<Instant>,
|
||||
started: bool,
|
||||
/// Current image, reused from one frame to the next.
|
||||
bgra: Vec<u8>,
|
||||
/// Current image, reused from one frame to the next: painting goes
|
||||
/// through `Arc::make_mut`, which copies only if the encoder still holds
|
||||
/// the previous frame.
|
||||
bgra: Arc<Vec<u8>>,
|
||||
/// Last square drawn, to erase before drawing the next one.
|
||||
last_square: Option<(usize, usize)>,
|
||||
}
|
||||
@@ -40,7 +59,7 @@ impl SyntheticCapturer {
|
||||
sequence: 0,
|
||||
next_at: None,
|
||||
started: false,
|
||||
bgra: vec![0; width * height * 4],
|
||||
bgra: Arc::new(vec![0; width * height * 4]),
|
||||
last_square: None,
|
||||
}
|
||||
}
|
||||
@@ -57,28 +76,34 @@ impl SyntheticCapturer {
|
||||
}
|
||||
|
||||
fn fill_bands(&mut self) {
|
||||
let third = self.width / 3;
|
||||
for row in 0..self.height {
|
||||
for col in 0..self.width {
|
||||
let width = self.width;
|
||||
let height = self.height;
|
||||
let third = width / 3;
|
||||
let bgra = Arc::make_mut(&mut self.bgra);
|
||||
for row in 0..height {
|
||||
for col in 0..width {
|
||||
let color = band_color(col, third);
|
||||
let index = (row * self.width + col) * 4;
|
||||
self.bgra[index..index + 4].copy_from_slice(&color);
|
||||
let index = (row * width + col) * 4;
|
||||
bgra[index..index + 4].copy_from_slice(&color);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn fill_rect(&mut self, x: usize, y: usize, size: usize, color: [u8; 4]) {
|
||||
let third = self.width / 3;
|
||||
for row in y..(y + size).min(self.height) {
|
||||
for col in x..(x + size).min(self.width) {
|
||||
let index = (row * self.width + col) * 4;
|
||||
let width = self.width;
|
||||
let height = self.height;
|
||||
let third = width / 3;
|
||||
let bgra = Arc::make_mut(&mut self.bgra);
|
||||
for row in y..(y + size).min(height) {
|
||||
for col in x..(x + size).min(width) {
|
||||
let index = (row * width + col) * 4;
|
||||
// The white rectangle is erased by repainting the original band.
|
||||
let value = if color == [255, 255, 255, 255] {
|
||||
color
|
||||
} else {
|
||||
band_color(col, third)
|
||||
};
|
||||
self.bgra[index..index + 4].copy_from_slice(&value);
|
||||
bgra[index..index + 4].copy_from_slice(&value);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -96,6 +121,60 @@ impl SyntheticCapturer {
|
||||
}
|
||||
}
|
||||
|
||||
impl SyntheticCapturer {
|
||||
/// Writes `millis` as the latency stamp, most significant bit first. A
|
||||
/// pattern too narrow for the stamp simply goes without it.
|
||||
fn paint_stamp(&mut self, millis: u64) {
|
||||
let needed = STAMP_MARGIN * 2 + STAMP_BITS * STAMP_BLOCK;
|
||||
if self.width < needed || self.height < STAMP_MARGIN * 2 + 2 * STAMP_BLOCK {
|
||||
return;
|
||||
}
|
||||
let width = self.width;
|
||||
let bgra = Arc::make_mut(&mut self.bgra);
|
||||
for bit in 0..STAMP_BITS {
|
||||
let set = (millis >> (STAMP_BITS - 1 - bit)) & 1 == 1;
|
||||
let x0 = STAMP_MARGIN + bit * STAMP_BLOCK;
|
||||
// Row 0: the bit; row 1: its complement.
|
||||
for (line, on) in [(0, set), (1, !set)] {
|
||||
let value = if on { 255 } else { 0 };
|
||||
let y0 = STAMP_MARGIN + line * STAMP_BLOCK;
|
||||
for row in y0..y0 + STAMP_BLOCK {
|
||||
for col in x0..x0 + STAMP_BLOCK {
|
||||
let index = (row * width + col) * 4;
|
||||
bgra[index..index + 4].copy_from_slice(&[value, value, value, 255]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads a latency stamp back from a BGRA image, for tests and tools.
|
||||
/// `None` when a bit is unclear on either row.
|
||||
pub fn read_stamp(bgra: &[u8], width: usize) -> Option<u64> {
|
||||
let mut millis = 0u64;
|
||||
for bit in 0..STAMP_BITS {
|
||||
let x = STAMP_MARGIN + bit * STAMP_BLOCK + STAMP_BLOCK / 2;
|
||||
let at = |line: usize| -> Option<i32> {
|
||||
let y = STAMP_MARGIN + line * STAMP_BLOCK + STAMP_BLOCK / 2;
|
||||
bgra.get((y * width + x) * 4 + 1).map(|g| i32::from(*g))
|
||||
};
|
||||
let (value, complement) = (at(0)?, at(1)?);
|
||||
if (value - complement).abs() < 128 {
|
||||
return None;
|
||||
}
|
||||
millis = (millis << 1) | u64::from(value > complement);
|
||||
}
|
||||
Some(millis)
|
||||
}
|
||||
|
||||
fn unix_millis() -> u64 {
|
||||
SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.map_or(0, |d| d.as_millis() as u64)
|
||||
& ((1 << STAMP_BITS) - 1)
|
||||
}
|
||||
|
||||
fn band_color(col: usize, third: usize) -> [u8; 4] {
|
||||
if col < third {
|
||||
// BGRA: red
|
||||
@@ -151,11 +230,13 @@ impl ScreenCapturer for SyntheticCapturer {
|
||||
self.next_at = Some(due + period);
|
||||
|
||||
self.paint_next();
|
||||
self.paint_stamp(unix_millis());
|
||||
let frame = CapturedFrame {
|
||||
width: self.width as u32,
|
||||
height: self.height as u32,
|
||||
bgra: self.bgra.clone(),
|
||||
bgra: Arc::clone(&self.bgra),
|
||||
captured_at: Instant::now(),
|
||||
fresh: true,
|
||||
sequence: self.sequence,
|
||||
};
|
||||
self.sequence += 1;
|
||||
@@ -207,6 +288,20 @@ mod tests {
|
||||
assert_ne!(first.bgra, second.bgra, "the square must have moved");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_frame_carries_its_capture_instant() {
|
||||
let mut capturer = SyntheticCapturer::new(1280, 720, 60);
|
||||
capturer.start(&SourceId(SOURCE_ID.into())).unwrap();
|
||||
let before = unix_millis();
|
||||
let frame = capturer.next_frame().unwrap();
|
||||
let after = unix_millis();
|
||||
let stamp = read_stamp(&frame.bgra, frame.width as usize).unwrap();
|
||||
assert!(
|
||||
(before..=after).contains(&stamp),
|
||||
"{before} <= {stamp} <= {after}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn odd_dimensions_are_rounded_down() {
|
||||
let capturer = SyntheticCapturer::new(301, 121, 30);
|
||||
|
||||
@@ -0,0 +1,655 @@
|
||||
//! Windows capture through GDI (#8): every monitor, all of them together, or
|
||||
//! one window.
|
||||
//!
|
||||
//! GDI is the path that works everywhere, from Windows 10 to Wine, without a
|
||||
//! GPU: `BitBlt` from the screen for a monitor, `PrintWindow` for a window,
|
||||
//! which reads it even when another one covers it. The pointer is drawn into
|
||||
//! the image, as the viewer must see where the presenter points. Desktop
|
||||
//! Duplication (DXGI) is the faster path for a monitor, and comes on top of
|
||||
//! this one.
|
||||
//!
|
||||
//! Window titles go to the interface, never to the log (ADR 0008).
|
||||
|
||||
use std::time::Instant;
|
||||
|
||||
use rs_proto::{SourceId, SourceInfo, SourceKind};
|
||||
use windows_sys::Win32::Foundation::{HWND, LPARAM, POINT, RECT, TRUE};
|
||||
use windows_sys::Win32::Graphics::Dwm::{DWMWA_CLOAKED, DwmGetWindowAttribute};
|
||||
use windows_sys::Win32::Graphics::Gdi::{
|
||||
BI_RGB, BITMAPINFO, BITMAPINFOHEADER, BitBlt, CAPTUREBLT, CreateCompatibleDC, CreateDIBSection,
|
||||
DIB_RGB_COLORS, DeleteDC, DeleteObject, EnumDisplayMonitors, GdiFlush, GetDC, GetMonitorInfoW,
|
||||
HBITMAP, HDC, HGDIOBJ, HMONITOR, MONITORINFO, MONITORINFOEXW, ReleaseDC, SRCCOPY, SelectObject,
|
||||
};
|
||||
use windows_sys::Win32::Storage::Xps::PrintWindow;
|
||||
use windows_sys::Win32::UI::HiDpi::{
|
||||
DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2, SetProcessDpiAwarenessContext,
|
||||
};
|
||||
use windows_sys::Win32::UI::WindowsAndMessaging::{
|
||||
CURSOR_SHOWING, CURSORINFO, DI_NORMAL, DrawIconEx, EnumWindows, GWL_EXSTYLE, GetCursorInfo,
|
||||
GetIconInfo, GetSystemMetrics, GetWindowLongPtrW, GetWindowRect, GetWindowTextW,
|
||||
GetWindowThreadProcessId, ICONINFO, IsIconic, IsWindow, IsWindowVisible, MONITORINFOF_PRIMARY,
|
||||
PW_RENDERFULLCONTENT, SM_CXVIRTUALSCREEN, SM_CYVIRTUALSCREEN, SM_XVIRTUALSCREEN,
|
||||
SM_YVIRTUALSCREEN, WS_EX_TOOLWINDOW,
|
||||
};
|
||||
|
||||
use crate::cadence::Cadence;
|
||||
use crate::frame::{CaptureError, CapturedFrame};
|
||||
use crate::pixels;
|
||||
use crate::source::{ScreenCapturer, describe};
|
||||
|
||||
/// All monitors together, as one image.
|
||||
pub const SCREEN: &str = "windows:screen";
|
||||
/// A monitor, by its device name (`\\.\DISPLAY1`).
|
||||
pub const MONITOR_PREFIX: &str = "windows:monitor:";
|
||||
/// A window, by its handle in hexadecimal.
|
||||
pub const WINDOW_PREFIX: &str = "windows:window:";
|
||||
|
||||
/// A handful of pixels is not an application.
|
||||
const MIN_WINDOW_SIZE: u32 = 64;
|
||||
|
||||
/// A monitor as Windows describes it, in physical pixels.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Monitor {
|
||||
pub device: String,
|
||||
pub x: i32,
|
||||
pub y: i32,
|
||||
pub width: u32,
|
||||
pub height: u32,
|
||||
pub primary: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
enum Target {
|
||||
Screen,
|
||||
Monitor,
|
||||
Window(HWND),
|
||||
}
|
||||
|
||||
pub struct GdiCapturer {
|
||||
target: Option<Target>,
|
||||
/// Device of the captured monitor: its rectangle is read again at each
|
||||
/// frame, so a resolution change follows.
|
||||
device: String,
|
||||
surface: Option<Surface>,
|
||||
cadence: Cadence,
|
||||
sequence: u64,
|
||||
previous: std::sync::Arc<Vec<u8>>,
|
||||
fitted: Vec<u8>,
|
||||
}
|
||||
|
||||
// The handles are only used from the capture thread that owns the capturer.
|
||||
unsafe impl Send for GdiCapturer {}
|
||||
|
||||
impl GdiCapturer {
|
||||
pub fn new(fps: u8) -> Self {
|
||||
// Physical pixels: without this, a 150 % display is captured at two
|
||||
// thirds of its size, then enlarged, and the text is blurry.
|
||||
// SAFETY: no argument to get wrong; refused when already set.
|
||||
unsafe { SetProcessDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2) };
|
||||
Self {
|
||||
target: None,
|
||||
device: String::new(),
|
||||
surface: None,
|
||||
cadence: Cadence::new(fps),
|
||||
sequence: 0,
|
||||
previous: std::sync::Arc::new(Vec::new()),
|
||||
fitted: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The monitors, the primary one first.
|
||||
pub fn monitors() -> Vec<Monitor> {
|
||||
unsafe extern "system" fn collect(
|
||||
monitor: HMONITOR,
|
||||
_dc: HDC,
|
||||
_rect: *mut RECT,
|
||||
data: LPARAM,
|
||||
) -> windows_sys::core::BOOL {
|
||||
// SAFETY: `data` is the vector passed by `monitors`, alive during
|
||||
// the enumeration.
|
||||
let list = unsafe { &mut *(data as *mut Vec<Monitor>) };
|
||||
let mut info = MONITORINFOEXW {
|
||||
monitorInfo: MONITORINFO {
|
||||
cbSize: std::mem::size_of::<MONITORINFOEXW>() as u32,
|
||||
..Default::default()
|
||||
},
|
||||
..Default::default()
|
||||
};
|
||||
// SAFETY: `info` is an MONITORINFOEXW whose size is announced.
|
||||
if unsafe { GetMonitorInfoW(monitor, (&raw mut info).cast()) } != 0 {
|
||||
let r = info.monitorInfo.rcMonitor;
|
||||
list.push(Monitor {
|
||||
device: from_wide(&info.szDevice),
|
||||
x: r.left,
|
||||
y: r.top,
|
||||
width: (r.right - r.left).max(0) as u32,
|
||||
height: (r.bottom - r.top).max(0) as u32,
|
||||
primary: info.monitorInfo.dwFlags & MONITORINFOF_PRIMARY != 0,
|
||||
});
|
||||
}
|
||||
TRUE
|
||||
}
|
||||
let mut list: Vec<Monitor> = Vec::new();
|
||||
// SAFETY: the callback only touches `list`, which outlives the call.
|
||||
unsafe {
|
||||
EnumDisplayMonitors(
|
||||
std::ptr::null_mut(),
|
||||
std::ptr::null(),
|
||||
Some(collect),
|
||||
(&raw mut list) as LPARAM,
|
||||
)
|
||||
};
|
||||
list.sort_by_key(|m| (!m.primary, m.x, m.y));
|
||||
list
|
||||
}
|
||||
|
||||
/// The application windows: visible, titled, not a tool palette, not
|
||||
/// cloaked (another virtual desktop, a suspended UWP app), not ours.
|
||||
fn windows() -> Vec<HWND> {
|
||||
unsafe extern "system" fn collect(window: HWND, data: LPARAM) -> windows_sys::core::BOOL {
|
||||
// SAFETY: `data` is the vector passed by `windows`.
|
||||
let list = unsafe { &mut *(data as *mut Vec<HWND>) };
|
||||
if is_application(window) {
|
||||
list.push(window);
|
||||
}
|
||||
TRUE
|
||||
}
|
||||
let mut list: Vec<HWND> = Vec::new();
|
||||
// SAFETY: the callback only touches `list`, which outlives the call.
|
||||
unsafe { EnumWindows(Some(collect), (&raw mut list) as LPARAM) };
|
||||
list
|
||||
}
|
||||
|
||||
/// The rectangle to read for the current target, in screen coordinates.
|
||||
fn rectangle(&self, target: Target) -> Result<RECT, CaptureError> {
|
||||
match target {
|
||||
Target::Screen => Ok(virtual_screen()),
|
||||
Target::Monitor => Self::monitors()
|
||||
.into_iter()
|
||||
.find(|m| m.device == self.device)
|
||||
.map(|m| RECT {
|
||||
left: m.x,
|
||||
top: m.y,
|
||||
right: m.x + m.width as i32,
|
||||
bottom: m.y + m.height as i32,
|
||||
})
|
||||
.ok_or(CaptureError::SourceGone),
|
||||
Target::Window(window) => window_rect(window),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ScreenCapturer for GdiCapturer {
|
||||
fn sources(&mut self) -> Result<Vec<SourceInfo>, CaptureError> {
|
||||
let monitors = Self::monitors();
|
||||
let mut sources = Vec::new();
|
||||
for m in &monitors {
|
||||
let name = if m.primary {
|
||||
format!("{} (primary)", m.device)
|
||||
} else {
|
||||
m.device.clone()
|
||||
};
|
||||
sources.push(describe(
|
||||
format!("{MONITOR_PREFIX}{}", m.device),
|
||||
SourceKind::Screen,
|
||||
name,
|
||||
m.width,
|
||||
m.height,
|
||||
true,
|
||||
));
|
||||
}
|
||||
if monitors.len() > 1 {
|
||||
let r = virtual_screen();
|
||||
sources.push(describe(
|
||||
SCREEN,
|
||||
SourceKind::Screen,
|
||||
"All screens",
|
||||
(r.right - r.left) as u32,
|
||||
(r.bottom - r.top) as u32,
|
||||
true,
|
||||
));
|
||||
}
|
||||
for window in Self::windows() {
|
||||
let Ok(r) = window_rect(window) else {
|
||||
continue;
|
||||
};
|
||||
let (w, h) = ((r.right - r.left) as u32, (r.bottom - r.top) as u32);
|
||||
// SAFETY: `window` came from EnumWindows; a stale handle fails.
|
||||
let minimized = unsafe { IsIconic(window) } != 0;
|
||||
// Minimized windows report a tiny rectangle: listed anyway, so the
|
||||
// user finds them and knows why they are not offered.
|
||||
if !minimized && (w < MIN_WINDOW_SIZE || h < MIN_WINDOW_SIZE) {
|
||||
continue;
|
||||
}
|
||||
sources.push(describe(
|
||||
format!("{WINDOW_PREFIX}{:x}", window as usize),
|
||||
SourceKind::Window,
|
||||
title(window),
|
||||
w,
|
||||
h,
|
||||
!minimized,
|
||||
));
|
||||
}
|
||||
Ok(sources)
|
||||
}
|
||||
|
||||
fn start(&mut self, source: &SourceId) -> Result<(), CaptureError> {
|
||||
let target = if source.0 == SCREEN {
|
||||
Target::Screen
|
||||
} else if let Some(device) = source.0.strip_prefix(MONITOR_PREFIX) {
|
||||
if !Self::monitors().iter().any(|m| m.device == device) {
|
||||
return Err(CaptureError::SourceGone);
|
||||
}
|
||||
self.device = device.to_string();
|
||||
Target::Monitor
|
||||
} else if let Some(hex) = source.0.strip_prefix(WINDOW_PREFIX) {
|
||||
let window =
|
||||
usize::from_str_radix(hex, 16).map_err(|_| CaptureError::SourceGone)? as HWND;
|
||||
// SAFETY: IsWindow accepts any value and says whether it is one.
|
||||
if unsafe { IsWindow(window) } == 0 {
|
||||
return Err(CaptureError::SourceGone);
|
||||
}
|
||||
// SAFETY: a valid window handle.
|
||||
if unsafe { IsIconic(window) } != 0 {
|
||||
return Err(CaptureError::Unavailable(
|
||||
"the window is minimized: restore it to share it".into(),
|
||||
));
|
||||
}
|
||||
Target::Window(window)
|
||||
} else {
|
||||
return Err(CaptureError::SourceGone);
|
||||
};
|
||||
self.target = Some(target);
|
||||
self.surface = None;
|
||||
self.previous = std::sync::Arc::new(Vec::new());
|
||||
self.cadence.reset();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn next_frame(&mut self) -> Result<CapturedFrame, CaptureError> {
|
||||
let target = self
|
||||
.target
|
||||
.ok_or_else(|| CaptureError::Internal("capture not started".into()))?;
|
||||
self.cadence.wait();
|
||||
|
||||
let minimized = match target {
|
||||
Target::Window(window) => {
|
||||
// SAFETY: IsWindow accepts any value.
|
||||
if unsafe { IsWindow(window) } == 0 {
|
||||
return Err(CaptureError::SourceGone);
|
||||
}
|
||||
// SAFETY: a valid window handle.
|
||||
(unsafe { IsIconic(window) }) != 0
|
||||
}
|
||||
_ => false,
|
||||
};
|
||||
// Minimized, a window has nothing to show: viewers keep the last
|
||||
// image rather than a black one.
|
||||
if minimized && !self.previous.is_empty() {
|
||||
return Ok(self.repeat());
|
||||
}
|
||||
|
||||
let r = self.rectangle(target)?;
|
||||
let (w, h) = ((r.right - r.left) as u32, (r.bottom - r.top) as u32);
|
||||
if w == 0 || h == 0 {
|
||||
return Err(CaptureError::Internal("zero-size source".into()));
|
||||
}
|
||||
if self
|
||||
.surface
|
||||
.as_ref()
|
||||
.is_none_or(|s| (s.width, s.height) != (w, h))
|
||||
{
|
||||
self.surface = Some(Surface::new(w, h)?);
|
||||
}
|
||||
let surface = self.surface.as_mut().expect("just created");
|
||||
match target {
|
||||
Target::Window(window) => {
|
||||
surface.print_window(window)?;
|
||||
// Some applications draw on the GPU and leave PrintWindow a
|
||||
// black image (and Wine always does): the window is then read
|
||||
// where it shows on screen, as long as nothing covers it.
|
||||
if surface.is_black() {
|
||||
surface.copy_screen(r.left, r.top)?;
|
||||
}
|
||||
}
|
||||
_ => surface.copy_screen(r.left, r.top)?,
|
||||
}
|
||||
surface.draw_cursor(r.left, r.top);
|
||||
|
||||
// The output follows the source (#16); only an odd dimension is
|
||||
// trimmed by one pixel, which I420 refuses.
|
||||
let output = pixels::even((w, h));
|
||||
let bgra = if (w, h) == output {
|
||||
surface.pixels().to_vec()
|
||||
} else {
|
||||
pixels::fit(
|
||||
surface.pixels(),
|
||||
w as usize,
|
||||
h as usize,
|
||||
(output.0 as usize, output.1 as usize),
|
||||
&mut self.fitted,
|
||||
);
|
||||
self.fitted.clone()
|
||||
};
|
||||
// GDI cannot tell an unchanged screen: a comparison costs about a
|
||||
// millisecond in 1080p, much less than encoding a repeat (#86).
|
||||
let fresh = bgra != *self.previous;
|
||||
let bgra = if fresh {
|
||||
std::sync::Arc::new(bgra)
|
||||
} else {
|
||||
self.previous.clone()
|
||||
};
|
||||
self.previous = bgra.clone();
|
||||
let frame = CapturedFrame {
|
||||
width: output.0,
|
||||
height: output.1,
|
||||
bgra,
|
||||
fresh,
|
||||
captured_at: Instant::now(),
|
||||
sequence: self.sequence,
|
||||
};
|
||||
self.sequence += 1;
|
||||
Ok(frame)
|
||||
}
|
||||
|
||||
fn stop(&mut self) {
|
||||
self.target = None;
|
||||
self.surface = None;
|
||||
}
|
||||
}
|
||||
|
||||
impl GdiCapturer {
|
||||
/// The last image again, marked as not fresh.
|
||||
fn repeat(&mut self) -> CapturedFrame {
|
||||
let (width, height) = self
|
||||
.surface
|
||||
.as_ref()
|
||||
.map(|s| pixels::even((s.width, s.height)))
|
||||
.unwrap_or((0, 0));
|
||||
let frame = CapturedFrame {
|
||||
width,
|
||||
height,
|
||||
bgra: self.previous.clone(),
|
||||
fresh: false,
|
||||
captured_at: Instant::now(),
|
||||
sequence: self.sequence,
|
||||
};
|
||||
self.sequence += 1;
|
||||
frame
|
||||
}
|
||||
}
|
||||
|
||||
/// A memory device context and its top-down 32-bit DIB: GDI draws into it,
|
||||
/// and its bits are the BGRA image.
|
||||
struct Surface {
|
||||
dc: HDC,
|
||||
bitmap: HBITMAP,
|
||||
previous: HGDIOBJ,
|
||||
bits: *mut u8,
|
||||
width: u32,
|
||||
height: u32,
|
||||
}
|
||||
|
||||
impl Surface {
|
||||
fn new(width: u32, height: u32) -> Result<Self, CaptureError> {
|
||||
let info = BITMAPINFO {
|
||||
bmiHeader: BITMAPINFOHEADER {
|
||||
biSize: std::mem::size_of::<BITMAPINFOHEADER>() as u32,
|
||||
biWidth: width as i32,
|
||||
// Negative: rows from top to bottom, as the encoder reads them.
|
||||
biHeight: -(height as i32),
|
||||
biPlanes: 1,
|
||||
biBitCount: 32,
|
||||
biCompression: BI_RGB,
|
||||
..Default::default()
|
||||
},
|
||||
..Default::default()
|
||||
};
|
||||
// SAFETY: plain GDI object creation; every handle is checked, and
|
||||
// freed by `Drop` or on the failure path.
|
||||
unsafe {
|
||||
let screen = GetDC(std::ptr::null_mut());
|
||||
let dc = CreateCompatibleDC(screen);
|
||||
ReleaseDC(std::ptr::null_mut(), screen);
|
||||
if dc.is_null() {
|
||||
return Err(gdi("CreateCompatibleDC"));
|
||||
}
|
||||
let mut bits = std::ptr::null_mut();
|
||||
let bitmap = CreateDIBSection(
|
||||
dc,
|
||||
&info,
|
||||
DIB_RGB_COLORS,
|
||||
&mut bits,
|
||||
std::ptr::null_mut(),
|
||||
0,
|
||||
);
|
||||
if bitmap.is_null() || bits.is_null() {
|
||||
DeleteDC(dc);
|
||||
return Err(gdi("CreateDIBSection"));
|
||||
}
|
||||
let previous = SelectObject(dc, bitmap);
|
||||
Ok(Self {
|
||||
dc,
|
||||
bitmap,
|
||||
previous,
|
||||
bits: bits.cast(),
|
||||
width,
|
||||
height,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn copy_screen(&mut self, x: i32, y: i32) -> Result<(), CaptureError> {
|
||||
// SAFETY: both device contexts are valid; the screen one is released.
|
||||
let copied = unsafe {
|
||||
let screen = GetDC(std::ptr::null_mut());
|
||||
let copied = BitBlt(
|
||||
self.dc,
|
||||
0,
|
||||
0,
|
||||
self.width as i32,
|
||||
self.height as i32,
|
||||
screen,
|
||||
x,
|
||||
y,
|
||||
// Layered windows (menus, tooltips) are in the image too.
|
||||
SRCCOPY | CAPTUREBLT,
|
||||
);
|
||||
ReleaseDC(std::ptr::null_mut(), screen);
|
||||
copied
|
||||
};
|
||||
if copied == 0 {
|
||||
// The secure desktop (UAC, lock screen) refuses to be read.
|
||||
return Err(CaptureError::Unavailable(
|
||||
"Windows refuses to read the screen right now (locked session or elevation prompt)"
|
||||
.into(),
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn print_window(&mut self, window: HWND) -> Result<(), CaptureError> {
|
||||
// SAFETY: valid window and device context.
|
||||
if unsafe { PrintWindow(window, self.dc, PW_RENDERFULLCONTENT) } == 0 {
|
||||
return Err(CaptureError::Unavailable(
|
||||
"Windows refuses to draw this window".into(),
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Draws the pointer where it is, relative to the captured area.
|
||||
fn draw_cursor(&mut self, left: i32, top: i32) {
|
||||
let mut cursor = CURSORINFO {
|
||||
cbSize: std::mem::size_of::<CURSORINFO>() as u32,
|
||||
..Default::default()
|
||||
};
|
||||
// SAFETY: `cursor` announces its size; the icon bitmaps that
|
||||
// GetIconInfo creates are deleted right after.
|
||||
unsafe {
|
||||
if GetCursorInfo(&mut cursor) == 0 || cursor.flags & CURSOR_SHOWING == 0 {
|
||||
return;
|
||||
}
|
||||
let mut icon = ICONINFO::default();
|
||||
let (hot_x, hot_y) = if GetIconInfo(cursor.hCursor, &mut icon) != 0 {
|
||||
if !icon.hbmMask.is_null() {
|
||||
DeleteObject(icon.hbmMask);
|
||||
}
|
||||
if !icon.hbmColor.is_null() {
|
||||
DeleteObject(icon.hbmColor);
|
||||
}
|
||||
(icon.xHotspot as i32, icon.yHotspot as i32)
|
||||
} else {
|
||||
(0, 0)
|
||||
};
|
||||
let POINT { x, y } = cursor.ptScreenPos;
|
||||
DrawIconEx(
|
||||
self.dc,
|
||||
x - left - hot_x,
|
||||
y - top - hot_y,
|
||||
cursor.hCursor,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
std::ptr::null_mut(),
|
||||
DI_NORMAL,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Every pixel black: nothing was drawn.
|
||||
fn is_black(&self) -> bool {
|
||||
self.pixels()
|
||||
.as_chunks::<4>()
|
||||
.0
|
||||
.iter()
|
||||
.all(|p| p[..3] == [0, 0, 0])
|
||||
}
|
||||
|
||||
fn pixels(&self) -> &[u8] {
|
||||
// GDI batches its drawing: without a flush, the bits may not hold the
|
||||
// last BitBlt yet.
|
||||
// SAFETY: no argument.
|
||||
unsafe { GdiFlush() };
|
||||
let len = self.width as usize * self.height as usize * 4;
|
||||
// SAFETY: the DIB holds width × height 32-bit pixels, alive with
|
||||
// `self`, and GDI is done drawing when this is called.
|
||||
unsafe { std::slice::from_raw_parts(self.bits, len) }
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Surface {
|
||||
fn drop(&mut self) {
|
||||
// SAFETY: created by `Surface::new`, freed once.
|
||||
unsafe {
|
||||
SelectObject(self.dc, self.previous);
|
||||
DeleteObject(self.bitmap);
|
||||
DeleteDC(self.dc);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The rectangle covering every monitor.
|
||||
fn virtual_screen() -> RECT {
|
||||
// SAFETY: plain metrics.
|
||||
unsafe {
|
||||
let left = GetSystemMetrics(SM_XVIRTUALSCREEN);
|
||||
let top = GetSystemMetrics(SM_YVIRTUALSCREEN);
|
||||
RECT {
|
||||
left,
|
||||
top,
|
||||
right: left + GetSystemMetrics(SM_CXVIRTUALSCREEN),
|
||||
bottom: top + GetSystemMetrics(SM_CYVIRTUALSCREEN),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn window_rect(window: HWND) -> Result<RECT, CaptureError> {
|
||||
let mut r = RECT::default();
|
||||
// SAFETY: `r` receives the rectangle; a stale handle fails.
|
||||
if unsafe { GetWindowRect(window, &mut r) } == 0 {
|
||||
return Err(CaptureError::SourceGone);
|
||||
}
|
||||
Ok(r)
|
||||
}
|
||||
|
||||
fn is_application(window: HWND) -> bool {
|
||||
// SAFETY: every call accepts a window handle from EnumWindows and fails
|
||||
// cleanly if it went away in between.
|
||||
unsafe {
|
||||
if IsWindowVisible(window) == 0 {
|
||||
return false;
|
||||
}
|
||||
let style = GetWindowLongPtrW(window, GWL_EXSTYLE) as u32;
|
||||
if style & WS_EX_TOOLWINDOW != 0 {
|
||||
return false;
|
||||
}
|
||||
let mut cloaked = 0u32;
|
||||
let cloaked_read = DwmGetWindowAttribute(
|
||||
window,
|
||||
DWMWA_CLOAKED as u32,
|
||||
(&raw mut cloaked).cast(),
|
||||
std::mem::size_of::<u32>() as u32,
|
||||
) >= 0;
|
||||
if cloaked_read && cloaked != 0 {
|
||||
return false;
|
||||
}
|
||||
let mut process = 0u32;
|
||||
GetWindowThreadProcessId(window, &mut process);
|
||||
if process == std::process::id() {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
!title(window).is_empty()
|
||||
}
|
||||
|
||||
fn title(window: HWND) -> String {
|
||||
let mut buffer = [0u16; 256];
|
||||
// SAFETY: the buffer length is passed.
|
||||
let len = unsafe { GetWindowTextW(window, buffer.as_mut_ptr(), buffer.len() as i32) };
|
||||
String::from_utf16_lossy(&buffer[..len.max(0) as usize])
|
||||
}
|
||||
|
||||
fn from_wide(text: &[u16]) -> String {
|
||||
let end = text.iter().position(|c| *c == 0).unwrap_or(text.len());
|
||||
String::from_utf16_lossy(&text[..end])
|
||||
}
|
||||
|
||||
fn gdi(call: &str) -> CaptureError {
|
||||
CaptureError::Internal(format!("{call}: {}", std::io::Error::last_os_error()))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// Needs a desktop: under Wine, an X server (`Xvfb :7 & DISPLAY=:7`).
|
||||
#[test]
|
||||
#[ignore = "needs a Windows desktop"]
|
||||
fn the_primary_monitor_is_captured_with_its_size() {
|
||||
let mut capturer = GdiCapturer::new(30);
|
||||
let sources = capturer.sources().unwrap();
|
||||
let first = sources.first().expect("no monitor");
|
||||
assert_eq!(first.kind, SourceKind::Screen);
|
||||
capturer.start(&first.id).unwrap();
|
||||
let frame = capturer.next_frame().unwrap();
|
||||
let (w, h) = pixels::even((first.width, first.height));
|
||||
assert_eq!((frame.width, frame.height), (w, h));
|
||||
assert_eq!(frame.bgra.len(), (w * h * 4) as usize);
|
||||
// Not a black rectangle: a desktop has more than one colour.
|
||||
let first_pixel = &frame.bgra[..4];
|
||||
let varied = frame
|
||||
.bgra
|
||||
.as_chunks::<4>()
|
||||
.0
|
||||
.iter()
|
||||
.any(|p| p[..3] != first_pixel[..3]);
|
||||
assert!(varied, "uniform image, first pixel {first_pixel:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_wide_string_stops_at_its_terminator() {
|
||||
let text: Vec<u16> = r"\\.\DISPLAY1".encode_utf16().chain([0, 65, 66]).collect();
|
||||
assert_eq!(from_wide(&text), r"\\.\DISPLAY1");
|
||||
}
|
||||
}
|
||||
@@ -670,7 +670,9 @@ impl ScreenCapturer for X11Capturer {
|
||||
let frame = CapturedFrame {
|
||||
width: output.0,
|
||||
height: output.1,
|
||||
bgra,
|
||||
bgra: std::sync::Arc::new(bgra),
|
||||
// X11 cannot tell an unchanged image without XDamage.
|
||||
fresh: true,
|
||||
captured_at: Instant::now(),
|
||||
sequence: self.sequence,
|
||||
};
|
||||
|
||||
@@ -10,10 +10,34 @@ repository.workspace = true
|
||||
[dependencies]
|
||||
rs-capture = { path = "../rs-capture" }
|
||||
thiserror.workspace = true
|
||||
# `watch` only: the encoding thread tells the sessions a frame is ready (#86).
|
||||
tokio = { version = "1.54.1", default-features = false, features = ["sync"] }
|
||||
tracing.workspace = true
|
||||
# Direct binding to libvpx: `vpx-encode` controlled neither the lag queue nor
|
||||
# forced keyframes (#67). The `unsafe` code lives in `src/vpx.rs`.
|
||||
env-libvpx-sys = "5.1.3"
|
||||
# Hardware encoding through VA-API (#57), behind the `vaapi` feature: GStreamer
|
||||
# drives the GPU's encoder, its `va` plugin and the driver are found at
|
||||
# runtime. Without them, the host falls back on libvpx.
|
||||
gstreamer = { version = "0.25", optional = true }
|
||||
gstreamer-app = { version = "0.25", optional = true }
|
||||
gstreamer-video = { version = "0.25", optional = true }
|
||||
|
||||
# Windows (#95): Media Foundation, the H.264 encoder of the GPU (Quick Sync,
|
||||
# NVENC, AMF). COM interfaces: `windows`, not `windows-sys`. The `unsafe`
|
||||
# code lives in `src/media_foundation.rs`.
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
windows = { version = "0.62.2", features = [
|
||||
"Win32_Foundation",
|
||||
"Win32_Media_MediaFoundation",
|
||||
"Win32_System_Com",
|
||||
"Win32_System_Com_StructuredStorage",
|
||||
"Win32_System_Ole",
|
||||
"Win32_System_Variant",
|
||||
] }
|
||||
|
||||
[features]
|
||||
vaapi = ["dep:gstreamer", "dep:gstreamer-app", "dep:gstreamer-video"]
|
||||
|
||||
[dev-dependencies]
|
||||
rs-proto = { path = "../rs-proto" }
|
||||
@@ -0,0 +1,88 @@
|
||||
//! Cost of the VA-API encoder (#57) for one image, as the encoding thread
|
||||
//! sees it: the call returns once the GPU handed back the access unit.
|
||||
//!
|
||||
//! cargo run --release -p rs-codec --features vaapi --example bench_hardware -- 1920x1080 h264 60
|
||||
//!
|
||||
//! Prints the median and p95 of the call, and the CPU time of the process per
|
||||
//! image: the latency decides whether 60 images per second fit (16.7 ms), the
|
||||
//! CPU time is what the GPU saves.
|
||||
|
||||
#[cfg(feature = "vaapi")]
|
||||
fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
use std::time::Instant;
|
||||
|
||||
use rs_codec::{BgraFrame, EncodeConfig, HardwareEncoder, VideoCodec, VideoEncoder};
|
||||
|
||||
let mut args = std::env::args().skip(1);
|
||||
let size = args.next().unwrap_or_else(|| "1920x1080".into());
|
||||
let codec: VideoCodec = args.next().unwrap_or_else(|| "h264".into()).parse()?;
|
||||
let fps: u8 = args.next().map_or(Ok(60), |f| f.parse())?;
|
||||
let (width, height) = size
|
||||
.split_once('x')
|
||||
.and_then(|(w, h)| Some((w.parse::<u32>().ok()?, h.parse::<u32>().ok()?)))
|
||||
.ok_or("size: WxH")?;
|
||||
let mut encoder = HardwareEncoder::new(EncodeConfig {
|
||||
width,
|
||||
height,
|
||||
fps,
|
||||
bitrate_kbps: 6000,
|
||||
codec,
|
||||
})?;
|
||||
let frames: Vec<std::sync::Arc<Vec<u8>>> = (0..8)
|
||||
.map(|n| {
|
||||
let mut data = vec![235u8; (width * height * 4) as usize];
|
||||
for (i, b) in data.iter_mut().enumerate().step_by(4 * 7) {
|
||||
*b = ((i / 4 + n * 3) % 255) as u8;
|
||||
}
|
||||
std::sync::Arc::new(data)
|
||||
})
|
||||
.collect();
|
||||
let shared = std::env::args().any(|a| a == "--shared");
|
||||
let cpu = || {
|
||||
let stat = std::fs::read_to_string("/proc/self/stat").unwrap_or_default();
|
||||
let fields: Vec<u64> = stat
|
||||
.rsplit(')')
|
||||
.next()
|
||||
.unwrap_or_default()
|
||||
.split_whitespace()
|
||||
.skip(11)
|
||||
.take(2)
|
||||
.filter_map(|f| f.parse().ok())
|
||||
.collect();
|
||||
fields.iter().sum::<u64>()
|
||||
};
|
||||
let mut times = Vec::new();
|
||||
let count = 300;
|
||||
let cpu_before = cpu();
|
||||
for i in 0..count {
|
||||
let data = &frames[i % frames.len()];
|
||||
let frame = BgraFrame {
|
||||
data: &data[..],
|
||||
width: width as usize,
|
||||
height: height as usize,
|
||||
};
|
||||
let start = Instant::now();
|
||||
let _ = if shared {
|
||||
encoder.encode_shared(&frame, data)
|
||||
} else {
|
||||
encoder.encode(&frame)
|
||||
};
|
||||
times.push(start.elapsed().as_secs_f64() * 1000.0);
|
||||
}
|
||||
let ticks = cpu() - cpu_before;
|
||||
times.sort_by(f64::total_cmp);
|
||||
let hz = 100.0;
|
||||
println!(
|
||||
"{size} {} : call median {:.1} ms, p95 {:.1} ms; CPU {:.1} ms per image",
|
||||
codec.as_str(),
|
||||
times[times.len() / 2],
|
||||
times[times.len() * 95 / 100],
|
||||
ticks as f64 / hz * 1000.0 / count as f64
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "vaapi"))]
|
||||
fn main() {
|
||||
eprintln!("build with --features vaapi");
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
//! Splits the per-frame cost of the encoding thread into its stages (#86):
|
||||
//! BGRA to I420 conversion, then encoding, at a given size.
|
||||
//!
|
||||
//! cargo run --release -p rs-codec --example bench_stages -- 1920x1080 vp8 60
|
||||
//!
|
||||
//! The image moves a little every frame (a band of "text" scrolls), like a
|
||||
//! desktop being used: an immobile image would let the encoder skip almost
|
||||
//! everything and hide its real cost.
|
||||
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use rs_codec::{BgraFrame, EncodeConfig, VideoCodec, VideoEncoder, VpxEncoder, bgra_to_i420};
|
||||
|
||||
fn desktop_frame(width: usize, height: usize, frame: usize) -> Vec<u8> {
|
||||
let mut data = vec![0u8; width * height * 4];
|
||||
for y in 0..height {
|
||||
for x in 0..width {
|
||||
let i = (y * width + x) * 4;
|
||||
// Flat background with a scrolling band of fine "text" detail.
|
||||
let text_band = (height / 3..height / 3 + 200).contains(&y);
|
||||
let v = if text_band && ((x + frame * 3) % 7 < 2) && (y % 9 < 6) {
|
||||
20
|
||||
} else {
|
||||
235
|
||||
};
|
||||
data[i..i + 4].copy_from_slice(&[v, v, v.saturating_sub(10), 255]);
|
||||
}
|
||||
}
|
||||
data
|
||||
}
|
||||
|
||||
fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let mut args = std::env::args().skip(1);
|
||||
let size = args.next().unwrap_or_else(|| "1920x1080".into());
|
||||
let codec = match args.next().as_deref() {
|
||||
Some("vp9") => VideoCodec::Vp9,
|
||||
_ => VideoCodec::Vp8,
|
||||
};
|
||||
let fps: u8 = args.next().map_or(Ok(60), |f| f.parse())?;
|
||||
let (width, height) = size
|
||||
.split_once('x')
|
||||
.and_then(|(w, h)| Some((w.parse::<usize>().ok()?, h.parse::<usize>().ok()?)))
|
||||
.ok_or("size: WIDTHxHEIGHT")?;
|
||||
|
||||
let frames: Vec<Vec<u8>> = (0..30).map(|i| desktop_frame(width, height, i)).collect();
|
||||
let mut encoder = VpxEncoder::new(EncodeConfig {
|
||||
width: width as u32,
|
||||
height: height as u32,
|
||||
fps,
|
||||
bitrate_kbps: 8_000,
|
||||
codec,
|
||||
})?;
|
||||
|
||||
let rounds = 240;
|
||||
let mut i420 = Vec::new();
|
||||
let mut convert = Duration::ZERO;
|
||||
let mut encode = Duration::ZERO;
|
||||
for n in 0..rounds {
|
||||
let frame = BgraFrame::new(&frames[n % frames.len()], width, height)?;
|
||||
let start = Instant::now();
|
||||
bgra_to_i420(&frame, &mut i420);
|
||||
convert += start.elapsed();
|
||||
let start = Instant::now();
|
||||
// `encode` converts again internally: what it adds over the
|
||||
// conversion measured above is the encoder's own cost.
|
||||
let _ = encoder.encode(&frame);
|
||||
encode += start.elapsed();
|
||||
}
|
||||
let per = |d: Duration| d.as_secs_f64() * 1000.0 / rounds as f64;
|
||||
let convert_ms = per(convert);
|
||||
let total_ms = per(encode);
|
||||
println!(
|
||||
"{width}x{height} {} @{fps}: conversion {convert_ms:.2} ms, encoding {:.2} ms, \
|
||||
total {total_ms:.2} ms per frame (budget {:.2} ms)",
|
||||
codec.as_str(),
|
||||
total_ms - convert_ms,
|
||||
1000.0 / f64::from(fps)
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
+130
-28
@@ -5,7 +5,7 @@
|
||||
//! and nothing in the pipeline flags it. The coefficients are therefore fixed
|
||||
//! here, with tests on known colors.
|
||||
|
||||
/// BGRA image as the capture APIs deliver it (Windows, macOS, PipeWire).
|
||||
/// BGRA image as the capture APIs deliver it (Windows, PipeWire).
|
||||
pub struct BgraFrame<'a> {
|
||||
pub data: &'a [u8],
|
||||
pub width: usize,
|
||||
@@ -50,7 +50,11 @@ impl<'a> BgraFrame<'a> {
|
||||
/// Converts a BGRA image to I420 (full-size Y, U and V in 4:2:0).
|
||||
///
|
||||
/// `out` is reused from one frame to the next to avoid one allocation per
|
||||
/// image, which matters at 30 frames per second.
|
||||
/// image, which matters at 60 frames per second.
|
||||
///
|
||||
/// One pass over pairs of rows: each 2x2 block gives its four luma values and
|
||||
/// its chroma at once. Very large images are cut into bands of row pairs
|
||||
/// converted in parallel (see [`conversion_bands`]).
|
||||
pub fn bgra_to_i420(frame: &BgraFrame, out: &mut Vec<u8>) {
|
||||
let width = frame.width;
|
||||
let height = frame.height;
|
||||
@@ -61,43 +65,86 @@ pub fn bgra_to_i420(frame: &BgraFrame, out: &mut Vec<u8>) {
|
||||
|
||||
let (y_plane, rest) = out.split_at_mut(y_size);
|
||||
let (u_plane, v_plane) = rest.split_at_mut(chroma_size);
|
||||
let source = &frame.data[..y_size * 4];
|
||||
|
||||
for row in 0..height {
|
||||
let src_row = &frame.data[row * width * 4..(row + 1) * width * 4];
|
||||
for col in 0..width {
|
||||
let px = &src_row[col * 4..col * 4 + 4];
|
||||
let b = px[0] as i32;
|
||||
let g = px[1] as i32;
|
||||
let r = px[2] as i32;
|
||||
y_plane[row * width + col] = rgb_to_y(r, g, b);
|
||||
let pairs = height / 2;
|
||||
let bands = conversion_bands(width * height).min(pairs.max(1));
|
||||
let pairs_per_band = pairs.div_ceil(bands);
|
||||
std::thread::scope(|scope| {
|
||||
let mut source = source;
|
||||
let (mut y_rest, mut u_rest, mut v_rest) = (y_plane, u_plane, v_plane);
|
||||
while !source.is_empty() {
|
||||
let rows = (pairs_per_band * 2).min(source.len() / (width * 4));
|
||||
let (band, next) = source.split_at(rows * width * 4);
|
||||
let (y_band, y_next) = y_rest.split_at_mut(rows * width);
|
||||
let (u_band, u_next) = u_rest.split_at_mut(rows / 2 * width / 2);
|
||||
let (v_band, v_next) = v_rest.split_at_mut(rows / 2 * width / 2);
|
||||
(source, y_rest, u_rest, v_rest) = (next, y_next, u_next, v_next);
|
||||
if source.is_empty() {
|
||||
// The last band runs on this thread: one spawn fewer.
|
||||
convert_band(band, width, y_band, u_band, v_band);
|
||||
} else {
|
||||
scope.spawn(move || convert_band(band, width, y_band, u_band, v_band));
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Chroma: average of the four pixels of the 2x2 block, at full resolution.
|
||||
for row in (0..height).step_by(2) {
|
||||
for col in (0..width).step_by(2) {
|
||||
let mut sum_u = 0i32;
|
||||
let mut sum_v = 0i32;
|
||||
for dy in 0..2 {
|
||||
let src_row = &frame.data[(row + dy) * width * 4..(row + dy + 1) * width * 4];
|
||||
for dx in 0..2 {
|
||||
let px = &src_row[(col + dx) * 4..(col + dx) * 4 + 4];
|
||||
let b = px[0] as i32;
|
||||
let g = px[1] as i32;
|
||||
let r = px[2] as i32;
|
||||
/// Bands to cut an image of `pixels` into. One up to 2560x1440: measured at
|
||||
/// 1920x1080 (#86), four bands halve the conversion time but double the CPU
|
||||
/// the host burns, for a step that already fits the 60 fps budget. Beyond,
|
||||
/// one per core, at most four.
|
||||
fn conversion_bands(pixels: usize) -> usize {
|
||||
if pixels <= 2560 * 1440 {
|
||||
return 1;
|
||||
}
|
||||
std::thread::available_parallelism()
|
||||
.map(|n| n.get())
|
||||
.unwrap_or(1)
|
||||
.clamp(1, 4)
|
||||
}
|
||||
|
||||
/// Converts whole row pairs: `source` holds `y.len() / width` BGRA rows.
|
||||
fn convert_band(source: &[u8], width: usize, y: &mut [u8], u: &mut [u8], v: &mut [u8]) {
|
||||
let row_bytes = width * 4;
|
||||
let half = width / 2;
|
||||
for ((pair, y_pair), (u_row, v_row)) in source
|
||||
.chunks_exact(2 * row_bytes)
|
||||
.zip(y.chunks_exact_mut(2 * width))
|
||||
.zip(u.chunks_exact_mut(half).zip(v.chunks_exact_mut(half)))
|
||||
{
|
||||
let (top, bottom) = pair.split_at(row_bytes);
|
||||
let (y_top, y_bottom) = y_pair.split_at_mut(width);
|
||||
for (((top, bottom), (y_top, y_bottom)), (u_out, v_out)) in top
|
||||
.as_chunks::<8>()
|
||||
.0
|
||||
.iter()
|
||||
.zip(bottom.as_chunks::<8>().0)
|
||||
.zip(
|
||||
y_top
|
||||
.as_chunks_mut::<2>()
|
||||
.0
|
||||
.iter_mut()
|
||||
.zip(y_bottom.as_chunks_mut::<2>().0.iter_mut()),
|
||||
)
|
||||
.zip(u_row.iter_mut().zip(v_row.iter_mut()))
|
||||
{
|
||||
let mut sum_u = 0;
|
||||
let mut sum_v = 0;
|
||||
for (pixels, luma) in [(top, y_top), (bottom, y_bottom)] {
|
||||
for (px, out) in pixels.as_chunks::<4>().0.iter().zip(luma.iter_mut()) {
|
||||
let (b, g, r) = (i32::from(px[0]), i32::from(px[1]), i32::from(px[2]));
|
||||
*out = rgb_to_y(r, g, b);
|
||||
sum_u += rgb_to_u(r, g, b);
|
||||
sum_v += rgb_to_v(r, g, b);
|
||||
}
|
||||
}
|
||||
let index = (row / 2) * (width / 2) + (col / 2);
|
||||
u_plane[index] = ((sum_u + 2) / 4).clamp(0, 255) as u8;
|
||||
v_plane[index] = ((sum_v + 2) / 4).clamp(0, 255) as u8;
|
||||
*u_out = ((sum_u + 2) / 4).clamp(0, 255) as u8;
|
||||
*v_out = ((sum_v + 2) / 4).clamp(0, 255) as u8;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Y in BT.709, limited range (16 to 235).
|
||||
#[inline]
|
||||
fn rgb_to_y(r: i32, g: i32, b: i32) -> u8 {
|
||||
(((47 * r + 157 * g + 16 * b + 128) >> 8) + 16).clamp(0, 255) as u8
|
||||
}
|
||||
@@ -132,6 +179,61 @@ pub enum ColorError {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// The straightforward conversion this module used before #86, kept as
|
||||
/// the reference the fast one must match byte for byte.
|
||||
fn reference_i420(frame: &BgraFrame) -> Vec<u8> {
|
||||
let (width, height) = (frame.width, frame.height);
|
||||
let mut out = vec![0; width * height * 3 / 2];
|
||||
let (y_plane, rest) = out.split_at_mut(width * height);
|
||||
let (u_plane, v_plane) = rest.split_at_mut(width * height / 4);
|
||||
let pixel = |row: usize, col: usize| {
|
||||
let i = (row * width + col) * 4;
|
||||
let p = &frame.data[i..i + 4];
|
||||
(i32::from(p[2]), i32::from(p[1]), i32::from(p[0]))
|
||||
};
|
||||
for row in 0..height {
|
||||
for col in 0..width {
|
||||
let (r, g, b) = pixel(row, col);
|
||||
y_plane[row * width + col] = rgb_to_y(r, g, b);
|
||||
}
|
||||
}
|
||||
for row in (0..height).step_by(2) {
|
||||
for col in (0..width).step_by(2) {
|
||||
let (mut su, mut sv) = (0, 0);
|
||||
for (dy, dx) in [(0, 0), (0, 1), (1, 0), (1, 1)] {
|
||||
let (r, g, b) = pixel(row + dy, col + dx);
|
||||
su += rgb_to_u(r, g, b);
|
||||
sv += rgb_to_v(r, g, b);
|
||||
}
|
||||
let index = (row / 2) * (width / 2) + col / 2;
|
||||
u_plane[index] = ((su + 2) / 4).clamp(0, 255) as u8;
|
||||
v_plane[index] = ((sv + 2) / 4).clamp(0, 255) as u8;
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_fast_conversion_matches_the_reference_byte_for_byte() {
|
||||
// Parallel bands at 1920x1080, a single band at 320x240, and a height
|
||||
// that does not split evenly into bands.
|
||||
for (width, height) in [(1920, 1080), (320, 240), (1282, 722)] {
|
||||
let mut state = 0x2545_f491_u32;
|
||||
let data: Vec<u8> = (0..width * height * 4)
|
||||
.map(|_| {
|
||||
state ^= state << 13;
|
||||
state ^= state >> 17;
|
||||
state ^= state << 5;
|
||||
state as u8
|
||||
})
|
||||
.collect();
|
||||
let frame = BgraFrame::new(&data, width, height).unwrap();
|
||||
let mut fast = Vec::new();
|
||||
bgra_to_i420(&frame, &mut fast);
|
||||
assert!(fast == reference_i420(&frame), "{width}x{height}");
|
||||
}
|
||||
}
|
||||
|
||||
fn solid(width: usize, height: usize, b: u8, g: u8, r: u8) -> Vec<u8> {
|
||||
let mut data = Vec::with_capacity(width * height * 4);
|
||||
for _ in 0..width * height {
|
||||
|
||||
@@ -20,6 +20,8 @@ pub enum VideoCodec {
|
||||
#[default]
|
||||
Vp8,
|
||||
Vp9,
|
||||
/// Hardware only (#57): constrained baseline, Annex B.
|
||||
H264,
|
||||
}
|
||||
|
||||
impl VideoCodec {
|
||||
@@ -27,6 +29,7 @@ impl VideoCodec {
|
||||
match self {
|
||||
Self::Vp8 => "vp8",
|
||||
Self::Vp9 => "vp9",
|
||||
Self::H264 => "h264",
|
||||
}
|
||||
}
|
||||
|
||||
@@ -35,6 +38,7 @@ impl VideoCodec {
|
||||
match self {
|
||||
Self::Vp8 => "VP8",
|
||||
Self::Vp9 => "VP9",
|
||||
Self::H264 => "H264",
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -46,7 +50,10 @@ impl std::str::FromStr for VideoCodec {
|
||||
match value.to_ascii_lowercase().as_str() {
|
||||
"vp8" => Ok(Self::Vp8),
|
||||
"vp9" => Ok(Self::Vp9),
|
||||
other => Err(format!("unknown codec: {other} (expected: vp8 or vp9)")),
|
||||
"h264" => Ok(Self::H264),
|
||||
other => Err(format!(
|
||||
"unknown codec: {other} (expected: vp8, vp9 or h264)"
|
||||
)),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -78,6 +85,17 @@ pub enum EncodeError {
|
||||
pub trait VideoEncoder: Send {
|
||||
/// Encodes a BGRA image and returns the packets produced.
|
||||
fn encode(&mut self, frame: &BgraFrame) -> Result<Vec<Vec<u8>>, EncodeError>;
|
||||
/// The same, when the image is a shared buffer (the capture's): an
|
||||
/// encoder that hands the image to another component, like the GPU's,
|
||||
/// can keep a reference instead of copying 8 MB per 1080p image (#57).
|
||||
fn encode_shared(
|
||||
&mut self,
|
||||
frame: &BgraFrame,
|
||||
shared: &std::sync::Arc<Vec<u8>>,
|
||||
) -> Result<Vec<Vec<u8>>, EncodeError> {
|
||||
let _ = shared;
|
||||
self.encode(frame)
|
||||
}
|
||||
/// Forces a keyframe on the next frame (new viewer, resume).
|
||||
fn request_keyframe(&mut self);
|
||||
fn config(&self) -> EncodeConfig;
|
||||
@@ -87,6 +105,33 @@ pub trait VideoEncoder: Send {
|
||||
fn reconfigure(&mut self, width: u32, height: u32) -> Result<(), EncodeError>;
|
||||
}
|
||||
|
||||
/// The encoder chosen at runtime, libvpx or the GPU's (#57).
|
||||
impl VideoEncoder for Box<dyn VideoEncoder> {
|
||||
fn encode(&mut self, frame: &BgraFrame) -> Result<Vec<Vec<u8>>, EncodeError> {
|
||||
(**self).encode(frame)
|
||||
}
|
||||
|
||||
fn encode_shared(
|
||||
&mut self,
|
||||
frame: &BgraFrame,
|
||||
shared: &std::sync::Arc<Vec<u8>>,
|
||||
) -> Result<Vec<Vec<u8>>, EncodeError> {
|
||||
(**self).encode_shared(frame, shared)
|
||||
}
|
||||
|
||||
fn request_keyframe(&mut self) {
|
||||
(**self).request_keyframe();
|
||||
}
|
||||
|
||||
fn config(&self) -> EncodeConfig {
|
||||
(**self).config()
|
||||
}
|
||||
|
||||
fn reconfigure(&mut self, width: u32, height: u32) -> Result<(), EncodeError> {
|
||||
(**self).reconfigure(width, height)
|
||||
}
|
||||
}
|
||||
|
||||
/// Real-time libvpx encoder, VP8 or VP9.
|
||||
pub struct VpxEncoder {
|
||||
inner: Context,
|
||||
@@ -282,6 +327,7 @@ mod tests {
|
||||
let key = match codec {
|
||||
VideoCodec::Vp8 => vp8_key(&packets[0]),
|
||||
VideoCodec::Vp9 => vp9_key(&packets[0]),
|
||||
VideoCodec::H264 => unreachable!("libvpx codecs only"),
|
||||
};
|
||||
assert!(key, "{codec:?}: the first image is a keyframe");
|
||||
}
|
||||
@@ -298,6 +344,7 @@ mod tests {
|
||||
let key = |p: &[u8]| match codec {
|
||||
VideoCodec::Vp8 => vp8_key(p),
|
||||
VideoCodec::Vp9 => vp9_key(p),
|
||||
VideoCodec::H264 => unreachable!("libvpx codecs only"),
|
||||
};
|
||||
for _ in 0..3 {
|
||||
encoder.encode(&frame).unwrap();
|
||||
@@ -352,7 +399,8 @@ mod tests {
|
||||
fn the_codec_name_parses_both_ways() {
|
||||
assert_eq!("vp8".parse::<VideoCodec>(), Ok(VideoCodec::Vp8));
|
||||
assert_eq!("VP9".parse::<VideoCodec>(), Ok(VideoCodec::Vp9));
|
||||
assert!("h264".parse::<VideoCodec>().is_err());
|
||||
assert_eq!("h264".parse::<VideoCodec>(), Ok(VideoCodec::H264));
|
||||
assert!("av1".parse::<VideoCodec>().is_err());
|
||||
assert_eq!(VideoCodec::Vp9.rtp_name(), "VP9");
|
||||
}
|
||||
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
//! screen or a GPU.
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::time::Instant;
|
||||
|
||||
/// Cadence and content of a video source.
|
||||
///
|
||||
@@ -18,6 +19,17 @@ pub trait FrameSource: Send {
|
||||
fn next_frame(&mut self) -> Arc<[u8]>;
|
||||
/// Number of frames already served, for statistics.
|
||||
fn served(&self) -> u64;
|
||||
/// Capture instant of the frame `next_frame` last returned, when known.
|
||||
/// The session derives the RTP timestamp from it, so that an irregular
|
||||
/// cadence (unchanged frames skipped) stays true to real time (#86).
|
||||
fn captured_at(&self) -> Option<Instant> {
|
||||
None
|
||||
}
|
||||
/// Changes when a new frame is ready, for a session to send it at once
|
||||
/// instead of polling at the frame rate (#86). `None`: poll.
|
||||
fn frames_ready(&self) -> Option<tokio::sync::watch::Receiver<u64>> {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// A media source shareable between several sessions.
|
||||
|
||||
@@ -0,0 +1,408 @@
|
||||
//! Hardware encoding through VA-API (#57), H.264 or VP9.
|
||||
//!
|
||||
//! libvpx costs more than two cores for 1080p60 on the development machine; the
|
||||
//! GPU's encoder does the same work for almost nothing (measures in
|
||||
//! `docs/perf.md`). GStreamer drives it: the BGRA image goes in through an
|
||||
//! `appsrc`, `vapostproc` converts it to NV12 on the GPU, the low-power encoder
|
||||
//! (`vah264lpenc`, `vavp9lpenc`) compresses it, and the access unit comes out
|
||||
//! of an `appsink`, one call to [`VideoEncoder::encode`] per image like
|
||||
//! libvpx: no queue, no B-frame, a keyframe on request.
|
||||
//!
|
||||
//! What GStreamer needs is found at runtime: its `va` plugin and the GPU's
|
||||
//! VA-API driver. [`HardwareEncoder::new`] fails cleanly without them, and the
|
||||
//! caller falls back on libvpx.
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use gstreamer as gst;
|
||||
use gstreamer::prelude::*;
|
||||
use gstreamer_app as gst_app;
|
||||
|
||||
use crate::color::BgraFrame;
|
||||
use crate::encoder::{EncodeConfig, EncodeError, VideoCodec, VideoEncoder};
|
||||
|
||||
/// How long an image may take through the GPU before it counts as lost. A
|
||||
/// low-power encoder answers within a few milliseconds; a frozen driver must
|
||||
/// not freeze the capture thread.
|
||||
const PULL_TIMEOUT: Duration = Duration::from_millis(500);
|
||||
|
||||
/// Seconds between two periodic keyframes, as libvpx does: a viewer that lost
|
||||
/// a packet recovers within that delay even without asking.
|
||||
const KEYFRAME_INTERVAL_S: u32 = 5;
|
||||
|
||||
pub struct HardwareEncoder {
|
||||
pipeline: gst::Pipeline,
|
||||
source: gst_app::AppSrc,
|
||||
sink: gst_app::AppSink,
|
||||
config: EncodeConfig,
|
||||
frames: u64,
|
||||
keyframe_requested: bool,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for HardwareEncoder {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("HardwareEncoder")
|
||||
.field("config", &self.config)
|
||||
.finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
impl HardwareEncoder {
|
||||
/// Opens the GPU encoder for `config.codec`. VP8 has no VA-API encoder on
|
||||
/// current GPUs: it is refused, like a machine without the plugin.
|
||||
pub fn new(config: EncodeConfig) -> Result<Self, EncodeError> {
|
||||
gst::init().map_err(|e| EncodeError::Init(format!("GStreamer: {e}")))?;
|
||||
let description = pipeline_description(&config)?;
|
||||
let pipeline = gst::parse::launch(&description)
|
||||
.map_err(|e| EncodeError::Init(format!("VA-API pipeline: {e}")))?
|
||||
.downcast::<gst::Pipeline>()
|
||||
.map_err(|_| EncodeError::Init("VA-API pipeline: not a pipeline".into()))?;
|
||||
let source = element::<gst_app::AppSrc>(&pipeline, "source")?;
|
||||
let sink = element::<gst_app::AppSink>(&pipeline, "sink")?;
|
||||
pipeline
|
||||
.set_state(gst::State::Playing)
|
||||
.map_err(|e| EncodeError::Init(format!("VA-API pipeline cannot start: {e}")))?;
|
||||
let encoder = Self {
|
||||
pipeline,
|
||||
source,
|
||||
sink,
|
||||
config,
|
||||
frames: 0,
|
||||
keyframe_requested: false,
|
||||
};
|
||||
// A missing driver often shows only once the pipeline runs: the
|
||||
// error is on the bus right away.
|
||||
encoder.check_bus()?;
|
||||
Ok(encoder)
|
||||
}
|
||||
|
||||
/// Tells whether this machine can encode `codec` on its GPU, without
|
||||
/// keeping anything open. For the diagnostics and the interface.
|
||||
pub fn available(codec: VideoCodec) -> bool {
|
||||
let probe = EncodeConfig {
|
||||
width: 64,
|
||||
height: 64,
|
||||
fps: 30,
|
||||
bitrate_kbps: 500,
|
||||
codec,
|
||||
};
|
||||
let Ok(mut encoder) = Self::new(probe) else {
|
||||
return false;
|
||||
};
|
||||
let black = vec![0u8; 64 * 64 * 4];
|
||||
let frame = BgraFrame {
|
||||
data: &black,
|
||||
width: 64,
|
||||
height: 64,
|
||||
};
|
||||
encoder.encode(&frame).is_ok()
|
||||
}
|
||||
|
||||
fn check_bus(&self) -> Result<(), EncodeError> {
|
||||
let Some(bus) = self.pipeline.bus() else {
|
||||
return Ok(());
|
||||
};
|
||||
while let Some(message) = bus.pop_filtered(&[gst::MessageType::Error]) {
|
||||
if let gst::MessageView::Error(error) = message.view() {
|
||||
return Err(EncodeError::Encode(format!(
|
||||
"VA-API: {} ({})",
|
||||
error.error(),
|
||||
error.debug().unwrap_or_default()
|
||||
)));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn timestamp(&self) -> gst::ClockTime {
|
||||
let fps = u64::from(self.config.fps.max(1));
|
||||
gst::ClockTime::from_nseconds(self.frames * 1_000_000_000 / fps)
|
||||
}
|
||||
}
|
||||
|
||||
/// A shared image, as GStreamer memory: the buffer keeps the reference, the
|
||||
/// capture keeps its own, nobody copies.
|
||||
struct SharedImage(Arc<Vec<u8>>);
|
||||
|
||||
impl AsRef<[u8]> for SharedImage {
|
||||
fn as_ref(&self) -> &[u8] {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl VideoEncoder for HardwareEncoder {
|
||||
fn encode(&mut self, frame: &BgraFrame) -> Result<Vec<Vec<u8>>, EncodeError> {
|
||||
self.push_and_pull(frame, || gst::Buffer::from_mut_slice(frame.data.to_vec()))
|
||||
}
|
||||
|
||||
fn encode_shared(
|
||||
&mut self,
|
||||
frame: &BgraFrame,
|
||||
shared: &Arc<Vec<u8>>,
|
||||
) -> Result<Vec<Vec<u8>>, EncodeError> {
|
||||
if shared.len() != frame.data.len() {
|
||||
return self.encode(frame);
|
||||
}
|
||||
let image = SharedImage(shared.clone());
|
||||
self.push_and_pull(frame, move || gst::Buffer::from_slice(image))
|
||||
}
|
||||
|
||||
fn request_keyframe(&mut self) {
|
||||
self.keyframe_requested = true;
|
||||
}
|
||||
|
||||
fn config(&self) -> EncodeConfig {
|
||||
self.config
|
||||
}
|
||||
|
||||
fn reconfigure(&mut self, width: u32, height: u32) -> Result<(), EncodeError> {
|
||||
// A new pipeline at the new size, opened before the old one goes: a
|
||||
// failure leaves the stream as it was. Its first image is a keyframe.
|
||||
let config = EncodeConfig {
|
||||
width,
|
||||
height,
|
||||
..self.config
|
||||
};
|
||||
*self = Self::new(config)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl HardwareEncoder {
|
||||
/// Pushes one image, made into a buffer by `buffer`, and takes the access
|
||||
/// unit it gives.
|
||||
fn push_and_pull(
|
||||
&mut self,
|
||||
frame: &BgraFrame,
|
||||
buffer: impl FnOnce() -> gst::Buffer,
|
||||
) -> Result<Vec<Vec<u8>>, EncodeError> {
|
||||
let expected = self.config.width as usize * self.config.height as usize * 4;
|
||||
if frame.data.len() != expected {
|
||||
return Err(EncodeError::Encode(format!(
|
||||
"image of {} bytes for a {}x{} encoder",
|
||||
frame.data.len(),
|
||||
self.config.width,
|
||||
self.config.height
|
||||
)));
|
||||
}
|
||||
if std::mem::take(&mut self.keyframe_requested) {
|
||||
// In stream order, before the image it applies to.
|
||||
let event = gstreamer_video::DownstreamForceKeyUnitEvent::builder()
|
||||
.all_headers(true)
|
||||
.build();
|
||||
self.source.send_event(event);
|
||||
}
|
||||
let mut buffer = buffer();
|
||||
{
|
||||
let buffer = buffer.get_mut().ok_or(EncodeError::NoFrame)?;
|
||||
let pts = self.timestamp();
|
||||
buffer.set_pts(pts);
|
||||
buffer.set_duration(gst::ClockTime::from_nseconds(
|
||||
1_000_000_000 / u64::from(self.config.fps.max(1)),
|
||||
));
|
||||
}
|
||||
self.frames += 1;
|
||||
self.source
|
||||
.push_buffer(buffer)
|
||||
.map_err(|e| EncodeError::Encode(format!("VA-API: {e:?}")))?;
|
||||
|
||||
let mut packets = Vec::new();
|
||||
let mut wait = gst::ClockTime::from_nseconds(PULL_TIMEOUT.as_nanos() as u64);
|
||||
// One access unit per image; any other ready one is taken as well,
|
||||
// without waiting.
|
||||
while let Some(sample) = self.sink.try_pull_sample(wait) {
|
||||
wait = gst::ClockTime::ZERO;
|
||||
let Some(buffer) = sample.buffer() else {
|
||||
continue;
|
||||
};
|
||||
let map = buffer
|
||||
.map_readable()
|
||||
.map_err(|_| EncodeError::Encode("VA-API: unreadable buffer".into()))?;
|
||||
packets.push(map.as_slice().to_vec());
|
||||
}
|
||||
if packets.is_empty() {
|
||||
self.check_bus()?;
|
||||
return Err(EncodeError::NoFrame);
|
||||
}
|
||||
Ok(packets)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for HardwareEncoder {
|
||||
fn drop(&mut self) {
|
||||
let _ = self.pipeline.set_state(gst::State::Null);
|
||||
}
|
||||
}
|
||||
|
||||
fn element<T: IsA<gst::Element>>(pipeline: &gst::Pipeline, name: &str) -> Result<T, EncodeError> {
|
||||
pipeline
|
||||
.by_name(name)
|
||||
.and_then(|e| e.downcast::<T>().ok())
|
||||
.ok_or_else(|| EncodeError::Init(format!("VA-API pipeline: no {name}")))
|
||||
}
|
||||
|
||||
/// The pipeline for `config`. Low latency everywhere: a live source, no
|
||||
/// B-frame, a single reference, a short rate-control buffer, an appsink that
|
||||
/// does not sync on a clock.
|
||||
fn pipeline_description(config: &EncodeConfig) -> Result<String, EncodeError> {
|
||||
let fps = u32::from(config.fps.max(1));
|
||||
let keyframes = fps * KEYFRAME_INTERVAL_S;
|
||||
// Half a second of buffer, like the libvpx settings: rate spikes stay
|
||||
// short, so does the latency they cause.
|
||||
let cpb = config.bitrate_kbps / 2;
|
||||
let encoder = match config.codec {
|
||||
// Constrained baseline: what every WebRTC browser decodes, hardware
|
||||
// decoders of phones included. Annex B byte stream, one access unit
|
||||
// per buffer, SPS and PPS before every keyframe.
|
||||
VideoCodec::H264 => format!(
|
||||
"vah264lpenc bitrate={bitrate} rate-control=cbr cpb-size={cpb} \
|
||||
key-int-max={keyframes} b-frames=0 ref-frames=1 cabac=false \
|
||||
! video/x-h264,profile=constrained-baseline \
|
||||
! h264parse config-interval=-1 \
|
||||
! video/x-h264,stream-format=byte-stream,alignment=au",
|
||||
bitrate = config.bitrate_kbps,
|
||||
),
|
||||
VideoCodec::Vp9 => format!(
|
||||
"vavp9lpenc bitrate={bitrate} rate-control=cbr cpb-size={cpb} \
|
||||
key-int-max={keyframes} ref-frames=1 \
|
||||
! video/x-vp9",
|
||||
bitrate = config.bitrate_kbps,
|
||||
),
|
||||
VideoCodec::Vp8 => {
|
||||
return Err(EncodeError::Init(
|
||||
"no VA-API encoder for VP8: use libvpx".into(),
|
||||
));
|
||||
}
|
||||
};
|
||||
Ok(format!(
|
||||
"appsrc name=source is-live=true format=time do-timestamp=false block=false \
|
||||
caps=video/x-raw,format=BGRA,width={width},height={height},framerate={fps}/1 \
|
||||
! vapostproc ! video/x-raw(memory:VAMemory),format=NV12 \
|
||||
! {encoder} \
|
||||
! appsink name=sink sync=false max-buffers=8 drop=false",
|
||||
width = config.width,
|
||||
height = config.height,
|
||||
))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn config(codec: VideoCodec) -> EncodeConfig {
|
||||
EncodeConfig {
|
||||
width: 320,
|
||||
height: 240,
|
||||
fps: 30,
|
||||
bitrate_kbps: 1000,
|
||||
codec,
|
||||
}
|
||||
}
|
||||
|
||||
/// Bars that move, so that the encoder has something to say.
|
||||
fn image(width: usize, height: usize, shift: usize) -> Vec<u8> {
|
||||
let mut data = vec![0u8; width * height * 4];
|
||||
for (i, pixel) in data.as_chunks_mut::<4>().0.iter_mut().enumerate() {
|
||||
let x = (i % width + shift) % width;
|
||||
pixel.copy_from_slice(&[(x * 255 / width) as u8, 128, 255 - (x as u8), 255]);
|
||||
}
|
||||
data
|
||||
}
|
||||
|
||||
/// Runs only where the GPU answers: elsewhere (CI runner, sandbox) there
|
||||
/// is nothing to check, and the fallback is tested by the caller.
|
||||
fn encoder(codec: VideoCodec) -> Option<HardwareEncoder> {
|
||||
match HardwareEncoder::new(config(codec)) {
|
||||
Ok(encoder) => Some(encoder),
|
||||
Err(error) => {
|
||||
eprintln!("no VA-API {}: {error}, test skipped", codec.as_str());
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn h264_comes_out_as_annex_b_with_its_parameters_and_a_keyframe_on_request() {
|
||||
let Some(mut encoder) = encoder(VideoCodec::H264) else {
|
||||
return;
|
||||
};
|
||||
let mut units = Vec::new();
|
||||
for i in 0..10 {
|
||||
if i == 5 {
|
||||
encoder.request_keyframe();
|
||||
}
|
||||
let data = image(320, 240, i * 7);
|
||||
let frame = BgraFrame {
|
||||
data: &data,
|
||||
width: 320,
|
||||
height: 240,
|
||||
};
|
||||
match encoder.encode(&frame) {
|
||||
Ok(packets) => units.extend(packets),
|
||||
Err(EncodeError::NoFrame) => {}
|
||||
Err(e) => panic!("{e}"),
|
||||
}
|
||||
}
|
||||
assert!(
|
||||
units.len() >= 8,
|
||||
"{} access units for 10 images",
|
||||
units.len()
|
||||
);
|
||||
let nal_types = |unit: &[u8]| -> Vec<u8> {
|
||||
unit.windows(4)
|
||||
.enumerate()
|
||||
.filter(|(_, w)| w[..3] == [0, 0, 1] || *w == [0, 0, 0, 1])
|
||||
.filter_map(|(i, w)| {
|
||||
let start = i + if w[2] == 1 { 3 } else { 4 };
|
||||
unit.get(start).map(|b| b & 0x1f)
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
// SPS (7), PPS (8) and an IDR slice (5) in the first unit.
|
||||
let first = nal_types(&units[0]);
|
||||
assert!(
|
||||
first.contains(&7) && first.contains(&8) && first.contains(&5),
|
||||
"{first:?}"
|
||||
);
|
||||
// And again for the requested keyframe, a few units later.
|
||||
let idr = units[1..]
|
||||
.iter()
|
||||
.filter(|u| nal_types(u).contains(&5))
|
||||
.count();
|
||||
assert!(idr >= 1, "no keyframe after the request");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vp9_produces_frames_and_follows_a_new_size() {
|
||||
let Some(mut encoder) = encoder(VideoCodec::Vp9) else {
|
||||
return;
|
||||
};
|
||||
let data = image(320, 240, 0);
|
||||
let frame = BgraFrame {
|
||||
data: &data,
|
||||
width: 320,
|
||||
height: 240,
|
||||
};
|
||||
let packets = encoder.encode(&frame).expect("a VP9 frame");
|
||||
// An uncompressed VP9 header starts with the frame marker 0b10.
|
||||
assert_eq!(packets[0][0] >> 6, 0b10);
|
||||
encoder.reconfigure(640, 360).expect("new size");
|
||||
let bigger = image(640, 360, 0);
|
||||
let frame = BgraFrame {
|
||||
data: &bigger,
|
||||
width: 640,
|
||||
height: 360,
|
||||
};
|
||||
assert!(encoder.encode(&frame).is_ok());
|
||||
assert_eq!(encoder.config().width, 640);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vp8_is_refused_rather_than_mislabelled() {
|
||||
assert!(matches!(
|
||||
HardwareEncoder::new(config(VideoCodec::Vp8)),
|
||||
Err(EncodeError::Init(_))
|
||||
));
|
||||
}
|
||||
}
|
||||
@@ -5,20 +5,30 @@
|
||||
//! libvpx through a direct binding), and the result comes out through the
|
||||
//! [`FrameSource`] trait consumed by `rs-rtc` ([`pipeline`] bridges the two).
|
||||
//!
|
||||
//! The hardware H.264 encoder will come behind the same trait, without
|
||||
//! touching the rest of the pipeline (issue #53).
|
||||
//! The hardware encoder ([`hardware`], `vaapi` feature, #57) sits behind the
|
||||
//! same trait: H.264 or VP9 on the GPU through VA-API, without touching the
|
||||
//! rest of the pipeline. Under Windows, [`media_foundation`] does the same
|
||||
//! with the GPU's Media Foundation transform (#95).
|
||||
//!
|
||||
//! Build dependency: libvpx. See `scripts/build-libvpx.sh` and AGENTS.md.
|
||||
|
||||
pub mod color;
|
||||
pub mod encoder;
|
||||
pub mod frame;
|
||||
#[cfg(feature = "vaapi")]
|
||||
pub mod hardware;
|
||||
pub mod ivf;
|
||||
#[cfg(windows)]
|
||||
pub mod media_foundation;
|
||||
pub mod pipeline;
|
||||
mod vpx;
|
||||
|
||||
pub use color::{BgraFrame, ColorError, bgra_to_i420};
|
||||
pub use encoder::{EncodeConfig, EncodeError, VideoCodec, VideoEncoder, VpxEncoder};
|
||||
pub use frame::{FrameSource, SharedFrames, SharedMedia, SharedPlayback, SyntheticFrames};
|
||||
#[cfg(feature = "vaapi")]
|
||||
pub use hardware::HardwareEncoder;
|
||||
pub use ivf::{IvfError, IvfFile};
|
||||
#[cfg(windows)]
|
||||
pub use media_foundation::MediaFoundationEncoder;
|
||||
pub use pipeline::{LiveSource, LiveStats, SourceView};
|
||||
@@ -0,0 +1,910 @@
|
||||
//! Hardware encoding under Windows through Media Foundation (#95), H.264.
|
||||
//!
|
||||
//! The Windows counterpart of [`crate::hardware`] (VA-API): the GPU's encoder
|
||||
//! is a Media Foundation transform (MFT) registered by its driver, Intel Quick
|
||||
//! Sync, NVIDIA NVENC or AMD AMF. It is found by [`MFTEnumEx`], set to low
|
||||
//! latency (no B-frame, one output per input, constant bitrate), and fed NV12:
|
||||
//! the BGRA image is converted on the processor, in BT.709 like the libvpx
|
||||
//! path, then interleaved.
|
||||
//!
|
||||
//! Hardware transforms are asynchronous: they say when they want an image
|
||||
//! (`METransformNeedInput`) and when an access unit is ready
|
||||
//! (`METransformHaveOutput`). Software ones are synchronous: input, then output
|
||||
//! until they ask for more. Both are driven here, the second for the tests
|
||||
//! under Wine, whose H.264 transform runs on GStreamer, and for
|
||||
//! [`MediaFoundationEncoder::software`].
|
||||
//!
|
||||
//! Without a hardware transform, [`MediaFoundationEncoder::new`] fails
|
||||
//! cleanly, and the caller falls back on libvpx.
|
||||
|
||||
use std::mem::ManuallyDrop;
|
||||
use std::sync::OnceLock;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use windows::Win32::Foundation::VARIANT_BOOL;
|
||||
use windows::Win32::Media::MediaFoundation::{
|
||||
CODECAPI_AVEncCommonMeanBitRate, CODECAPI_AVEncCommonRateControlMode,
|
||||
CODECAPI_AVEncH264CABACEnable, CODECAPI_AVEncMPVDefaultBPictureCount, CODECAPI_AVEncMPVGOPSize,
|
||||
CODECAPI_AVEncVideoForceKeyFrame, CODECAPI_AVLowLatencyMode, ICodecAPI, IMFActivate,
|
||||
IMFMediaEventGenerator, IMFMediaType, IMFSample, IMFTransform, METransformHaveOutput,
|
||||
METransformNeedInput, MF_E_NO_EVENTS_AVAILABLE, MF_E_NOTACCEPTING,
|
||||
MF_E_TRANSFORM_NEED_MORE_INPUT, MF_E_TRANSFORM_STREAM_CHANGE, MF_EVENT_FLAG_NO_WAIT,
|
||||
MF_EVENT_TYPE, MF_LOW_LATENCY, MF_MT_AVG_BITRATE, MF_MT_FRAME_RATE, MF_MT_FRAME_SIZE,
|
||||
MF_MT_INTERLACE_MODE, MF_MT_MAJOR_TYPE, MF_MT_MPEG_SEQUENCE_HEADER, MF_MT_MPEG2_PROFILE,
|
||||
MF_MT_PIXEL_ASPECT_RATIO, MF_MT_SUBTYPE, MF_MT_VIDEO_NOMINAL_RANGE, MF_MT_YUV_MATRIX,
|
||||
MF_TRANSFORM_ASYNC, MF_TRANSFORM_ASYNC_UNLOCK, MF_VERSION, MFCreateMediaType,
|
||||
MFCreateMemoryBuffer, MFCreateSample, MFMediaType_Video, MFNominalRange_16_235, MFSTARTUP_LITE,
|
||||
MFSampleExtension_CleanPoint, MFStartup, MFT_CATEGORY_VIDEO_ENCODER, MFT_ENUM_FLAG,
|
||||
MFT_ENUM_FLAG_HARDWARE, MFT_ENUM_FLAG_SORTANDFILTER, MFT_ENUM_FLAG_SYNCMFT,
|
||||
MFT_ENUM_HARDWARE_URL_Attribute, MFT_FRIENDLY_NAME_Attribute,
|
||||
MFT_MESSAGE_NOTIFY_BEGIN_STREAMING, MFT_MESSAGE_NOTIFY_START_OF_STREAM, MFT_OUTPUT_DATA_BUFFER,
|
||||
MFT_OUTPUT_STREAM_PROVIDES_SAMPLES, MFT_REGISTER_TYPE_INFO, MFTEnumEx, MFVideoFormat_H264,
|
||||
MFVideoFormat_NV12, MFVideoInterlace_Progressive, MFVideoTransferMatrix_BT709,
|
||||
eAVEncCommonRateControlMode_CBR, eAVEncH264VProfile_Base, eAVEncH264VProfile_ConstrainedBase,
|
||||
};
|
||||
use windows::Win32::System::Com::{CoIncrementMTAUsage, CoTaskMemFree};
|
||||
use windows::Win32::System::Variant::{
|
||||
VARIANT, VARIANT_0, VARIANT_0_0, VARIANT_0_0_0, VT_BOOL, VT_UI4,
|
||||
};
|
||||
use windows::core::{GUID, Interface, PWSTR};
|
||||
|
||||
use crate::color::{BgraFrame, bgra_to_i420};
|
||||
use crate::encoder::{EncodeConfig, EncodeError, VideoCodec, VideoEncoder};
|
||||
|
||||
/// How long an image may take through the GPU before it counts as lost, as
|
||||
/// with VA-API: a frozen driver must not freeze the capture thread.
|
||||
const PULL_TIMEOUT: Duration = Duration::from_millis(500);
|
||||
|
||||
/// Seconds between two periodic keyframes, as libvpx and VA-API do.
|
||||
const KEYFRAME_INTERVAL_S: u32 = 5;
|
||||
|
||||
/// Media Foundation time unit: 100 ns.
|
||||
const TICKS_PER_SECOND: i64 = 10_000_000;
|
||||
|
||||
pub struct MediaFoundationEncoder {
|
||||
activate: IMFActivate,
|
||||
transform: IMFTransform,
|
||||
/// Present for an asynchronous (hardware) transform.
|
||||
events: Option<IMFMediaEventGenerator>,
|
||||
/// Keyframes on request and rate control; some transforms lack it.
|
||||
codec_api: Option<ICodecAPI>,
|
||||
input_stream: u32,
|
||||
output_stream: u32,
|
||||
/// Output buffer we lend the transform, when it does not bring its own.
|
||||
output_sample: Option<IMFSample>,
|
||||
/// `METransformNeedInput` received and not yet answered.
|
||||
input_wanted: u32,
|
||||
/// SPS and PPS, put back before a keyframe that comes without them.
|
||||
sequence_header: Option<Vec<u8>>,
|
||||
config: EncodeConfig,
|
||||
software: bool,
|
||||
name: String,
|
||||
frames: u64,
|
||||
keyframe_requested: bool,
|
||||
i420: Vec<u8>,
|
||||
}
|
||||
|
||||
// SAFETY: COM runs in the process's multithreaded apartment (`com_ready`),
|
||||
// and the transforms Media Foundation hands out are free-threaded. The encoder
|
||||
// is used by one thread at a time: created by the session, then moved into
|
||||
// the encoding thread (`LiveSource::spawn`).
|
||||
unsafe impl Send for MediaFoundationEncoder {}
|
||||
|
||||
impl std::fmt::Debug for MediaFoundationEncoder {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("MediaFoundationEncoder")
|
||||
.field("name", &self.name)
|
||||
.field("asynchronous", &self.events.is_some())
|
||||
.field("config", &self.config)
|
||||
.finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
impl MediaFoundationEncoder {
|
||||
/// Opens the GPU's H.264 encoder. VP8 and VP9 are refused, like a machine
|
||||
/// without one: libvpx encodes them.
|
||||
pub fn new(config: EncodeConfig) -> Result<Self, EncodeError> {
|
||||
Self::open(config, false)
|
||||
}
|
||||
|
||||
/// The same, a software transform accepted when no GPU offers one
|
||||
/// (Microsoft's, or Wine's): for the tests and for comparisons, not for
|
||||
/// a share, where libvpx is the fallback.
|
||||
pub fn software(config: EncodeConfig) -> Result<Self, EncodeError> {
|
||||
Self::open(config, true)
|
||||
}
|
||||
|
||||
/// Tells whether this machine encodes `codec` on its GPU, without keeping
|
||||
/// anything open. For the diagnostics.
|
||||
pub fn available(codec: VideoCodec) -> bool {
|
||||
let probe = EncodeConfig {
|
||||
width: 64,
|
||||
height: 64,
|
||||
fps: 30,
|
||||
bitrate_kbps: 500,
|
||||
codec,
|
||||
};
|
||||
Self::new(probe).is_ok()
|
||||
}
|
||||
|
||||
/// The transform's name, as its driver registers it.
|
||||
pub fn name(&self) -> &str {
|
||||
&self.name
|
||||
}
|
||||
|
||||
fn open(config: EncodeConfig, software: bool) -> Result<Self, EncodeError> {
|
||||
if config.codec != VideoCodec::H264 {
|
||||
return Err(EncodeError::Init(format!(
|
||||
"no Media Foundation encoder for {}: use libvpx",
|
||||
config.codec.rtp_name()
|
||||
)));
|
||||
}
|
||||
media_foundation_ready()?;
|
||||
let mut last_error = None;
|
||||
for activate in encoders(software)? {
|
||||
match Self::activate(activate, config, software) {
|
||||
Ok(encoder) => {
|
||||
tracing::info!(
|
||||
encoder = encoder.name,
|
||||
asynchronous = encoder.events.is_some(),
|
||||
"Media Foundation encoder opened"
|
||||
);
|
||||
return Ok(encoder);
|
||||
}
|
||||
Err(error) => {
|
||||
tracing::debug!(%error, "Media Foundation encoder refused");
|
||||
last_error = Some(error);
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(last_error.unwrap_or_else(|| {
|
||||
EncodeError::Init(if software {
|
||||
"no H.264 encoder in Media Foundation".into()
|
||||
} else {
|
||||
"no hardware H.264 encoder in Media Foundation".into()
|
||||
})
|
||||
}))
|
||||
}
|
||||
|
||||
fn activate(
|
||||
activate: IMFActivate,
|
||||
config: EncodeConfig,
|
||||
software: bool,
|
||||
) -> Result<Self, EncodeError> {
|
||||
// SAFETY: plain COM calls on interfaces we own; every pointer passed
|
||||
// lives for the duration of the call.
|
||||
unsafe {
|
||||
let name = friendly_name(&activate);
|
||||
let transform: IMFTransform = activate.ActivateObject().map_err(init)?;
|
||||
let attributes = transform.GetAttributes().ok();
|
||||
let asynchronous = attributes
|
||||
.as_ref()
|
||||
.and_then(|a| a.GetUINT32(&MF_TRANSFORM_ASYNC).ok())
|
||||
== Some(1);
|
||||
if let Some(attributes) = &attributes {
|
||||
if asynchronous {
|
||||
// Without this, an asynchronous transform refuses every
|
||||
// call: it expects a caller that knows the model.
|
||||
attributes
|
||||
.SetUINT32(&MF_TRANSFORM_ASYNC_UNLOCK, 1)
|
||||
.map_err(init)?;
|
||||
}
|
||||
let _ = attributes.SetUINT32(&MF_LOW_LATENCY, 1);
|
||||
}
|
||||
let events = if asynchronous {
|
||||
Some(transform.cast::<IMFMediaEventGenerator>().map_err(init)?)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let codec_api = transform.cast::<ICodecAPI>().ok();
|
||||
if let Some(api) = &codec_api {
|
||||
// Each is a wish: a transform that ignores one still encodes.
|
||||
let fps = u32::from(config.fps.max(1));
|
||||
for (key, value) in [
|
||||
(CODECAPI_AVLowLatencyMode, variant_bool(true)),
|
||||
(
|
||||
CODECAPI_AVEncCommonRateControlMode,
|
||||
variant_u32(eAVEncCommonRateControlMode_CBR.0 as u32),
|
||||
),
|
||||
(
|
||||
CODECAPI_AVEncCommonMeanBitRate,
|
||||
variant_u32(config.bitrate_kbps.saturating_mul(1000)),
|
||||
),
|
||||
(
|
||||
CODECAPI_AVEncMPVGOPSize,
|
||||
variant_u32(fps * KEYFRAME_INTERVAL_S),
|
||||
),
|
||||
(CODECAPI_AVEncMPVDefaultBPictureCount, variant_u32(0)),
|
||||
(CODECAPI_AVEncH264CABACEnable, variant_bool(false)),
|
||||
] {
|
||||
if let Err(error) = api.SetValue(&key, &value) {
|
||||
tracing::debug!(?key, %error, "codec setting ignored");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let (input_stream, output_stream) = stream_ids(&transform);
|
||||
// An encoder takes its output type first: the input it accepts
|
||||
// follows from it. Constrained baseline is what browsers prefer;
|
||||
// some drivers only know baseline, decoded the same way when
|
||||
// nothing beyond constrained is used, which encoders never do.
|
||||
let mut output_set = Err(EncodeError::Init("no H.264 profile accepted".into()));
|
||||
for profile in [
|
||||
eAVEncH264VProfile_ConstrainedBase.0,
|
||||
eAVEncH264VProfile_Base.0,
|
||||
] {
|
||||
let output = video_type(&MFVideoFormat_H264, &config)?;
|
||||
output
|
||||
.SetUINT32(&MF_MT_AVG_BITRATE, config.bitrate_kbps.saturating_mul(1000))
|
||||
.map_err(init)?;
|
||||
output
|
||||
.SetUINT32(&MF_MT_MPEG2_PROFILE, profile as u32)
|
||||
.map_err(init)?;
|
||||
output_set = transform
|
||||
.SetOutputType(output_stream, &output, 0)
|
||||
.map_err(init);
|
||||
if output_set.is_ok() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
output_set?;
|
||||
let input = video_type(&MFVideoFormat_NV12, &config)?;
|
||||
// The colors of `bgra_to_i420`: BT.709, studio range.
|
||||
let _ = input.SetUINT32(&MF_MT_YUV_MATRIX, MFVideoTransferMatrix_BT709.0 as u32);
|
||||
let _ = input.SetUINT32(&MF_MT_VIDEO_NOMINAL_RANGE, MFNominalRange_16_235.0 as u32);
|
||||
transform
|
||||
.SetInputType(input_stream, &input, 0)
|
||||
.map_err(init)?;
|
||||
|
||||
let info = transform.GetOutputStreamInfo(output_stream).map_err(init)?;
|
||||
let output_sample = if info.dwFlags & MFT_OUTPUT_STREAM_PROVIDES_SAMPLES.0 as u32 != 0 {
|
||||
None
|
||||
} else {
|
||||
// The size it asks for, or room for an uncompressed image: a
|
||||
// keyframe never comes close.
|
||||
let raw = config.width * config.height * 3 / 2;
|
||||
Some(new_sample(info.cbSize.max(raw)).map_err(init)?)
|
||||
};
|
||||
transform
|
||||
.ProcessMessage(MFT_MESSAGE_NOTIFY_BEGIN_STREAMING, 0)
|
||||
.map_err(init)?;
|
||||
transform
|
||||
.ProcessMessage(MFT_MESSAGE_NOTIFY_START_OF_STREAM, 0)
|
||||
.map_err(init)?;
|
||||
let sequence_header = sequence_header(&transform, output_stream);
|
||||
Ok(Self {
|
||||
activate,
|
||||
transform,
|
||||
events,
|
||||
codec_api,
|
||||
input_stream,
|
||||
output_stream,
|
||||
output_sample,
|
||||
input_wanted: 0,
|
||||
sequence_header,
|
||||
config,
|
||||
software,
|
||||
name,
|
||||
frames: 0,
|
||||
keyframe_requested: false,
|
||||
i420: Vec::new(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// The image as an NV12 sample with its timestamp.
|
||||
fn input_sample(&mut self, frame: &BgraFrame) -> Result<IMFSample, EncodeError> {
|
||||
bgra_to_i420(frame, &mut self.i420);
|
||||
let (width, height) = (frame.width, frame.height);
|
||||
let luma = width * height;
|
||||
let chroma = luma / 4;
|
||||
let size = luma + 2 * chroma;
|
||||
let fps = i64::from(self.config.fps.max(1));
|
||||
// SAFETY: the buffer is locked for `size` bytes, written within them,
|
||||
// then unlocked before anyone else sees it.
|
||||
unsafe {
|
||||
// A new buffer per image: an asynchronous transform may hold the
|
||||
// previous one until its output.
|
||||
let buffer = MFCreateMemoryBuffer(size as u32).map_err(encode)?;
|
||||
let mut data = std::ptr::null_mut();
|
||||
buffer.Lock(&mut data, None, None).map_err(encode)?;
|
||||
let out = std::slice::from_raw_parts_mut(data, size);
|
||||
let (y, uv) = out.split_at_mut(luma);
|
||||
y.copy_from_slice(&self.i420[..luma]);
|
||||
let (u, v) = self.i420[luma..].split_at(chroma);
|
||||
for ((pair, u), v) in uv.as_chunks_mut::<2>().0.iter_mut().zip(u).zip(v) {
|
||||
*pair = [*u, *v];
|
||||
}
|
||||
buffer.Unlock().map_err(encode)?;
|
||||
buffer.SetCurrentLength(size as u32).map_err(encode)?;
|
||||
let sample = MFCreateSample().map_err(encode)?;
|
||||
sample.AddBuffer(&buffer).map_err(encode)?;
|
||||
let time = self.frames as i64 * TICKS_PER_SECOND / fps;
|
||||
sample.SetSampleTime(time).map_err(encode)?;
|
||||
sample
|
||||
.SetSampleDuration(TICKS_PER_SECOND / fps)
|
||||
.map_err(encode)?;
|
||||
Ok(sample)
|
||||
}
|
||||
}
|
||||
|
||||
fn force_keyframe(&self) {
|
||||
let Some(api) = &self.codec_api else {
|
||||
// The next periodic keyframe will do, within five seconds.
|
||||
tracing::debug!("keyframe requested from an encoder without ICodecAPI");
|
||||
return;
|
||||
};
|
||||
// SAFETY: COM call with a value that outlives it.
|
||||
if let Err(error) =
|
||||
unsafe { api.SetValue(&CODECAPI_AVEncVideoForceKeyFrame, &variant_u32(1)) }
|
||||
{
|
||||
tracing::debug!(%error, "keyframe request refused");
|
||||
}
|
||||
}
|
||||
|
||||
/// Synchronous transform: the image in, then every unit it gives.
|
||||
fn encode_sync(&mut self, sample: &IMFSample) -> Result<Vec<Vec<u8>>, EncodeError> {
|
||||
let mut packets = Vec::new();
|
||||
// SAFETY: COM call on a sample we own.
|
||||
let accepted = unsafe { self.transform.ProcessInput(self.input_stream, sample, 0) };
|
||||
match accepted {
|
||||
Ok(()) => {}
|
||||
Err(error) if error.code() == MF_E_NOTACCEPTING => {
|
||||
// It still holds output: take it, then try again once.
|
||||
self.drain(&mut packets)?;
|
||||
// SAFETY: as above.
|
||||
unsafe { self.transform.ProcessInput(self.input_stream, sample, 0) }
|
||||
.map_err(encode)?;
|
||||
}
|
||||
Err(error) => return Err(encode(error)),
|
||||
}
|
||||
self.drain(&mut packets)?;
|
||||
Ok(packets)
|
||||
}
|
||||
|
||||
/// Asynchronous transform: wait for it to want an image, give it, wait
|
||||
/// for the unit, take whatever else is ready.
|
||||
fn encode_async(&mut self, sample: &IMFSample) -> Result<Vec<Vec<u8>>, EncodeError> {
|
||||
let mut packets = Vec::new();
|
||||
let deadline = Instant::now() + PULL_TIMEOUT;
|
||||
while self.input_wanted == 0 {
|
||||
if !self.next_event(Some(deadline), &mut packets)? {
|
||||
return Err(EncodeError::Encode(
|
||||
"Media Foundation: the encoder asks for no image".into(),
|
||||
));
|
||||
}
|
||||
}
|
||||
// SAFETY: COM call on a sample we own.
|
||||
unsafe { self.transform.ProcessInput(self.input_stream, sample, 0) }.map_err(encode)?;
|
||||
self.input_wanted -= 1;
|
||||
let deadline = Instant::now() + PULL_TIMEOUT;
|
||||
while packets.is_empty() && self.next_event(Some(deadline), &mut packets)? {}
|
||||
while self.next_event(None, &mut packets)? {}
|
||||
Ok(packets)
|
||||
}
|
||||
|
||||
/// Handles one event of an asynchronous transform, waiting until
|
||||
/// `deadline` at most (not at all without one). False when none came.
|
||||
fn next_event(
|
||||
&mut self,
|
||||
deadline: Option<Instant>,
|
||||
packets: &mut Vec<Vec<u8>>,
|
||||
) -> Result<bool, EncodeError> {
|
||||
let Some(events) = self.events.clone() else {
|
||||
return Ok(false);
|
||||
};
|
||||
loop {
|
||||
// SAFETY: COM call; the event is ours once returned.
|
||||
let event = unsafe { events.GetEvent(MF_EVENT_FLAG_NO_WAIT) };
|
||||
match event {
|
||||
Ok(event) => {
|
||||
// SAFETY: as above.
|
||||
let (kind, status) = unsafe { (event.GetType(), event.GetStatus()) };
|
||||
if let Ok(status) = status {
|
||||
status.ok().map_err(encode)?;
|
||||
}
|
||||
let kind = MF_EVENT_TYPE(kind.map_err(encode)? as i32);
|
||||
if kind == METransformNeedInput {
|
||||
self.input_wanted += 1;
|
||||
} else if kind == METransformHaveOutput
|
||||
&& let Some(packet) = self.take_output()?
|
||||
{
|
||||
packets.push(packet);
|
||||
}
|
||||
return Ok(true);
|
||||
}
|
||||
Err(error) if error.code() == MF_E_NO_EVENTS_AVAILABLE => {
|
||||
match deadline {
|
||||
Some(deadline) if Instant::now() < deadline => {
|
||||
// `GetEvent` either blocks forever or not at all:
|
||||
// poll instead, a quarter of a millisecond is
|
||||
// nothing next to a frame.
|
||||
std::thread::sleep(Duration::from_micros(250));
|
||||
}
|
||||
_ => return Ok(false),
|
||||
}
|
||||
}
|
||||
Err(error) => return Err(encode(error)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Takes every unit a synchronous transform has ready.
|
||||
fn drain(&mut self, packets: &mut Vec<Vec<u8>>) -> Result<(), EncodeError> {
|
||||
while let Some(packet) = self.take_output()? {
|
||||
packets.push(packet);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// One access unit, or `None` when the transform wants more input.
|
||||
fn take_output(&mut self) -> Result<Option<Vec<u8>>, EncodeError> {
|
||||
loop {
|
||||
if let Some(sample) = &self.output_sample {
|
||||
// SAFETY: COM calls on a sample we own.
|
||||
unsafe {
|
||||
sample
|
||||
.GetBufferByIndex(0)
|
||||
.and_then(|b| b.SetCurrentLength(0))
|
||||
}
|
||||
.map_err(encode)?;
|
||||
}
|
||||
let mut buffers = [MFT_OUTPUT_DATA_BUFFER {
|
||||
dwStreamID: self.output_stream,
|
||||
pSample: ManuallyDrop::new(self.output_sample.clone()),
|
||||
dwStatus: 0,
|
||||
pEvents: ManuallyDrop::new(None),
|
||||
}];
|
||||
let mut status = 0;
|
||||
// SAFETY: the transform fills `buffers`, whose references we take
|
||||
// back right after, success or not, so that none leaks.
|
||||
let result = unsafe { self.transform.ProcessOutput(0, &mut buffers, &mut status) };
|
||||
let (sample, _events) = unsafe {
|
||||
(
|
||||
ManuallyDrop::take(&mut buffers[0].pSample),
|
||||
ManuallyDrop::take(&mut buffers[0].pEvents),
|
||||
)
|
||||
};
|
||||
match result {
|
||||
Ok(()) => {}
|
||||
Err(error) if error.code() == MF_E_TRANSFORM_NEED_MORE_INPUT => return Ok(None),
|
||||
Err(error) if error.code() == MF_E_TRANSFORM_STREAM_CHANGE => {
|
||||
// The transform settled its output type: take the one it
|
||||
// proposes, and ask again.
|
||||
// SAFETY: COM calls on the transform we own.
|
||||
unsafe {
|
||||
let proposed = self
|
||||
.transform
|
||||
.GetOutputAvailableType(self.output_stream, 0)
|
||||
.map_err(encode)?;
|
||||
self.transform
|
||||
.SetOutputType(self.output_stream, &proposed, 0)
|
||||
.map_err(encode)?;
|
||||
}
|
||||
self.sequence_header = sequence_header(&self.transform, self.output_stream);
|
||||
continue;
|
||||
}
|
||||
Err(error) => return Err(encode(error)),
|
||||
}
|
||||
let Some(sample) = sample else {
|
||||
return Ok(None);
|
||||
};
|
||||
// SAFETY: the buffer is locked for its current length, copied,
|
||||
// then unlocked.
|
||||
let (mut unit, keyframe) = unsafe {
|
||||
let buffer = sample.ConvertToContiguousBuffer().map_err(encode)?;
|
||||
let mut data = std::ptr::null_mut();
|
||||
let mut length = 0;
|
||||
buffer
|
||||
.Lock(&mut data, None, Some(&mut length))
|
||||
.map_err(encode)?;
|
||||
let unit = std::slice::from_raw_parts(data, length as usize).to_vec();
|
||||
buffer.Unlock().map_err(encode)?;
|
||||
let keyframe = sample.GetUINT32(&MFSampleExtension_CleanPoint) == Ok(1);
|
||||
(unit, keyframe)
|
||||
};
|
||||
if unit.is_empty() {
|
||||
continue;
|
||||
}
|
||||
if keyframe
|
||||
&& !nal_types(&unit).contains(&7)
|
||||
&& let Some(header) = &self.sequence_header
|
||||
{
|
||||
// A browser joining on this keyframe needs SPS and PPS.
|
||||
unit.splice(0..0, header.iter().copied());
|
||||
}
|
||||
return Ok(Some(unit));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl VideoEncoder for MediaFoundationEncoder {
|
||||
fn encode(&mut self, frame: &BgraFrame) -> Result<Vec<Vec<u8>>, EncodeError> {
|
||||
let expected = self.config.width as usize * self.config.height as usize * 4;
|
||||
if frame.data.len() < expected
|
||||
|| frame.width != self.config.width as usize
|
||||
|| frame.height != self.config.height as usize
|
||||
{
|
||||
return Err(EncodeError::Encode(format!(
|
||||
"{}x{} image for a {}x{} encoder",
|
||||
frame.width, frame.height, self.config.width, self.config.height
|
||||
)));
|
||||
}
|
||||
if std::mem::take(&mut self.keyframe_requested) {
|
||||
self.force_keyframe();
|
||||
}
|
||||
let sample = self.input_sample(frame)?;
|
||||
self.frames += 1;
|
||||
let packets = if self.events.is_some() {
|
||||
self.encode_async(&sample)?
|
||||
} else {
|
||||
self.encode_sync(&sample)?
|
||||
};
|
||||
if packets.is_empty() {
|
||||
return Err(EncodeError::NoFrame);
|
||||
}
|
||||
Ok(packets)
|
||||
}
|
||||
|
||||
fn request_keyframe(&mut self) {
|
||||
self.keyframe_requested = true;
|
||||
}
|
||||
|
||||
fn config(&self) -> EncodeConfig {
|
||||
self.config
|
||||
}
|
||||
|
||||
fn reconfigure(&mut self, width: u32, height: u32) -> Result<(), EncodeError> {
|
||||
// A new transform at the new size, opened before the old one goes: a
|
||||
// failure leaves the stream as it was. Its first image is a keyframe.
|
||||
let config = EncodeConfig {
|
||||
width,
|
||||
height,
|
||||
..self.config
|
||||
};
|
||||
*self = Self::open(config, self.software)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for MediaFoundationEncoder {
|
||||
fn drop(&mut self) {
|
||||
// SAFETY: the transform is not used after this.
|
||||
let _ = unsafe { self.activate.ShutdownObject() };
|
||||
}
|
||||
}
|
||||
|
||||
/// Starts COM in the multithreaded apartment for the whole process, and
|
||||
/// Media Foundation, once. Neither is ever stopped: an encoder can open at
|
||||
/// any time, on any thread.
|
||||
fn media_foundation_ready() -> Result<(), EncodeError> {
|
||||
static READY: OnceLock<Result<(), String>> = OnceLock::new();
|
||||
READY
|
||||
.get_or_init(|| {
|
||||
// SAFETY: process-wide initializations, without arguments to keep
|
||||
// alive.
|
||||
unsafe {
|
||||
// Every thread that has not chosen an apartment joins this
|
||||
// one: the encoding thread does not have to.
|
||||
CoIncrementMTAUsage().map_err(|e| format!("COM: {e}"))?;
|
||||
MFStartup(MF_VERSION, MFSTARTUP_LITE).map_err(|e| format!("Media Foundation: {e}"))
|
||||
}
|
||||
})
|
||||
.clone()
|
||||
.map_err(EncodeError::Init)
|
||||
}
|
||||
|
||||
/// The H.264 encoders that take NV12, best first: hardware ones only, unless
|
||||
/// `software`.
|
||||
fn encoders(software: bool) -> Result<Vec<IMFActivate>, EncodeError> {
|
||||
let input = MFT_REGISTER_TYPE_INFO {
|
||||
guidMajorType: MFMediaType_Video,
|
||||
guidSubtype: MFVideoFormat_NV12,
|
||||
};
|
||||
let output = MFT_REGISTER_TYPE_INFO {
|
||||
guidMajorType: MFMediaType_Video,
|
||||
guidSubtype: MFVideoFormat_H264,
|
||||
};
|
||||
let mut flags = MFT_ENUM_FLAG_HARDWARE.0 | MFT_ENUM_FLAG_SORTANDFILTER.0;
|
||||
if software {
|
||||
flags |= MFT_ENUM_FLAG_SYNCMFT.0;
|
||||
}
|
||||
let mut list = std::ptr::null_mut();
|
||||
let mut count = 0;
|
||||
// SAFETY: Media Foundation allocates the array; we take each reference
|
||||
// out of it, then free it.
|
||||
unsafe {
|
||||
MFTEnumEx(
|
||||
MFT_CATEGORY_VIDEO_ENCODER,
|
||||
MFT_ENUM_FLAG(flags),
|
||||
Some(&input),
|
||||
Some(&output),
|
||||
&mut list,
|
||||
&mut count,
|
||||
)
|
||||
.map_err(init)?;
|
||||
if list.is_null() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
let found = (0..count as usize)
|
||||
.filter_map(|i| std::ptr::read(list.add(i)))
|
||||
.collect::<Vec<_>>();
|
||||
CoTaskMemFree(Some(list as *const _));
|
||||
// Hardware first: the sort puts it there already, but not every
|
||||
// version of Windows sorts by it.
|
||||
let (mut hardware, other): (Vec<_>, Vec<_>) = found
|
||||
.into_iter()
|
||||
.partition(|a| a.GetStringLength(&MFT_ENUM_HARDWARE_URL_Attribute).is_ok());
|
||||
hardware.extend(other);
|
||||
Ok(hardware)
|
||||
}
|
||||
}
|
||||
|
||||
/// The registered name of an encoder, for the log.
|
||||
fn friendly_name(activate: &IMFActivate) -> String {
|
||||
let mut name = PWSTR::null();
|
||||
let mut length = 0;
|
||||
// SAFETY: Media Foundation allocates the string; we copy it, then free it.
|
||||
unsafe {
|
||||
if activate
|
||||
.GetAllocatedString(&MFT_FRIENDLY_NAME_Attribute, &mut name, &mut length)
|
||||
.is_err()
|
||||
{
|
||||
return "unnamed encoder".into();
|
||||
}
|
||||
let text = name.to_string().unwrap_or_default();
|
||||
CoTaskMemFree(Some(name.0 as *const _));
|
||||
text
|
||||
}
|
||||
}
|
||||
|
||||
/// Stream identifiers: most transforms have fixed streams numbered 0, and
|
||||
/// answer `E_NOTIMPL`.
|
||||
fn stream_ids(transform: &IMFTransform) -> (u32, u32) {
|
||||
let (mut input, mut output) = ([0u32], [0u32]);
|
||||
// SAFETY: two arrays of one identifier each, as announced.
|
||||
match unsafe { transform.GetStreamIDs(&mut input, &mut output) } {
|
||||
Ok(()) => (input[0], output[0]),
|
||||
Err(_) => (0, 0),
|
||||
}
|
||||
}
|
||||
|
||||
/// A progressive video type of `subtype` at the configured size and rate.
|
||||
fn video_type(subtype: &GUID, config: &EncodeConfig) -> Result<IMFMediaType, EncodeError> {
|
||||
// SAFETY: COM calls on a type we just created.
|
||||
unsafe {
|
||||
let media = MFCreateMediaType().map_err(init)?;
|
||||
media
|
||||
.SetGUID(&MF_MT_MAJOR_TYPE, &MFMediaType_Video)
|
||||
.map_err(init)?;
|
||||
media.SetGUID(&MF_MT_SUBTYPE, subtype).map_err(init)?;
|
||||
media
|
||||
.SetUINT64(
|
||||
&MF_MT_FRAME_SIZE,
|
||||
u64::from(config.width) << 32 | u64::from(config.height),
|
||||
)
|
||||
.map_err(init)?;
|
||||
media
|
||||
.SetUINT64(&MF_MT_FRAME_RATE, u64::from(config.fps.max(1)) << 32 | 1)
|
||||
.map_err(init)?;
|
||||
media
|
||||
.SetUINT64(&MF_MT_PIXEL_ASPECT_RATIO, 1 << 32 | 1)
|
||||
.map_err(init)?;
|
||||
media
|
||||
.SetUINT32(&MF_MT_INTERLACE_MODE, MFVideoInterlace_Progressive.0 as u32)
|
||||
.map_err(init)?;
|
||||
Ok(media)
|
||||
}
|
||||
}
|
||||
|
||||
/// SPS and PPS of the current output type, when the transform gives them in
|
||||
/// Annex B (start codes); otherwise nothing, the stream carries them.
|
||||
fn sequence_header(transform: &IMFTransform, stream: u32) -> Option<Vec<u8>> {
|
||||
// SAFETY: the blob is copied into a buffer of the size announced.
|
||||
unsafe {
|
||||
let media = transform.GetOutputCurrentType(stream).ok()?;
|
||||
let size = media.GetBlobSize(&MF_MT_MPEG_SEQUENCE_HEADER).ok()?;
|
||||
let mut header = vec![0u8; size as usize];
|
||||
media
|
||||
.GetBlob(&MF_MT_MPEG_SEQUENCE_HEADER, &mut header, None)
|
||||
.ok()?;
|
||||
(header.starts_with(&[0, 0, 1]) || header.starts_with(&[0, 0, 0, 1])).then_some(header)
|
||||
}
|
||||
}
|
||||
|
||||
/// An empty sample with a buffer of `size` bytes, lent to the transform.
|
||||
fn new_sample(size: u32) -> windows::core::Result<IMFSample> {
|
||||
// SAFETY: COM calls on objects we just created.
|
||||
unsafe {
|
||||
let sample = MFCreateSample()?;
|
||||
sample.AddBuffer(&MFCreateMemoryBuffer(size)?)?;
|
||||
Ok(sample)
|
||||
}
|
||||
}
|
||||
|
||||
/// NAL unit types of an Annex B access unit, in order.
|
||||
fn nal_types(unit: &[u8]) -> Vec<u8> {
|
||||
unit.windows(3)
|
||||
.enumerate()
|
||||
.filter(|(_, w)| *w == [0, 0, 1])
|
||||
.filter_map(|(i, _)| unit.get(i + 3).map(|b| b & 0x1f))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn variant_u32(value: u32) -> VARIANT {
|
||||
VARIANT {
|
||||
Anonymous: VARIANT_0 {
|
||||
Anonymous: ManuallyDrop::new(VARIANT_0_0 {
|
||||
vt: VT_UI4,
|
||||
wReserved1: 0,
|
||||
wReserved2: 0,
|
||||
wReserved3: 0,
|
||||
Anonymous: VARIANT_0_0_0 { ulVal: value },
|
||||
}),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fn variant_bool(value: bool) -> VARIANT {
|
||||
VARIANT {
|
||||
Anonymous: VARIANT_0 {
|
||||
Anonymous: ManuallyDrop::new(VARIANT_0_0 {
|
||||
vt: VT_BOOL,
|
||||
wReserved1: 0,
|
||||
wReserved2: 0,
|
||||
wReserved3: 0,
|
||||
Anonymous: VARIANT_0_0_0 {
|
||||
boolVal: VARIANT_BOOL(if value { -1 } else { 0 }),
|
||||
},
|
||||
}),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fn init(error: windows::core::Error) -> EncodeError {
|
||||
EncodeError::Init(format!("Media Foundation: {error}"))
|
||||
}
|
||||
|
||||
fn encode(error: windows::core::Error) -> EncodeError {
|
||||
EncodeError::Encode(format!("Media Foundation: {error}"))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn config(width: u32, height: u32) -> EncodeConfig {
|
||||
EncodeConfig {
|
||||
width,
|
||||
height,
|
||||
fps: 30,
|
||||
bitrate_kbps: 1000,
|
||||
codec: VideoCodec::H264,
|
||||
}
|
||||
}
|
||||
|
||||
/// Bars that move, so that the encoder has something to say.
|
||||
fn image(width: usize, height: usize, shift: usize) -> Vec<u8> {
|
||||
let mut data = vec![0u8; width * height * 4];
|
||||
for (i, pixel) in data.as_chunks_mut::<4>().0.iter_mut().enumerate() {
|
||||
let x = (i % width + shift) % width;
|
||||
pixel.copy_from_slice(&[(x * 255 / width) as u8, 128, 255 - (x as u8), 255]);
|
||||
}
|
||||
data
|
||||
}
|
||||
|
||||
/// Any H.264 transform: the GPU's on a real machine, Wine's (GStreamer,
|
||||
/// x264) under Wine. Skipped where neither exists.
|
||||
fn encoder(width: u32, height: u32) -> Option<MediaFoundationEncoder> {
|
||||
match MediaFoundationEncoder::software(config(width, height)) {
|
||||
Ok(encoder) => {
|
||||
eprintln!("encoder: {}", encoder.name());
|
||||
Some(encoder)
|
||||
}
|
||||
Err(error) => {
|
||||
eprintln!("no Media Foundation H.264: {error}, test skipped");
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Enough images to get past the lookahead of a software encoder.
|
||||
const IMAGES: usize = 90;
|
||||
|
||||
fn encode_all(
|
||||
encoder: &mut MediaFoundationEncoder,
|
||||
images: usize,
|
||||
width: usize,
|
||||
height: usize,
|
||||
) -> Vec<Vec<u8>> {
|
||||
let mut units = Vec::new();
|
||||
for i in 0..images {
|
||||
if i == images / 2 {
|
||||
encoder.request_keyframe();
|
||||
}
|
||||
let data = image(width, height, i * 7);
|
||||
let frame = BgraFrame {
|
||||
data: &data,
|
||||
width,
|
||||
height,
|
||||
};
|
||||
match encoder.encode(&frame) {
|
||||
Ok(packets) => units.extend(packets),
|
||||
Err(EncodeError::NoFrame) => {}
|
||||
Err(e) => panic!("{e}"),
|
||||
}
|
||||
}
|
||||
units
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn h264_comes_out_as_annex_b_with_its_parameters() {
|
||||
let Some(mut encoder) = encoder(320, 240) else {
|
||||
return;
|
||||
};
|
||||
// A GPU gives one unit per image; Wine's x264 keeps about forty in
|
||||
// its lookahead first, whatever the low-latency setting says.
|
||||
let units = encode_all(&mut encoder, IMAGES, 320, 240);
|
||||
assert!(
|
||||
units.len() >= IMAGES / 4,
|
||||
"{} access units for {IMAGES} images",
|
||||
units.len()
|
||||
);
|
||||
// SPS (7), PPS (8) and an IDR slice (5) in the first unit.
|
||||
let first = nal_types(&units[0]);
|
||||
assert!(
|
||||
first.contains(&7) && first.contains(&8) && first.contains(&5),
|
||||
"{first:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_new_size_gives_a_new_encoder_that_starts_on_a_keyframe() {
|
||||
let Some(mut encoder) = encoder(320, 240) else {
|
||||
return;
|
||||
};
|
||||
encode_all(&mut encoder, 3, 320, 240);
|
||||
encoder.reconfigure(640, 360).expect("new size");
|
||||
assert_eq!(encoder.config().width, 640);
|
||||
let units = encode_all(&mut encoder, IMAGES, 640, 360);
|
||||
assert!(!units.is_empty());
|
||||
assert!(nal_types(&units[0]).contains(&5));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_image_of_the_wrong_size_is_refused() {
|
||||
let Some(mut encoder) = encoder(320, 240) else {
|
||||
return;
|
||||
};
|
||||
let data = image(160, 120, 0);
|
||||
let frame = BgraFrame {
|
||||
data: &data,
|
||||
width: 160,
|
||||
height: 120,
|
||||
};
|
||||
assert!(matches!(
|
||||
encoder.encode(&frame),
|
||||
Err(EncodeError::Encode(_))
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vp8_and_vp9_are_left_to_libvpx() {
|
||||
for codec in [VideoCodec::Vp8, VideoCodec::Vp9] {
|
||||
let config = EncodeConfig {
|
||||
codec,
|
||||
..config(320, 240)
|
||||
};
|
||||
assert!(matches!(
|
||||
MediaFoundationEncoder::software(config),
|
||||
Err(EncodeError::Init(_))
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nal_types_are_read_after_three_and_four_byte_start_codes() {
|
||||
let unit = [0, 0, 0, 1, 0x67, 9, 0, 0, 1, 0x68, 9, 0, 0, 1, 0x65, 1, 2];
|
||||
assert_eq!(nal_types(&unit), vec![7, 8, 5]);
|
||||
}
|
||||
}
|
||||
+270
-12
@@ -21,10 +21,12 @@ use crate::encoder::{EncodeConfig, EncodeError, VideoEncoder};
|
||||
use crate::frame::{FrameSource, SharedMedia};
|
||||
|
||||
/// What the encoding thread publishes, and what the viewers read.
|
||||
#[derive(Default)]
|
||||
struct SharedOutput {
|
||||
frame: Mutex<Arc<[u8]>>,
|
||||
/// Last encoded frame and the instant its image was captured.
|
||||
frame: Mutex<(Arc<[u8]>, Option<Instant>)>,
|
||||
version: AtomicU64,
|
||||
/// Bumped with `version`: sessions wait on it instead of polling (#86).
|
||||
ready: tokio::sync::watch::Sender<u64>,
|
||||
/// Keyframe request for the next encode: a viewer arriving mid-stream
|
||||
/// cannot decode without one.
|
||||
keyframe: AtomicBool,
|
||||
@@ -33,6 +35,14 @@ struct SharedOutput {
|
||||
capture_errors: AtomicU64,
|
||||
encode_errors: AtomicU64,
|
||||
empty_frames: AtomicU64,
|
||||
/// Captured frames skipped because the image had not changed.
|
||||
unchanged: AtomicU64,
|
||||
/// Captured frames dropped to hold the adaptive cadence.
|
||||
paced: AtomicU64,
|
||||
/// Cadence the encoder currently holds, at most the configured one.
|
||||
effective_fps: std::sync::atomic::AtomicU8,
|
||||
/// Configured cadence, for the adaptive one to start from.
|
||||
max_fps: std::sync::atomic::AtomicU8,
|
||||
subscribers: AtomicU64,
|
||||
/// The capture has ended for good, and why.
|
||||
ended: Mutex<Option<CaptureError>>,
|
||||
@@ -42,6 +52,33 @@ struct SharedOutput {
|
||||
resolution_changes: AtomicU64,
|
||||
}
|
||||
|
||||
impl Default for SharedOutput {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
frame: Mutex::new((Arc::from(&[][..]), None)),
|
||||
version: AtomicU64::new(0),
|
||||
ready: tokio::sync::watch::Sender::new(0),
|
||||
keyframe: AtomicBool::default(),
|
||||
captured: AtomicU64::default(),
|
||||
encoded: AtomicU64::default(),
|
||||
capture_errors: AtomicU64::default(),
|
||||
encode_errors: AtomicU64::default(),
|
||||
empty_frames: AtomicU64::default(),
|
||||
unchanged: AtomicU64::default(),
|
||||
paced: AtomicU64::default(),
|
||||
effective_fps: std::sync::atomic::AtomicU8::default(),
|
||||
max_fps: std::sync::atomic::AtomicU8::default(),
|
||||
subscribers: AtomicU64::default(),
|
||||
ended: Mutex::default(),
|
||||
dimensions: AtomicU64::default(),
|
||||
resolution_changes: AtomicU64::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Longest gap between two encoded frames on an unchanged screen.
|
||||
const REFRESH: Duration = Duration::from_secs(1);
|
||||
|
||||
fn pack(width: u32, height: u32) -> u64 {
|
||||
(u64::from(width) << 32) | u64::from(height)
|
||||
}
|
||||
@@ -51,25 +88,31 @@ fn unpack(value: u64) -> (u32, u32) {
|
||||
}
|
||||
|
||||
impl SharedOutput {
|
||||
fn publish(&self, frame: Vec<u8>) {
|
||||
fn max_fps(&self) -> u8 {
|
||||
self.max_fps.load(Ordering::Relaxed).max(1)
|
||||
}
|
||||
|
||||
fn publish(&self, frame: Vec<u8>, captured_at: Instant) {
|
||||
if frame.is_empty() {
|
||||
self.empty_frames.fetch_add(1, Ordering::Relaxed);
|
||||
return;
|
||||
}
|
||||
{
|
||||
let mut slot = self.frame.lock().unwrap_or_else(|e| e.into_inner());
|
||||
*slot = Arc::from(frame.as_slice());
|
||||
*slot = (Arc::from(frame.as_slice()), Some(captured_at));
|
||||
}
|
||||
self.version.fetch_add(1, Ordering::Release);
|
||||
let version = self.version.fetch_add(1, Ordering::Release) + 1;
|
||||
// Wakes the sessions waiting for a frame; nobody waiting is fine.
|
||||
self.ready.send_replace(version);
|
||||
}
|
||||
|
||||
fn read(&self) -> (u64, Arc<[u8]>) {
|
||||
fn read(&self) -> (u64, Arc<[u8]>, Option<Instant>) {
|
||||
let version = self.version.load(Ordering::Acquire);
|
||||
let frame = {
|
||||
let (frame, captured_at) = {
|
||||
let slot = self.frame.lock().unwrap_or_else(|e| e.into_inner());
|
||||
slot.clone()
|
||||
};
|
||||
(version, frame)
|
||||
(version, frame, captured_at)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -85,6 +128,12 @@ pub struct LiveStats {
|
||||
pub encode_errors: u64,
|
||||
/// Frames the encoder returned empty (insignificant image).
|
||||
pub empty_frames: u64,
|
||||
/// Captured frames not encoded because the image had not changed.
|
||||
pub unchanged: u64,
|
||||
/// Captured frames dropped to hold the adaptive cadence.
|
||||
pub paced: u64,
|
||||
/// Cadence the encoder currently holds (adaptive, at most `fps`).
|
||||
pub effective_fps: u8,
|
||||
/// Viewers subscribed to this source.
|
||||
pub subscribers: u64,
|
||||
/// Resolution changes followed since start.
|
||||
@@ -114,6 +163,10 @@ impl LiveSource {
|
||||
output
|
||||
.dimensions
|
||||
.store(pack(config.width, config.height), Ordering::Relaxed);
|
||||
output.max_fps.store(config.fps.max(1), Ordering::Relaxed);
|
||||
output
|
||||
.effective_fps
|
||||
.store(config.fps.max(1), Ordering::Relaxed);
|
||||
let stop = Arc::new(AtomicBool::new(false));
|
||||
|
||||
let worker_output = output.clone();
|
||||
@@ -128,9 +181,12 @@ impl LiveSource {
|
||||
// nothing explaining why.
|
||||
let mut logged = Logged::default();
|
||||
let start = Instant::now();
|
||||
let mut last_encode: Option<Instant> = None;
|
||||
let mut cadence = AdaptiveCadence::new(worker_output.max_fps());
|
||||
while !worker_stop.load(Ordering::Relaxed) {
|
||||
// A keyframe request arrives when a viewer joins.
|
||||
if worker_output.keyframe.swap(false, Ordering::Relaxed) {
|
||||
let keyframe = worker_output.keyframe.swap(false, Ordering::Relaxed);
|
||||
if keyframe {
|
||||
encoder.request_keyframe();
|
||||
}
|
||||
|
||||
@@ -170,12 +226,34 @@ impl LiveSource {
|
||||
};
|
||||
worker_output.captured.fetch_add(1, Ordering::Relaxed);
|
||||
|
||||
// An unchanged image is not encoded again (#86): an idle
|
||||
// screen costs almost nothing, and the viewer's decoder
|
||||
// keeps showing the last frame. Still encoded: a frame a
|
||||
// viewer asked a keyframe for, and one per second, so a
|
||||
// still screen does not look like a dead stream.
|
||||
if !frame.fresh
|
||||
&& !keyframe
|
||||
&& last_encode.is_some_and(|at| at.elapsed() < REFRESH)
|
||||
{
|
||||
worker_output.unchanged.fetch_add(1, Ordering::Relaxed);
|
||||
continue;
|
||||
}
|
||||
// The cadence the encoder actually holds: frames in
|
||||
// between are dropped instead of piling up as latency.
|
||||
if !keyframe && last_encode.is_some_and(|at| !cadence.due(at.elapsed())) {
|
||||
worker_output.paced.fetch_add(1, Ordering::Relaxed);
|
||||
continue;
|
||||
}
|
||||
let work_started = Instant::now();
|
||||
last_encode = Some(work_started);
|
||||
|
||||
// The source changed size (resolution, rotation, window
|
||||
// resized): follow it instead of cropping.
|
||||
let current = encoder.config();
|
||||
if (frame.width, frame.height) != (current.width, current.height) {
|
||||
match encoder.reconfigure(frame.width, frame.height) {
|
||||
Ok(()) => {
|
||||
cadence.warm_up();
|
||||
tracing::info!(
|
||||
event = "resolution_changed",
|
||||
before = ?(current.width, current.height),
|
||||
@@ -219,7 +297,18 @@ impl LiveSource {
|
||||
}
|
||||
};
|
||||
|
||||
match encoder.encode(&view) {
|
||||
let encoded = encoder.encode_shared(&view, &frame.bgra);
|
||||
if let Some(fps) = cadence.record(work_started.elapsed()) {
|
||||
tracing::info!(
|
||||
event = "cadence_changed",
|
||||
fps,
|
||||
"the encoding cadence follows what this machine holds"
|
||||
);
|
||||
}
|
||||
worker_output
|
||||
.effective_fps
|
||||
.store(cadence.fps(), Ordering::Relaxed);
|
||||
match encoded {
|
||||
Ok(packets) => {
|
||||
let mut joined = Vec::new();
|
||||
for packet in packets {
|
||||
@@ -236,7 +325,7 @@ impl LiveSource {
|
||||
"first image encoded"
|
||||
);
|
||||
}
|
||||
worker_output.publish(joined);
|
||||
worker_output.publish(joined, frame.captured_at);
|
||||
worker_output.encoded.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
Err(EncodeError::NoFrame) => {
|
||||
@@ -277,6 +366,9 @@ impl LiveSource {
|
||||
capture_errors: self.output.capture_errors.load(Ordering::Relaxed),
|
||||
encode_errors: self.output.encode_errors.load(Ordering::Relaxed),
|
||||
empty_frames: self.output.empty_frames.load(Ordering::Relaxed),
|
||||
unchanged: self.output.unchanged.load(Ordering::Relaxed),
|
||||
paced: self.output.paced.load(Ordering::Relaxed),
|
||||
effective_fps: self.output.effective_fps.load(Ordering::Relaxed),
|
||||
subscribers: self.output.subscribers.load(Ordering::Relaxed),
|
||||
resolution_changes: self.output.resolution_changes.load(Ordering::Relaxed),
|
||||
ended: self.ended().is_some(),
|
||||
@@ -301,6 +393,7 @@ impl SharedMedia for LiveSource {
|
||||
config: self.config,
|
||||
last_version: 0,
|
||||
served: 0,
|
||||
captured_at: None,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -331,6 +424,7 @@ pub struct SourceView {
|
||||
config: EncodeConfig,
|
||||
last_version: u64,
|
||||
served: u64,
|
||||
captured_at: Option<Instant>,
|
||||
}
|
||||
|
||||
impl FrameSource for SourceView {
|
||||
@@ -344,17 +438,26 @@ impl FrameSource for SourceView {
|
||||
|
||||
fn next_frame(&mut self) -> Arc<[u8]> {
|
||||
self.served += 1;
|
||||
let (version, frame) = self.output.read();
|
||||
let (version, frame, captured_at) = self.output.read();
|
||||
if version == self.last_version {
|
||||
return Arc::from(&[][..]);
|
||||
}
|
||||
self.last_version = version;
|
||||
self.captured_at = captured_at;
|
||||
frame
|
||||
}
|
||||
|
||||
fn served(&self) -> u64 {
|
||||
self.served
|
||||
}
|
||||
|
||||
fn captured_at(&self) -> Option<Instant> {
|
||||
self.captured_at
|
||||
}
|
||||
|
||||
fn frames_ready(&self) -> Option<tokio::sync::watch::Receiver<u64>> {
|
||||
Some(self.output.ready.subscribe())
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for SourceView {
|
||||
@@ -381,9 +484,164 @@ struct Logged {
|
||||
first: bool,
|
||||
}
|
||||
|
||||
/// The cadence the encoder actually holds (#86): "60 fps when possible".
|
||||
///
|
||||
/// The configured cadence is the ceiling. When the work per frame (conversion
|
||||
/// and encoding) takes more than [`LOWER_ABOVE`] of the frame period, the
|
||||
/// cadence halves (60, 30, 15): frames that cannot be encoded in time would
|
||||
/// otherwise pile up as latency and stutter. When it has stayed under
|
||||
/// [`RAISE_BELOW`] of the faster period for [`RAISE_AFTER`] frames, it doubles
|
||||
/// back. The RTP timestamps follow the capture instants, so the browser sees
|
||||
/// a slower stream, not a jerky one.
|
||||
struct AdaptiveCadence {
|
||||
max_fps: u8,
|
||||
fps: u8,
|
||||
/// Smoothed work time per encoded frame.
|
||||
work: Option<Duration>,
|
||||
/// Encoded frames in a row with room to spare for the faster cadence.
|
||||
roomy: u32,
|
||||
/// Frames still to ignore: the first ones of a new encoder (#57).
|
||||
warming: u32,
|
||||
}
|
||||
|
||||
/// Lower the cadence when the work takes more than this share of a period.
|
||||
const LOWER_ABOVE: f64 = 0.85;
|
||||
/// Raise it back when the work fits in this share of the faster period...
|
||||
const RAISE_BELOW: f64 = 0.5;
|
||||
/// ...for this many frames in a row (a second at 60 fps).
|
||||
const RAISE_AFTER: u32 = 60;
|
||||
/// The slowest cadence the adaptation goes down to.
|
||||
const MIN_FPS: u8 = 15;
|
||||
/// Frames not counted after the encoder opens or changes size. The first ones
|
||||
/// are slow for reasons that do not last (a GPU pipeline starting, the first
|
||||
/// keyframe): counted, they halved the cadence of a hardware encoder that
|
||||
/// then never came back, its 9 to 13 ms per 1080p frame being above the
|
||||
/// raising threshold (#57).
|
||||
const WARM_UP_FRAMES: u32 = 10;
|
||||
|
||||
impl AdaptiveCadence {
|
||||
fn new(max_fps: u8) -> Self {
|
||||
let max_fps = max_fps.max(1);
|
||||
Self {
|
||||
max_fps,
|
||||
fps: max_fps,
|
||||
work: None,
|
||||
roomy: 0,
|
||||
warming: WARM_UP_FRAMES,
|
||||
}
|
||||
}
|
||||
|
||||
/// A new encoder, or a new size: its first frames say nothing yet.
|
||||
fn warm_up(&mut self) {
|
||||
self.warming = WARM_UP_FRAMES;
|
||||
self.work = None;
|
||||
}
|
||||
|
||||
fn fps(&self) -> u8 {
|
||||
self.fps
|
||||
}
|
||||
|
||||
fn period(fps: u8) -> Duration {
|
||||
Duration::from_secs_f64(1.0 / f64::from(fps.max(1)))
|
||||
}
|
||||
|
||||
/// Whether a frame may be encoded `since` the last one. A tenth of a
|
||||
/// period of slack absorbs the capture's own jitter.
|
||||
fn due(&self, since: Duration) -> bool {
|
||||
since >= Self::period(self.fps).mul_f64(0.9)
|
||||
}
|
||||
|
||||
/// Records the work time of an encoded frame; returns the new cadence
|
||||
/// when it changes.
|
||||
fn record(&mut self, work: Duration) -> Option<u8> {
|
||||
if self.warming > 0 {
|
||||
self.warming -= 1;
|
||||
return None;
|
||||
}
|
||||
let smoothed = match self.work {
|
||||
Some(previous) => previous.mul_f64(0.9) + work.mul_f64(0.1),
|
||||
None => work,
|
||||
};
|
||||
self.work = Some(smoothed);
|
||||
if smoothed > Self::period(self.fps).mul_f64(LOWER_ABOVE) && self.fps / 2 >= MIN_FPS {
|
||||
self.fps /= 2;
|
||||
self.roomy = 0;
|
||||
return Some(self.fps);
|
||||
}
|
||||
let faster = self.fps.saturating_mul(2).min(self.max_fps);
|
||||
if faster > self.fps && smoothed < Self::period(faster).mul_f64(RAISE_BELOW) {
|
||||
self.roomy += 1;
|
||||
if self.roomy >= RAISE_AFTER {
|
||||
self.fps = faster;
|
||||
self.roomy = 0;
|
||||
return Some(self.fps);
|
||||
}
|
||||
} else {
|
||||
self.roomy = 0;
|
||||
}
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn the_cadence_halves_when_the_work_does_not_fit_and_comes_back() {
|
||||
let mut cadence = AdaptiveCadence::new(60);
|
||||
cadence.warming = 0;
|
||||
// 15 ms of work per frame: above 85 % of the 16.7 ms period at 60 fps.
|
||||
assert_eq!(cadence.record(Duration::from_millis(15)), Some(30));
|
||||
assert_eq!(cadence.fps(), 30);
|
||||
// Light work again: back to 60 after a second of frames.
|
||||
let mut changed = None;
|
||||
for _ in 0..200 {
|
||||
changed = changed.or(cadence.record(Duration::from_millis(3)));
|
||||
}
|
||||
assert_eq!(changed, Some(60));
|
||||
assert_eq!(cadence.fps(), 60);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_cadence_never_drops_below_its_floor_nor_climbs_above_the_ceiling() {
|
||||
let mut cadence = AdaptiveCadence::new(60);
|
||||
for _ in 0..50 {
|
||||
cadence.record(Duration::from_millis(500));
|
||||
}
|
||||
assert_eq!(cadence.fps(), MIN_FPS);
|
||||
let mut thirty = AdaptiveCadence::new(30);
|
||||
for _ in 0..500 {
|
||||
thirty.record(Duration::from_millis(1));
|
||||
}
|
||||
assert_eq!(thirty.fps(), 30);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_slow_start_does_not_halve_the_cadence() {
|
||||
// A GPU pipeline: the first frames take 40 ms, then 11 ms each,
|
||||
// which fits 60 fps but not the raising threshold. Counted, the
|
||||
// start would have left it at 30 for good.
|
||||
let mut cadence = AdaptiveCadence::new(60);
|
||||
for _ in 0..WARM_UP_FRAMES {
|
||||
assert_eq!(cadence.record(Duration::from_millis(40)), None);
|
||||
}
|
||||
for _ in 0..300 {
|
||||
cadence.record(Duration::from_millis(11));
|
||||
}
|
||||
assert_eq!(cadence.fps(), 60);
|
||||
// Same after a change of size.
|
||||
cadence.warm_up();
|
||||
assert_eq!(cadence.record(Duration::from_millis(40)), None);
|
||||
assert_eq!(cadence.fps(), 60);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_frame_is_due_after_most_of_a_period() {
|
||||
let cadence = AdaptiveCadence::new(30);
|
||||
assert!(!cadence.due(Duration::from_millis(20)));
|
||||
assert!(cadence.due(Duration::from_millis(31)));
|
||||
}
|
||||
use crate::encoder::VpxEncoder;
|
||||
use rs_capture::SyntheticCapturer;
|
||||
use rs_proto::SourceId;
|
||||
|
||||
@@ -116,6 +116,13 @@ impl Context {
|
||||
VideoCodec::Vp8 => unsafe { vpx_codec_vp8_cx() },
|
||||
// SAFETY: same.
|
||||
VideoCodec::Vp9 => unsafe { vpx_codec_vp9_cx() },
|
||||
// The hardware encoder's (#57): never opened here.
|
||||
VideoCodec::H264 => {
|
||||
return Err(VpxError {
|
||||
call: "vpx_codec_enc_init",
|
||||
message: "H.264 is not a libvpx codec".into(),
|
||||
});
|
||||
}
|
||||
};
|
||||
if iface.is_null() {
|
||||
return Err(VpxError {
|
||||
@@ -190,6 +197,8 @@ impl Context {
|
||||
|
||||
fn apply_controls(&mut self, settings: &EncoderSettings) -> Result<(), VpxError> {
|
||||
match settings.codec {
|
||||
// Refused by `open`: there is no context to control.
|
||||
VideoCodec::H264 => {}
|
||||
VideoCodec::Vp8 => {
|
||||
// Negative: fixed speed, without adapting to the time left.
|
||||
// -6 is libwebrtc's value for VP8 on a desktop computer.
|
||||
|
||||
@@ -32,8 +32,9 @@ pub struct LogGuard {
|
||||
}
|
||||
|
||||
/// Where the logs live: `RUSTSCREEN_LOG_DIR`, otherwise the XDG state
|
||||
/// directory (`~/.local/state/rustscreen/logs`). Logs are state, not data:
|
||||
/// they can be deleted without losing anything important.
|
||||
/// directory (`~/.local/state/rustscreen/logs`), or `%LOCALAPPDATA%` on
|
||||
/// Windows (#93). Logs are state, not data: they can be deleted without losing
|
||||
/// anything important, and they stay on this machine.
|
||||
pub fn log_dir() -> Option<PathBuf> {
|
||||
dir_from(|name| std::env::var_os(name).map(PathBuf::from))
|
||||
}
|
||||
@@ -42,9 +43,13 @@ fn dir_from(get: impl Fn(&str) -> Option<PathBuf>) -> Option<PathBuf> {
|
||||
if let Some(dir) = get("RUSTSCREEN_LOG_DIR") {
|
||||
return Some(dir);
|
||||
}
|
||||
let state = get("XDG_STATE_HOME")
|
||||
.filter(|p| p.is_absolute())
|
||||
.or_else(|| get("HOME").map(|h| h.join(".local/state")))?;
|
||||
let state = if cfg!(windows) {
|
||||
get("LOCALAPPDATA").filter(|p| p.is_absolute())?
|
||||
} else {
|
||||
get("XDG_STATE_HOME")
|
||||
.filter(|p| p.is_absolute())
|
||||
.or_else(|| get("HOME").map(|h| h.join(".local/state")))?
|
||||
};
|
||||
Some(state.join("rustscreen").join("logs"))
|
||||
}
|
||||
|
||||
@@ -121,6 +126,17 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(windows)]
|
||||
fn local_app_data_on_windows() {
|
||||
assert_eq!(
|
||||
from_pairs(&[("LOCALAPPDATA", r"C:\Users\a\AppData\Local")]),
|
||||
Some(PathBuf::from(r"C:\Users\a\AppData\Local\rustscreen\logs"))
|
||||
);
|
||||
assert_eq!(from_pairs(&[("HOME", "/home/a")]), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(not(windows))]
|
||||
fn xdg_state_home_then_home() {
|
||||
assert_eq!(
|
||||
from_pairs(&[("XDG_STATE_HOME", "/state"), ("HOME", "/home/a")]),
|
||||
|
||||
@@ -14,7 +14,25 @@ futures-util = { version = "0.3.34", default-features = false, features = ["std"
|
||||
thiserror.workspace = true
|
||||
tokio = { version = "1", features = ["time"] }
|
||||
tracing.workspace = true
|
||||
|
||||
[target.'cfg(target_os = "linux")'.dependencies]
|
||||
zbus = { version = "6.1.0", default-features = false, features = ["tokio"] }
|
||||
|
||||
# Windows (#94): power requests, the resume notification, the registry for
|
||||
# autostart and the neighbour table for MAC addresses.
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
tokio = { version = "1", features = ["sync"] }
|
||||
windows-sys = { version = "0.61.2", features = [
|
||||
"Win32_Foundation",
|
||||
"Win32_NetworkManagement_IpHelper",
|
||||
"Win32_NetworkManagement_Ndis",
|
||||
"Win32_Networking_WinSock",
|
||||
"Win32_System_Power",
|
||||
"Win32_System_Registry",
|
||||
"Win32_System_SystemServices",
|
||||
"Win32_System_Threading",
|
||||
"Win32_UI_WindowsAndMessaging",
|
||||
] }
|
||||
|
||||
[dev-dependencies]
|
||||
tokio = { version = "1", features = ["rt", "macros"] }
|
||||
@@ -1,89 +1,69 @@
|
||||
//! Autostart when the session opens, through the XDG mechanism.
|
||||
//! Autostart when the session opens.
|
||||
//!
|
||||
//! A `.desktop` file in `~/.config/autostart`: every Linux desktop reads it,
|
||||
//! with no service and no privilege. Enabling means writing it; disabling
|
||||
//! means removing it. No other state: the setting and the file cannot drift
|
||||
//! apart silently, since [`is_enabled`] rereads the file.
|
||||
//! Linux: a `.desktop` file in `~/.config/autostart`, which every desktop
|
||||
//! reads, with no service and no privilege. Windows (#94): a value under
|
||||
//! `HKCU\Software\Microsoft\Windows\CurrentVersion\Run`, the same thing
|
||||
//! for the Windows session. Enabling means writing it, disabling means
|
||||
//! removing it. No other state: the setting and the entry cannot drift apart
|
||||
//! silently, since [`is_enabled`] rereads the entry.
|
||||
//!
|
||||
//! [`directory`] says where the entry lives: a folder on Linux, a registry key
|
||||
//! under `HKCU` on Windows. Tests pass their own.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// File name, unique to the product.
|
||||
pub const FILE_NAME: &str = "rustscreen.desktop";
|
||||
#[cfg(not(windows))]
|
||||
mod xdg;
|
||||
#[cfg(not(windows))]
|
||||
pub use xdg::{FILE_NAME, content, directory, is_enabled, refresh, set};
|
||||
|
||||
/// Where the file lives: `$XDG_CONFIG_HOME/autostart`, else `~/.config/autostart`.
|
||||
pub fn directory() -> Option<PathBuf> {
|
||||
std::env::var_os("XDG_CONFIG_HOME")
|
||||
.map(PathBuf::from)
|
||||
.filter(|p| p.is_absolute())
|
||||
.or_else(|| std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".config")))
|
||||
.map(|config| config.join("autostart"))
|
||||
}
|
||||
#[cfg(windows)]
|
||||
mod windows;
|
||||
#[cfg(windows)]
|
||||
pub use windows::{RUN_KEY, VALUE_NAME, content, directory, is_enabled, refresh, set};
|
||||
|
||||
/// The file content that launches `executable` (with its arguments).
|
||||
pub fn content(executable: &Path, arguments: &str) -> String {
|
||||
// A path with a space must be quoted (Desktop Entry specification, Exec
|
||||
// key).
|
||||
let path = executable.display().to_string();
|
||||
let path = if path.contains(' ') {
|
||||
format!("\"{}\"", path.replace('"', "\\\""))
|
||||
} else {
|
||||
path
|
||||
};
|
||||
let exec = if arguments.is_empty() {
|
||||
path
|
||||
} else {
|
||||
format!("{path} {arguments}")
|
||||
};
|
||||
format!(
|
||||
"[Desktop Entry]\n\
|
||||
Type=Application\n\
|
||||
Name=rustscreen\n\
|
||||
Comment=Screen sharing over the local network\n\
|
||||
Exec={exec}\n\
|
||||
Terminal=false\n\
|
||||
X-GNOME-Autostart-enabled=true\n"
|
||||
)
|
||||
}
|
||||
|
||||
/// Writes or removes the file in `directory`.
|
||||
pub fn set(
|
||||
directory: &Path,
|
||||
enabled: bool,
|
||||
executable: &Path,
|
||||
arguments: &str,
|
||||
) -> std::io::Result<()> {
|
||||
let file = directory.join(FILE_NAME);
|
||||
if enabled {
|
||||
std::fs::create_dir_all(directory)?;
|
||||
std::fs::write(file, content(executable, arguments))
|
||||
} else {
|
||||
match std::fs::remove_file(file) {
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
|
||||
other => other,
|
||||
}
|
||||
/// The path to write in the file for `executable`, one that survives an
|
||||
/// update (#32).
|
||||
///
|
||||
/// A Nix build runs from `/nix/store/<hash>-rustscreen/...`: the next version
|
||||
/// lives elsewhere, and the old path disappears at the next garbage collection.
|
||||
/// The profile link (`~/.nix-profile/bin/rustscreen`,
|
||||
/// `/run/current-system/sw/bin/rustscreen`) follows the updates: when the
|
||||
/// `PATH` has one, it is the one written. Any other path is kept as is.
|
||||
pub fn launcher(executable: &Path, path_var: Option<&std::ffi::OsStr>) -> PathBuf {
|
||||
if !executable.starts_with("/nix/store") {
|
||||
return executable.to_path_buf();
|
||||
}
|
||||
path_var
|
||||
.into_iter()
|
||||
.flat_map(std::env::split_paths)
|
||||
.filter(|dir| !dir.starts_with("/nix/store"))
|
||||
.map(|dir| dir.join(COMMAND))
|
||||
.find(|candidate| candidate.is_file())
|
||||
.unwrap_or_else(|| executable.to_path_buf())
|
||||
}
|
||||
|
||||
pub fn is_enabled(directory: &Path) -> bool {
|
||||
directory.join(FILE_NAME).is_file()
|
||||
}
|
||||
/// Name of the desktop application's command.
|
||||
const COMMAND: &str = "rustscreen";
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn enabling_writes_the_file_and_disabling_removes_it() {
|
||||
let directory = std::env::temp_dir().join(format!("rs-autostart-{}", std::process::id()));
|
||||
let exe = Path::new("/opt/rust screen/rustscreen-desktop");
|
||||
set(&directory, true, exe, "--cache").unwrap();
|
||||
assert!(is_enabled(&directory));
|
||||
let text = std::fs::read_to_string(directory.join(FILE_NAME)).unwrap();
|
||||
assert!(text.contains("Exec=\"/opt/rust screen/rustscreen-desktop\" --cache"));
|
||||
set(&directory, false, exe, "").unwrap();
|
||||
assert!(!is_enabled(&directory));
|
||||
// Disabling twice is not an error.
|
||||
set(&directory, false, exe, "").unwrap();
|
||||
let _ = std::fs::remove_dir_all(&directory);
|
||||
fn a_nix_store_path_gives_way_to_the_profile_link() {
|
||||
let profile = std::env::temp_dir().join(format!("rs-profile-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&profile).unwrap();
|
||||
std::fs::write(profile.join(COMMAND), "").unwrap();
|
||||
let store = Path::new("/nix/store/abc-rustscreen/bin/.rustscreen-wrapped");
|
||||
let path = std::env::join_paths(["/nix/store/abc-rustscreen/bin".into(), profile.clone()])
|
||||
.unwrap();
|
||||
assert_eq!(launcher(store, Some(&path)), profile.join(COMMAND));
|
||||
// Not found on the PATH: the store path, rather than nothing.
|
||||
assert_eq!(launcher(store, None), store);
|
||||
// Outside Nix (AppImage, package): unchanged.
|
||||
let usr = Path::new("/usr/bin/rustscreen");
|
||||
assert_eq!(launcher(usr, Some(&path)), usr);
|
||||
let _ = std::fs::remove_dir_all(&profile);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,208 @@
|
||||
//! Autostart on Windows: a value of the `Run` key of the current user.
|
||||
//!
|
||||
//! No administrator rights: `HKEY_CURRENT_USER` belongs to the user, and
|
||||
//! Windows starts every command listed there when the session opens. Task
|
||||
//! Manager shows it under "Startup apps", where the user can also turn it off.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use windows_sys::Win32::Foundation::{ERROR_FILE_NOT_FOUND, ERROR_SUCCESS};
|
||||
use windows_sys::Win32::System::Registry::{
|
||||
HKEY, HKEY_CURRENT_USER, KEY_QUERY_VALUE, KEY_SET_VALUE, REG_OPTION_NON_VOLATILE, REG_SZ,
|
||||
RRF_RT_REG_SZ, RegCloseKey, RegCreateKeyExW, RegDeleteValueW, RegGetValueW, RegSetValueExW,
|
||||
};
|
||||
|
||||
/// The key Windows reads at logon, under `HKEY_CURRENT_USER`.
|
||||
pub const RUN_KEY: &str = r"Software\Microsoft\Windows\CurrentVersion\Run";
|
||||
/// The name of the value, unique to the product.
|
||||
pub const VALUE_NAME: &str = "rustscreen";
|
||||
|
||||
/// Where the entry lives: the `Run` key, under `HKEY_CURRENT_USER`.
|
||||
pub fn directory() -> Option<PathBuf> {
|
||||
Some(PathBuf::from(RUN_KEY))
|
||||
}
|
||||
|
||||
/// The command line Windows runs: the quoted executable, then the arguments.
|
||||
pub fn content(executable: &Path, arguments: &str) -> String {
|
||||
let path = format!("\"{}\"", executable.display());
|
||||
if arguments.is_empty() {
|
||||
path
|
||||
} else {
|
||||
format!("{path} {arguments}")
|
||||
}
|
||||
}
|
||||
|
||||
/// Rewrites the value if autostart is on and its command is stale: an update
|
||||
/// may have moved the executable (#32). Off, nothing is written.
|
||||
pub fn refresh(key: &Path, executable: &Path, arguments: &str) -> std::io::Result<bool> {
|
||||
let Some(current) = read(key)? else {
|
||||
return Ok(false);
|
||||
};
|
||||
let wanted = content(executable, arguments);
|
||||
if current == wanted {
|
||||
return Ok(false);
|
||||
}
|
||||
write(key, &wanted)?;
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// Writes or removes the value under `key`.
|
||||
pub fn set(key: &Path, enabled: bool, executable: &Path, arguments: &str) -> std::io::Result<()> {
|
||||
if enabled {
|
||||
write(key, &content(executable, arguments))
|
||||
} else {
|
||||
let handle = open(key)?;
|
||||
let name = wide(VALUE_NAME);
|
||||
// SAFETY: `handle` is open, `name` is NUL-terminated.
|
||||
let status = unsafe { RegDeleteValueW(handle.0, name.as_ptr()) };
|
||||
match status {
|
||||
ERROR_SUCCESS | ERROR_FILE_NOT_FOUND => Ok(()),
|
||||
error => Err(os_error(error)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn is_enabled(key: &Path) -> bool {
|
||||
matches!(read(key), Ok(Some(_)))
|
||||
}
|
||||
|
||||
/// An open key, closed on drop.
|
||||
struct Key(HKEY);
|
||||
|
||||
impl Drop for Key {
|
||||
fn drop(&mut self) {
|
||||
// SAFETY: opened by `open`, closed once.
|
||||
unsafe { RegCloseKey(self.0) };
|
||||
}
|
||||
}
|
||||
|
||||
/// Opens `key` under `HKEY_CURRENT_USER`, creating it if needed.
|
||||
fn open(key: &Path) -> std::io::Result<Key> {
|
||||
let subkey = wide(&key.to_string_lossy());
|
||||
let mut handle: HKEY = std::ptr::null_mut();
|
||||
// SAFETY: `subkey` is NUL-terminated, `handle` receives the key.
|
||||
let status = unsafe {
|
||||
RegCreateKeyExW(
|
||||
HKEY_CURRENT_USER,
|
||||
subkey.as_ptr(),
|
||||
0,
|
||||
std::ptr::null(),
|
||||
REG_OPTION_NON_VOLATILE,
|
||||
KEY_SET_VALUE | KEY_QUERY_VALUE,
|
||||
std::ptr::null(),
|
||||
&mut handle,
|
||||
std::ptr::null_mut(),
|
||||
)
|
||||
};
|
||||
if status != ERROR_SUCCESS {
|
||||
return Err(os_error(status));
|
||||
}
|
||||
Ok(Key(handle))
|
||||
}
|
||||
|
||||
fn write(key: &Path, command: &str) -> std::io::Result<()> {
|
||||
let handle = open(key)?;
|
||||
let name = wide(VALUE_NAME);
|
||||
let data = wide(command);
|
||||
// SAFETY: `data` holds `data.len()` UTF-16 units, terminator included,
|
||||
// as REG_SZ wants.
|
||||
let status = unsafe {
|
||||
RegSetValueExW(
|
||||
handle.0,
|
||||
name.as_ptr(),
|
||||
0,
|
||||
REG_SZ,
|
||||
data.as_ptr().cast(),
|
||||
(data.len() * 2) as u32,
|
||||
)
|
||||
};
|
||||
if status != ERROR_SUCCESS {
|
||||
return Err(os_error(status));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The command of the value, `None` when there is none.
|
||||
fn read(key: &Path) -> std::io::Result<Option<String>> {
|
||||
let subkey = wide(&key.to_string_lossy());
|
||||
let name = wide(VALUE_NAME);
|
||||
// A command line, a path and a few arguments: 32 KiB is the limit of a
|
||||
// command line on Windows.
|
||||
let mut buffer = vec![0u16; 16 * 1024];
|
||||
let mut size = (buffer.len() * 2) as u32;
|
||||
// SAFETY: `buffer` holds `size` bytes; RegGetValueW NUL-terminates.
|
||||
let status = unsafe {
|
||||
RegGetValueW(
|
||||
HKEY_CURRENT_USER,
|
||||
subkey.as_ptr(),
|
||||
name.as_ptr(),
|
||||
RRF_RT_REG_SZ,
|
||||
std::ptr::null_mut(),
|
||||
buffer.as_mut_ptr().cast(),
|
||||
&mut size,
|
||||
)
|
||||
};
|
||||
match status {
|
||||
ERROR_SUCCESS => {
|
||||
let units = (size as usize / 2).saturating_sub(1);
|
||||
Ok(Some(String::from_utf16_lossy(&buffer[..units])))
|
||||
}
|
||||
ERROR_FILE_NOT_FOUND => Ok(None),
|
||||
error => Err(os_error(error)),
|
||||
}
|
||||
}
|
||||
|
||||
fn wide(text: &str) -> Vec<u16> {
|
||||
text.encode_utf16().chain(Some(0)).collect()
|
||||
}
|
||||
|
||||
fn os_error(status: u32) -> std::io::Error {
|
||||
std::io::Error::from_raw_os_error(status as i32)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// A key of its own: the user's real `Run` key is never touched.
|
||||
fn test_key(name: &str) -> PathBuf {
|
||||
PathBuf::from(format!(
|
||||
r"Software\rustscreen-tests\{name}-{}",
|
||||
std::process::id()
|
||||
))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn enabling_writes_the_value_and_disabling_removes_it() {
|
||||
let key = test_key("set");
|
||||
let exe = Path::new(r"C:\Program Files\rustscreen\rustscreen.exe");
|
||||
set(&key, true, exe, "--autostarted").unwrap();
|
||||
assert!(is_enabled(&key));
|
||||
assert_eq!(
|
||||
read(&key).unwrap().as_deref(),
|
||||
Some(r#""C:\Program Files\rustscreen\rustscreen.exe" --autostarted"#)
|
||||
);
|
||||
set(&key, false, exe, "").unwrap();
|
||||
assert!(!is_enabled(&key));
|
||||
// Disabling twice is not an error.
|
||||
set(&key, false, exe, "").unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refreshing_rewrites_a_stale_value_only_when_enabled() {
|
||||
let key = test_key("refresh");
|
||||
let old = Path::new(r"C:\old\rustscreen.exe");
|
||||
let new = Path::new(r"C:\new\rustscreen.exe");
|
||||
assert!(
|
||||
!refresh(&key, new, "--autostarted").unwrap(),
|
||||
"off: nothing written"
|
||||
);
|
||||
set(&key, true, old, "--autostarted").unwrap();
|
||||
assert!(refresh(&key, new, "--autostarted").unwrap());
|
||||
assert!(
|
||||
!refresh(&key, new, "--autostarted").unwrap(),
|
||||
"already fresh"
|
||||
);
|
||||
set(&key, false, new, "").unwrap();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
//! Autostart on Linux: the XDG `.desktop` file.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// File name, unique to the product.
|
||||
pub const FILE_NAME: &str = "rustscreen.desktop";
|
||||
|
||||
/// Where the file lives: `$XDG_CONFIG_HOME/autostart`, else `~/.config/autostart`.
|
||||
pub fn directory() -> Option<PathBuf> {
|
||||
std::env::var_os("XDG_CONFIG_HOME")
|
||||
.map(PathBuf::from)
|
||||
.filter(|p| p.is_absolute())
|
||||
.or_else(|| std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".config")))
|
||||
.map(|config| config.join("autostart"))
|
||||
}
|
||||
|
||||
/// Rewrites the file if autostart is on and its content is stale: an update
|
||||
/// may have moved the executable (#32). Off, nothing is written.
|
||||
pub fn refresh(directory: &Path, executable: &Path, arguments: &str) -> std::io::Result<bool> {
|
||||
let file = directory.join(FILE_NAME);
|
||||
let Ok(current) = std::fs::read_to_string(&file) else {
|
||||
return Ok(false);
|
||||
};
|
||||
let wanted = content(executable, arguments);
|
||||
if current == wanted {
|
||||
return Ok(false);
|
||||
}
|
||||
std::fs::write(file, wanted)?;
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// The file content that launches `executable` (with its arguments).
|
||||
pub fn content(executable: &Path, arguments: &str) -> String {
|
||||
// A path with a space must be quoted (Desktop Entry specification, Exec
|
||||
// key).
|
||||
let path = executable.display().to_string();
|
||||
let path = if path.contains(' ') {
|
||||
format!("\"{}\"", path.replace('"', "\\\""))
|
||||
} else {
|
||||
path
|
||||
};
|
||||
let exec = if arguments.is_empty() {
|
||||
path
|
||||
} else {
|
||||
format!("{path} {arguments}")
|
||||
};
|
||||
format!(
|
||||
"[Desktop Entry]\n\
|
||||
Type=Application\n\
|
||||
Name=rustscreen\n\
|
||||
Comment=Screen sharing over the local network\n\
|
||||
Exec={exec}\n\
|
||||
Terminal=false\n\
|
||||
X-GNOME-Autostart-enabled=true\n"
|
||||
)
|
||||
}
|
||||
|
||||
/// Writes or removes the file in `directory`.
|
||||
pub fn set(
|
||||
directory: &Path,
|
||||
enabled: bool,
|
||||
executable: &Path,
|
||||
arguments: &str,
|
||||
) -> std::io::Result<()> {
|
||||
let file = directory.join(FILE_NAME);
|
||||
if enabled {
|
||||
std::fs::create_dir_all(directory)?;
|
||||
std::fs::write(file, content(executable, arguments))
|
||||
} else {
|
||||
match std::fs::remove_file(file) {
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
|
||||
other => other,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn is_enabled(directory: &Path) -> bool {
|
||||
directory.join(FILE_NAME).is_file()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn enabling_writes_the_file_and_disabling_removes_it() {
|
||||
let directory = std::env::temp_dir().join(format!("rs-autostart-{}", std::process::id()));
|
||||
let exe = Path::new("/opt/rust screen/rustscreen-desktop");
|
||||
set(&directory, true, exe, "--cache").unwrap();
|
||||
assert!(is_enabled(&directory));
|
||||
let text = std::fs::read_to_string(directory.join(FILE_NAME)).unwrap();
|
||||
assert!(text.contains("Exec=\"/opt/rust screen/rustscreen-desktop\" --cache"));
|
||||
set(&directory, false, exe, "").unwrap();
|
||||
assert!(!is_enabled(&directory));
|
||||
// Disabling twice is not an error.
|
||||
set(&directory, false, exe, "").unwrap();
|
||||
let _ = std::fs::remove_dir_all(&directory);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refreshing_rewrites_a_stale_file_only_when_enabled() {
|
||||
let directory =
|
||||
std::env::temp_dir().join(format!("rs-autostart-refresh-{}", std::process::id()));
|
||||
let old = Path::new("/nix/store/old/bin/rustscreen");
|
||||
let new = Path::new("/nix/store/new/bin/rustscreen");
|
||||
assert!(
|
||||
!refresh(&directory, new, "--autostarted").unwrap(),
|
||||
"off: nothing written"
|
||||
);
|
||||
assert!(!is_enabled(&directory));
|
||||
set(&directory, true, old, "--autostarted").unwrap();
|
||||
assert!(refresh(&directory, new, "--autostarted").unwrap());
|
||||
let text = std::fs::read_to_string(directory.join(FILE_NAME)).unwrap();
|
||||
assert!(
|
||||
text.contains("Exec=/nix/store/new/bin/rustscreen --autostarted"),
|
||||
"{text}"
|
||||
);
|
||||
assert!(
|
||||
!refresh(&directory, new, "--autostarted").unwrap(),
|
||||
"already fresh"
|
||||
);
|
||||
let _ = std::fs::remove_dir_all(&directory);
|
||||
}
|
||||
}
|
||||
@@ -13,6 +13,8 @@ use crate::portal::PortalInfo;
|
||||
pub enum SessionType {
|
||||
Wayland,
|
||||
X11,
|
||||
/// A Windows desktop (#8): GDI reads every monitor and window.
|
||||
Windows,
|
||||
/// Session without a display server: capture and virtual display impossible.
|
||||
Headless,
|
||||
}
|
||||
@@ -63,7 +65,12 @@ pub struct Environment {
|
||||
impl Environment {
|
||||
/// Reads the real environment of the process.
|
||||
pub fn detect() -> Self {
|
||||
Self::from_vars(|name| std::env::var(name).ok())
|
||||
let mut environment = Self::from_vars(|name| std::env::var(name).ok());
|
||||
// A Windows session has none of these variables: the system says it.
|
||||
if cfg!(windows) {
|
||||
environment.session = SessionType::Windows;
|
||||
}
|
||||
environment
|
||||
}
|
||||
|
||||
/// Injectable detection, for tests.
|
||||
@@ -118,6 +125,8 @@ impl Environment {
|
||||
match self.session {
|
||||
SessionType::Headless => VirtualDisplayBackend::NotApplicable,
|
||||
SessionType::X11 => VirtualDisplayBackend::Evdi,
|
||||
// An IddCx driver would do it, and is an extension (ROADMAP).
|
||||
SessionType::Windows => VirtualDisplayBackend::Unsupported,
|
||||
SessionType::Wayland => {
|
||||
if portal.is_some_and(PortalInfo::supports_virtual_display) {
|
||||
VirtualDisplayBackend::PortalVirtual
|
||||
@@ -134,7 +143,7 @@ impl Environment {
|
||||
pub fn advice(&self, portal: Option<&PortalInfo>) -> &'static str {
|
||||
match self.virtual_display_backend(portal) {
|
||||
VirtualDisplayBackend::PortalVirtual => {
|
||||
"virtual display available through the portal: --virtuel extends the desktop \
|
||||
"virtual display available through the portal: --virtual extends the desktop \
|
||||
onto the tablet"
|
||||
}
|
||||
VirtualDisplayBackend::WlrootsHeadless => {
|
||||
|
||||
@@ -50,14 +50,18 @@ pub fn interfaces() -> Vec<NetworkInterface> {
|
||||
None => list.push(NetworkInterface {
|
||||
name: interface.name.clone(),
|
||||
addresses: vec![ip],
|
||||
active: false,
|
||||
// Windows gives the adapter's state with its addresses; Linux
|
||||
// reads sysfs below, which also knows VPN links.
|
||||
active: !cfg!(target_os = "linux") && oper_up(&interface.oper_status),
|
||||
loopback: interface.is_loopback(),
|
||||
}),
|
||||
}
|
||||
}
|
||||
for interface in &mut list {
|
||||
interface.addresses.sort_by_key(|ip| !ip.is_ipv4());
|
||||
interface.active = is_up(link_state(&interface.name).as_deref());
|
||||
if cfg!(target_os = "linux") {
|
||||
interface.active = is_up(link_state(&interface.name).as_deref());
|
||||
}
|
||||
}
|
||||
list.sort_by(|a, b| (a.loopback, &a.name).cmp(&(b.loopback, &b.name)));
|
||||
list
|
||||
@@ -75,6 +79,12 @@ fn link_state(name: &str) -> Option<String> {
|
||||
.map(|s| s.trim().to_string())
|
||||
}
|
||||
|
||||
/// The state an adapter reports outside Linux: the same rule as [`is_up`].
|
||||
fn oper_up(status: &if_addrs::IfOperStatus) -> bool {
|
||||
use if_addrs::IfOperStatus::{Dormant, Down, LowerLayerDown, NotPresent};
|
||||
!matches!(status, Down | Dormant | LowerLayerDown | NotPresent)
|
||||
}
|
||||
|
||||
/// `unknown` is the state of many virtual interfaces (VPN, tun) that work
|
||||
/// nonetheless: only an interface explicitly `down` (or `dormant`,
|
||||
/// `lowerlayerdown`) is considered cut off.
|
||||
@@ -129,3 +139,133 @@ mod tests {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The MAC address behind `ip`, from the kernel's neighbour table (#38).
|
||||
///
|
||||
/// Only a device on the same link has one there: behind a router, the table
|
||||
/// holds the router's address under the router's IP, never under the
|
||||
/// device's, so the answer is `None` (unknown) rather than a wrong MAC. IPv6
|
||||
/// neighbours are not read: `None` as well. Never logged, never in the
|
||||
/// diagnostics (ADR 0008).
|
||||
pub fn mac_address(ip: std::net::IpAddr) -> Option<String> {
|
||||
let ip = match ip {
|
||||
std::net::IpAddr::V4(v4) => v4,
|
||||
std::net::IpAddr::V6(v6) => v6.to_ipv4_mapped()?,
|
||||
};
|
||||
#[cfg(windows)]
|
||||
return windows::neighbour_mac(ip);
|
||||
#[cfg(not(windows))]
|
||||
{
|
||||
let table = std::fs::read_to_string("/proc/net/arp").ok()?;
|
||||
mac_in_arp_table(&table, ip)
|
||||
}
|
||||
}
|
||||
|
||||
/// A hardware address as the interface shows it: lowercase, colon separated.
|
||||
/// `None` for an empty or all-zero one (an incomplete neighbour).
|
||||
pub fn format_mac(bytes: &[u8]) -> Option<String> {
|
||||
(!bytes.is_empty() && bytes.iter().any(|b| *b != 0)).then(|| {
|
||||
bytes
|
||||
.iter()
|
||||
.map(|b| format!("{b:02x}"))
|
||||
.collect::<Vec<_>>()
|
||||
.join(":")
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
mod windows {
|
||||
use std::net::Ipv4Addr;
|
||||
|
||||
use windows_sys::Win32::NetworkManagement::IpHelper::{
|
||||
FreeMibTable, GetIpNetTable2, MIB_IPNET_TABLE2,
|
||||
};
|
||||
use windows_sys::Win32::Networking::WinSock::{AF_INET, NlnsIncomplete, NlnsUnreachable};
|
||||
|
||||
/// The neighbour table (`GetIpNetTable2`, what `arp -a` shows), IPv4.
|
||||
pub(super) fn neighbour_mac(ip: Ipv4Addr) -> Option<String> {
|
||||
let mut table: *mut MIB_IPNET_TABLE2 = std::ptr::null_mut();
|
||||
// SAFETY: on success Windows allocates the table, freed below.
|
||||
if unsafe { GetIpNetTable2(AF_INET, &mut table) } != 0 || table.is_null() {
|
||||
return None;
|
||||
}
|
||||
// SAFETY: `NumEntries` rows follow the header, in the same block.
|
||||
let rows = unsafe {
|
||||
std::slice::from_raw_parts((*table).Table.as_ptr(), (*table).NumEntries as usize)
|
||||
};
|
||||
let found = rows.iter().find_map(|row| {
|
||||
// SAFETY: AF_INET was asked for: every row is an IPv4 address,
|
||||
// stored in network order.
|
||||
let address = unsafe { row.Address.Ipv4.sin_addr.S_un.S_addr };
|
||||
let usable = row.State != NlnsIncomplete && row.State != NlnsUnreachable;
|
||||
let length = (row.PhysicalAddressLength as usize).min(row.PhysicalAddress.len());
|
||||
(Ipv4Addr::from(address.to_ne_bytes()) == ip && usable)
|
||||
.then(|| super::format_mac(&row.PhysicalAddress[..length]))
|
||||
.flatten()
|
||||
});
|
||||
// SAFETY: allocated by GetIpNetTable2, freed once.
|
||||
unsafe { FreeMibTable(table.cast()) };
|
||||
found
|
||||
}
|
||||
}
|
||||
|
||||
/// The lookup in the text of `/proc/net/arp`: complete entries only (flag
|
||||
/// `0x2`), never the all-zero address of an incomplete one.
|
||||
pub fn mac_in_arp_table(table: &str, ip: std::net::Ipv4Addr) -> Option<String> {
|
||||
const COMPLETE: u32 = 0x2;
|
||||
table.lines().skip(1).find_map(|line| {
|
||||
let fields: Vec<&str> = line.split_whitespace().collect();
|
||||
let [address, _, flags, mac, ..] = fields.as_slice() else {
|
||||
return None;
|
||||
};
|
||||
let flags = u32::from_str_radix(flags.trim_start_matches("0x"), 16).ok()?;
|
||||
(address.parse::<std::net::Ipv4Addr>().ok()? == ip
|
||||
&& flags & COMPLETE != 0
|
||||
&& *mac != "00:00:00:00:00:00")
|
||||
.then(|| mac.to_ascii_lowercase())
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod arp_tests {
|
||||
use super::*;
|
||||
|
||||
const TABLE: &str = "\
|
||||
IP address HW type Flags HW address Mask Device
|
||||
172.17.0.32 0x1 0x0 00:00:00:00:00:00 * docker0
|
||||
192.168.100.37 0x1 0x2 1C:83:41:41:A3:E8 * wlp0s20f3
|
||||
192.168.100.40 0x1 0x0 34:5a:60:43:b3:33 * wlp0s20f3
|
||||
";
|
||||
|
||||
#[test]
|
||||
fn a_hardware_address_reads_like_the_linux_one() {
|
||||
assert_eq!(
|
||||
format_mac(&[0x1c, 0x83, 0x41, 0x41, 0xa3, 0xe8]).as_deref(),
|
||||
Some("1c:83:41:41:a3:e8")
|
||||
);
|
||||
assert_eq!(format_mac(&[0; 6]), None);
|
||||
assert_eq!(format_mac(&[]), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_complete_entry_gives_the_mac() {
|
||||
assert_eq!(
|
||||
mac_in_arp_table(TABLE, "192.168.100.37".parse().unwrap()).as_deref(),
|
||||
Some("1c:83:41:41:a3:e8")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn incomplete_or_absent_is_unknown_not_wrong() {
|
||||
assert_eq!(
|
||||
mac_in_arp_table(TABLE, "172.17.0.32".parse().unwrap()),
|
||||
None
|
||||
);
|
||||
assert_eq!(
|
||||
mac_in_arp_table(TABLE, "192.168.100.40".parse().unwrap()),
|
||||
None
|
||||
);
|
||||
// Behind a router: the device's IP is not in the table.
|
||||
assert_eq!(mac_in_arp_table(TABLE, "10.1.2.3".parse().unwrap()), None);
|
||||
}
|
||||
}
|
||||
@@ -9,38 +9,28 @@
|
||||
//! Consuming the frames needs `libpipewire`, a system dependency that the
|
||||
//! negotiation does not need. Keeping the two apart lets the negotiation be
|
||||
//! checked alone, on a machine with a desktop, before adding the rest.
|
||||
//!
|
||||
//! The portal exists on Linux only. Elsewhere, [`probe`] and [`Session::open`]
|
||||
//! fail with [`PortalError::Unsupported`], and the host offers the sources of
|
||||
//! that system instead.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::os::fd::OwnedFd;
|
||||
use std::sync::atomic::{AtomicU32, Ordering};
|
||||
use std::time::Duration;
|
||||
|
||||
use futures_util::StreamExt;
|
||||
use zbus::{Connection, MatchRule, MessageStream};
|
||||
use zbus::{OwnedObjectPath, OwnedVariant, Variant};
|
||||
#[cfg(target_os = "linux")]
|
||||
mod dbus;
|
||||
#[cfg(target_os = "linux")]
|
||||
pub use dbus::{Session, SessionClosed, Stream, probe};
|
||||
|
||||
const BUS: &str = "org.freedesktop.portal.Desktop";
|
||||
const PORTAL_PATH: &str = "/org/freedesktop/portal/desktop";
|
||||
const PROPERTIES_INTERFACE: &str = "org.freedesktop.DBus.Properties";
|
||||
const SCREENCAST_INTERFACE: &str = "org.freedesktop.portal.ScreenCast";
|
||||
const REQUEST_INTERFACE: &str = "org.freedesktop.portal.Request";
|
||||
const SESSION_INTERFACE: &str = "org.freedesktop.portal.Session";
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
mod unsupported;
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
pub use unsupported::{Session, SessionClosed, Stream, probe};
|
||||
|
||||
/// Source types of `SelectSources`, as a bit mask.
|
||||
pub const TYPE_MONITOR: u32 = 1;
|
||||
pub const TYPE_WINDOW: u32 = 2;
|
||||
pub const TYPE_VIRTUAL: u32 = 4;
|
||||
|
||||
/// Token counter: one request object per call. A reused token makes the
|
||||
/// portal answer on an already consumed object, and the answer is lost.
|
||||
static COUNTER: AtomicU32 = AtomicU32::new(0);
|
||||
|
||||
/// Token unique within this process, valid in a D-Bus path.
|
||||
fn token(prefix: &str) -> String {
|
||||
let n = COUNTER.fetch_add(1, Ordering::Relaxed);
|
||||
format!("rustscreen_{}_{prefix}_{n}", std::process::id())
|
||||
}
|
||||
|
||||
/// The portal waits for the user's answer in front of a picker. Two minutes
|
||||
/// leave time to choose a display, without leaving a service blocked forever
|
||||
/// if nobody answers.
|
||||
@@ -60,6 +50,9 @@ pub enum PortalError {
|
||||
Timeout,
|
||||
#[error("the portal returned an answer without a usable stream: {0}")]
|
||||
NoStream(String),
|
||||
/// Not a Linux desktop: there is no portal to ask.
|
||||
#[error("no desktop portal on this system")]
|
||||
Unsupported,
|
||||
}
|
||||
|
||||
/// What the portal announces.
|
||||
@@ -96,502 +89,3 @@ pub enum SourceType {
|
||||
/// only that window; once minimised, it stops sending frames.
|
||||
Window,
|
||||
}
|
||||
|
||||
impl SourceType {
|
||||
fn mask(self) -> u32 {
|
||||
match self {
|
||||
Self::Monitor => TYPE_MONITOR,
|
||||
Self::Virtual => TYPE_VIRTUAL,
|
||||
Self::Window => TYPE_WINDOW,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A captured stream: the PipeWire descriptor and its node identifier.
|
||||
pub struct Stream {
|
||||
pub node_id: u32,
|
||||
pub fd: OwnedFd,
|
||||
/// Size announced by the portal, when it provides one.
|
||||
pub size: Option<(u32, u32)>,
|
||||
/// Token that avoids asking for the choice again at the next launch, when
|
||||
/// the portal returns one (persistent mode).
|
||||
pub restore_token: Option<String>,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for Stream {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("Stream")
|
||||
.field("node_id", &self.node_id)
|
||||
.field("size", &self.size)
|
||||
.field("fd", &self.fd)
|
||||
.field("restorable", &self.restore_token.is_some())
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
/// An open screencast session. Keeping it alive keeps the capture going;
|
||||
/// closing it frees the stream and stops the share on the portal side.
|
||||
pub struct Session {
|
||||
connection: Connection,
|
||||
path: OwnedObjectPath,
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// Opens a screencast session.
|
||||
///
|
||||
/// Shows nothing yet: the picker only appears at the `start` step, which
|
||||
/// leaves time to choose the options.
|
||||
pub async fn open() -> Result<Self, PortalError> {
|
||||
let connection = Connection::session()
|
||||
.await
|
||||
.map_err(|e| PortalError::Bus(e.to_string()))?;
|
||||
|
||||
let mut options: HashMap<String, Variant> = HashMap::new();
|
||||
let session_token = token("session");
|
||||
options.insert(
|
||||
"session_handle_token".into(),
|
||||
Variant::from(session_token.as_str()),
|
||||
);
|
||||
let token = token("create");
|
||||
options.insert("handle_token".into(), Variant::from(token.as_str()));
|
||||
|
||||
let results = call(
|
||||
&connection,
|
||||
PORTAL_PATH,
|
||||
SCREENCAST_INTERFACE,
|
||||
"CreateSession",
|
||||
&(options,),
|
||||
&token,
|
||||
)
|
||||
.await?;
|
||||
|
||||
let handle = results
|
||||
.get("session_handle")
|
||||
.ok_or_else(|| PortalError::Response("session_handle missing".into()))?;
|
||||
let path = match &**handle {
|
||||
Variant::Str(path) => {
|
||||
OwnedObjectPath::try_from(path.as_str()).map_err(|e| e.to_string())
|
||||
}
|
||||
// An ObjectPath can be owned without any possible failure.
|
||||
Variant::ObjectPath(path) => Ok::<_, String>(OwnedObjectPath::from(path.clone())),
|
||||
other => {
|
||||
return Err(PortalError::Response(format!(
|
||||
"session_handle of unexpected type: {other:?}"
|
||||
)));
|
||||
}
|
||||
}
|
||||
.map_err(PortalError::Response)?;
|
||||
|
||||
Ok(Self { connection, path })
|
||||
}
|
||||
|
||||
/// Asks to share a whole display, existing or virtual.
|
||||
///
|
||||
/// `multiple` stays false: a second display does not need to be multiple,
|
||||
/// and a simple picker is less intimidating.
|
||||
pub async fn select_monitor(&self, restore: Option<&str>) -> Result<(), PortalError> {
|
||||
self.select_source(SourceType::Monitor, restore).await
|
||||
}
|
||||
|
||||
/// Asks for a source of the given type. For a virtual display, the picker
|
||||
/// has nothing to offer: GNOME creates it directly, at the size the
|
||||
/// PipeWire consumer will set.
|
||||
pub async fn select_source(
|
||||
&self,
|
||||
source_type: SourceType,
|
||||
restore: Option<&str>,
|
||||
) -> Result<(), PortalError> {
|
||||
let mut options: HashMap<String, Variant> = HashMap::new();
|
||||
let token = token("sources");
|
||||
options.insert("handle_token".into(), Variant::from(token.as_str()));
|
||||
options.insert("types".into(), Variant::from(source_type.mask()));
|
||||
options.insert("multiple".into(), Variant::from(false));
|
||||
// Cursor embedded in the frame: without it, a viewer does not see
|
||||
// where the host clicks, which makes the share useless for explaining.
|
||||
options.insert("cursor_mode".into(), Variant::from(2u32));
|
||||
// A virtual display has nothing to restore: it is recreated every
|
||||
// time. For a monitor, 2 = persistent: the portal returns a token that
|
||||
// avoids confirming the choice again at each launch.
|
||||
if source_type == SourceType::Monitor {
|
||||
if let Some(restore_token) = restore {
|
||||
options.insert(
|
||||
"restore_token".into(),
|
||||
Variant::from(restore_token.to_string()),
|
||||
);
|
||||
}
|
||||
options.insert("persist_mode".into(), Variant::from(2u32));
|
||||
}
|
||||
|
||||
call(
|
||||
&self.connection,
|
||||
// The methods live on the portal object; the session is the first
|
||||
// argument, not the target of the call.
|
||||
PORTAL_PATH,
|
||||
SCREENCAST_INTERFACE,
|
||||
"SelectSources",
|
||||
&(&self.path, options),
|
||||
&token,
|
||||
)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Starts the capture. This is where the picker shows up.
|
||||
pub async fn start(&self) -> Result<Stream, PortalError> {
|
||||
let mut options: HashMap<String, Variant> = HashMap::new();
|
||||
let token = token("start");
|
||||
options.insert("handle_token".into(), Variant::from(token.as_str()));
|
||||
|
||||
// Start takes three arguments: session, parent window (empty: no modal
|
||||
// dialog attached to a window), options.
|
||||
let results = call(
|
||||
&self.connection,
|
||||
// The methods live on the portal object; the session is the first
|
||||
// argument, not the target of the call.
|
||||
PORTAL_PATH,
|
||||
SCREENCAST_INTERFACE,
|
||||
"Start",
|
||||
&(&self.path, "", options),
|
||||
&token,
|
||||
)
|
||||
.await?;
|
||||
|
||||
let (node_id, size) = first_stream(results.get("streams"))?;
|
||||
let restore_token = results
|
||||
.get("restore_token")
|
||||
.and_then(|v| String::try_from(v.clone()).ok());
|
||||
|
||||
// The descriptor is not in the answer to `Start`: it is requested
|
||||
// separately, through `OpenPipeWireRemote`, once the capture is granted.
|
||||
let options: HashMap<String, Variant> = HashMap::new();
|
||||
let reply = self
|
||||
.connection
|
||||
.call_method(
|
||||
Some(BUS),
|
||||
PORTAL_PATH,
|
||||
Some(SCREENCAST_INTERFACE),
|
||||
"OpenPipeWireRemote",
|
||||
&(&self.path, options),
|
||||
)
|
||||
.await
|
||||
.map_err(|e| PortalError::NoStream(format!("OpenPipeWireRemote: {e}")))?;
|
||||
// Deserialization duplicates the descriptor (`dup`): the copy belongs
|
||||
// to us and outlives the D-Bus message that carried the original.
|
||||
let fd: OwnedFd = reply
|
||||
.body()
|
||||
.deserialize::<zbus::OwnedFd>()
|
||||
.map_err(|e| PortalError::NoStream(format!("unreadable descriptor: {e}")))?
|
||||
.into();
|
||||
Ok(Stream {
|
||||
node_id,
|
||||
fd,
|
||||
size,
|
||||
restore_token,
|
||||
})
|
||||
}
|
||||
|
||||
/// Closes the session on the portal side. The session object carries
|
||||
/// `Close`, not the request object: calling the latter closes nothing.
|
||||
pub async fn close(&self) {
|
||||
let _ = self
|
||||
.connection
|
||||
.call_method(
|
||||
Some(BUS),
|
||||
self.path.as_str(),
|
||||
Some(SESSION_INTERFACE),
|
||||
"Close",
|
||||
&(),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
|
||||
/// Prepares to listen for the desktop closing the session (GNOME's "stop
|
||||
/// sharing" button, revocation). Call it before `start`: a signal emitted
|
||||
/// before the subscription would be lost.
|
||||
pub async fn watch_closed(&self) -> Result<SessionClosed, PortalError> {
|
||||
let rule = MatchRule::builder()
|
||||
.msg_type(zbus::message::Type::Signal)
|
||||
.interface(SESSION_INTERFACE)
|
||||
.member("Closed")
|
||||
.path(self.path.as_str())
|
||||
.build()
|
||||
.map_err(|e| PortalError::Response(e.to_string()))?;
|
||||
let stream = MessageStream::for_match_rule(rule, &self.connection, None)
|
||||
.await
|
||||
.map_err(|e| PortalError::Response(e.to_string()))?;
|
||||
Ok(SessionClosed { stream })
|
||||
}
|
||||
|
||||
pub fn path(&self) -> &str {
|
||||
self.path.as_str()
|
||||
}
|
||||
}
|
||||
|
||||
/// Waiting for the desktop to close a session.
|
||||
pub struct SessionClosed {
|
||||
stream: MessageStream,
|
||||
}
|
||||
|
||||
impl SessionClosed {
|
||||
/// Returns when the desktop has closed the session: the user stopped the
|
||||
/// share, or the compositor removed the display.
|
||||
pub async fn wait(mut self) {
|
||||
// The stream only ends with the connection: either way, the capture
|
||||
// is over.
|
||||
let _ = self.stream.next().await;
|
||||
}
|
||||
}
|
||||
|
||||
/// Extracts the identifier and size of the first stream in the answer.
|
||||
///
|
||||
/// The portal returns `a(ua{sv})`: a node identifier, then properties of which
|
||||
/// only the size matters to us for now.
|
||||
fn first_stream(value: Option<&OwnedVariant>) -> Result<(u32, Option<(u32, u32)>), PortalError> {
|
||||
let value = value.ok_or_else(|| PortalError::NoStream("streams missing".into()))?;
|
||||
let list = match &**value {
|
||||
Variant::Array(list) => list,
|
||||
other => {
|
||||
return Err(PortalError::NoStream(format!(
|
||||
"streams of unexpected type: {other:?}"
|
||||
)));
|
||||
}
|
||||
};
|
||||
let first = list
|
||||
.first()
|
||||
.ok_or_else(|| PortalError::NoStream("no stream in streams".into()))?;
|
||||
let structure = match first {
|
||||
Variant::Structure(structure) => structure,
|
||||
other => {
|
||||
return Err(PortalError::NoStream(format!(
|
||||
"stream of unexpected type: {other:?}"
|
||||
)));
|
||||
}
|
||||
};
|
||||
let fields = structure.fields();
|
||||
let node_id = fields
|
||||
.first()
|
||||
.and_then(|v| u32::try_from(v.clone()).ok())
|
||||
.ok_or_else(|| PortalError::NoStream("unreadable node identifier".into()))?;
|
||||
|
||||
// The size announced by the portal is for the logs; the authoritative one
|
||||
// is the format negotiated on the PipeWire side.
|
||||
let size = fields.get(1).and_then(|properties| match properties {
|
||||
Variant::Dict(dict) => {
|
||||
dict.get::<_, Variant>(&"size")
|
||||
.ok()
|
||||
.flatten()
|
||||
.and_then(|v| match v {
|
||||
Variant::Structure(s) => {
|
||||
let f = s.fields();
|
||||
let w = i32::try_from(f.first()?.clone()).ok()?;
|
||||
let h = i32::try_from(f.get(1)?.clone()).ok()?;
|
||||
Some((u32::try_from(w).ok()?, u32::try_from(h).ok()?))
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
}
|
||||
_ => None,
|
||||
});
|
||||
Ok((node_id, size))
|
||||
}
|
||||
|
||||
/// Calls a portal method and waits for its answer.
|
||||
///
|
||||
/// The signal subscription comes before the call: the signal may leave before
|
||||
/// we subscribe, and a lost answer turns into a two-minute hang.
|
||||
///
|
||||
/// The body is the argument list, not a variant: wrapped in a `Variant`, it
|
||||
/// goes out with signature `(v)` and the portal rejects it (`InvalidArgs`), an
|
||||
/// error that only a real session reveals.
|
||||
async fn call<B>(
|
||||
connection: &Connection,
|
||||
object: &str,
|
||||
interface: &str,
|
||||
method: &str,
|
||||
body: &B,
|
||||
token: &str,
|
||||
) -> Result<HashMap<String, OwnedVariant>, PortalError>
|
||||
where
|
||||
B: serde::Serialize + zbus::zvariant::DynamicType,
|
||||
{
|
||||
let response_path = request_path(connection, token)?;
|
||||
let rule = MatchRule::builder()
|
||||
.msg_type(zbus::message::Type::Signal)
|
||||
.interface(REQUEST_INTERFACE)
|
||||
.member("Response")
|
||||
.path(response_path.as_str())
|
||||
.build()
|
||||
.map_err(|e| PortalError::Response(e.to_string()))?;
|
||||
let mut stream =
|
||||
MessageStream::for_match_rule(rule, connection, std::num::NonZeroUsize::new(4))
|
||||
.await
|
||||
.map_err(|e| PortalError::Response(e.to_string()))?;
|
||||
|
||||
connection
|
||||
.call_method(Some(BUS), object, Some(interface), method, body)
|
||||
.await
|
||||
.map_err(|e| PortalError::Unreachable(e.to_string()))?;
|
||||
|
||||
let message = tokio::time::timeout(RESPONSE_TIMEOUT, stream.next())
|
||||
.await
|
||||
.map_err(|_| PortalError::Timeout)?
|
||||
.ok_or_else(|| PortalError::Response("response stream closed".into()))?
|
||||
.map_err(|e| PortalError::Response(e.to_string()))?;
|
||||
|
||||
let (code, results): (u32, HashMap<String, OwnedVariant>) = message
|
||||
.body()
|
||||
.deserialize()
|
||||
.map_err(|e| PortalError::Response(e.to_string()))?;
|
||||
|
||||
match code {
|
||||
0 => Ok(results),
|
||||
1 => Err(PortalError::Denied("request cancelled by the user".into())),
|
||||
// 2 = "other error". Seen for real: the desktop service
|
||||
// (xdg-desktop-portal-gnome) stops when idle, and its first answer
|
||||
// after a restart fails before ScreenCast is ready. Retrying a few
|
||||
// seconds later is enough.
|
||||
2 => Err(PortalError::Response(
|
||||
"the desktop portal failed (code 2): it may have been restarting, \
|
||||
retry in a few seconds"
|
||||
.into(),
|
||||
)),
|
||||
other => Err(PortalError::Response(format!(
|
||||
"the portal answered {other}"
|
||||
))),
|
||||
}
|
||||
}
|
||||
|
||||
/// The request object path follows a convention derived from the unique name
|
||||
/// on the bus: `:1.42` becomes `1_42`.
|
||||
fn request_path(connection: &Connection, token: &str) -> Result<String, PortalError> {
|
||||
let unique = connection
|
||||
.unique_name()
|
||||
.ok_or_else(|| PortalError::Bus("no unique name on the bus".into()))?
|
||||
.as_str()
|
||||
.to_string();
|
||||
if !token.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') {
|
||||
// The token ends up in a D-Bus path: a forbidden character must be
|
||||
// rejected here, not by an obscure bus message.
|
||||
return Err(PortalError::Response(format!("invalid token: {token}")));
|
||||
}
|
||||
let sender = unique.trim_start_matches(':').replace('.', "_");
|
||||
Ok(format!("{PORTAL_PATH}/request/{sender}/{token}"))
|
||||
}
|
||||
|
||||
/// Queries the portal.
|
||||
///
|
||||
/// Triggers no consent request: we only read the interface version, which
|
||||
/// needs no user authorisation.
|
||||
pub async fn probe() -> Result<PortalInfo, PortalError> {
|
||||
let connection = Connection::session()
|
||||
.await
|
||||
.map_err(|e| PortalError::Bus(e.to_string()))?;
|
||||
let version = property(&connection, "version").await?;
|
||||
// Missing from very old portals: it is then taken as "monitors only",
|
||||
// which is the only thing they could do.
|
||||
let types = property(&connection, "AvailableSourceTypes")
|
||||
.await
|
||||
.unwrap_or(TYPE_MONITOR);
|
||||
Ok(PortalInfo { version, types })
|
||||
}
|
||||
|
||||
/// Reads an integer property of the ScreenCast interface.
|
||||
async fn property(connection: &Connection, name: &str) -> Result<u32, PortalError> {
|
||||
let reply = connection
|
||||
.call_method(
|
||||
Some(BUS),
|
||||
PORTAL_PATH,
|
||||
Some(PROPERTIES_INTERFACE),
|
||||
"Get",
|
||||
&(SCREENCAST_INTERFACE, name),
|
||||
)
|
||||
.await
|
||||
.map_err(|e| match e {
|
||||
zbus::Error::MethodError(error_name, _, _)
|
||||
if error_name.as_str().contains("UnknownInterface")
|
||||
|| error_name.as_str().contains("UnknownObject")
|
||||
|| error_name.as_str().contains("UnknownService") =>
|
||||
{
|
||||
PortalError::Unreachable("the ScreenCast service is not exposed".into())
|
||||
}
|
||||
other => PortalError::Unreachable(other.to_string()),
|
||||
})?;
|
||||
|
||||
// The property arrives wrapped in a variant (`v`).
|
||||
reply
|
||||
.body()
|
||||
.deserialize::<Variant>()
|
||||
.map_err(|e| PortalError::Response(e.to_string()))?
|
||||
.downcast::<u32>()
|
||||
.map_err(|_| PortalError::Response(format!("{name} is not an integer")))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_virtual_display_is_read_from_the_source_types() {
|
||||
// GNOME 46 announces 7 (monitor, window, virtual) in version 5. The
|
||||
// version alone says nothing: a v5 portal without type 4 creates
|
||||
// nothing.
|
||||
let gnome = PortalInfo {
|
||||
version: 5,
|
||||
types: 7,
|
||||
};
|
||||
assert!(gnome.supports_virtual_display());
|
||||
assert!(gnome.supports_window());
|
||||
let old = PortalInfo {
|
||||
version: 5,
|
||||
types: TYPE_MONITOR | TYPE_WINDOW,
|
||||
};
|
||||
assert!(!old.supports_virtual_display());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tokens_are_unique_and_valid_in_a_path() {
|
||||
let a = token("x");
|
||||
let b = token("x");
|
||||
assert_ne!(a, b, "a reused token loses the portal's answer");
|
||||
for t in [a, b] {
|
||||
assert!(
|
||||
t.chars().all(|c| c.is_ascii_alphanumeric() || c == '_'),
|
||||
"{t}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// On a machine without a portal, the failure must be explained, not
|
||||
/// panic. The test accepts both outcomes: it checks the behaviour, not the
|
||||
/// environment of the test machine.
|
||||
#[tokio::test]
|
||||
async fn probing_never_panics_and_explains_failure() {
|
||||
match probe().await {
|
||||
Ok(info) => assert!(info.version > 0, "a zero version makes no sense"),
|
||||
Err(error) => {
|
||||
let message = error.to_string();
|
||||
assert!(!message.is_empty(), "the error must be readable");
|
||||
assert!(
|
||||
message.contains("portal") || message.contains("D-Bus"),
|
||||
"unexpected message: {message}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn opening_a_session_without_portal_fails_cleanly() {
|
||||
// Without a portal, opening must return a readable error, never hang:
|
||||
// this is the case of any machine without xdg-desktop-portal.
|
||||
match Session::open().await {
|
||||
Ok(session) => assert!(session.path().starts_with("/org/freedesktop/portal")),
|
||||
Err(error) => {
|
||||
let message = error.to_string();
|
||||
assert!(
|
||||
message.contains("portal") || message.contains("D-Bus"),
|
||||
"unexpected message: {message}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,529 @@
|
||||
//! The portal over D-Bus, on Linux.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::os::fd::OwnedFd;
|
||||
use std::sync::atomic::{AtomicU32, Ordering};
|
||||
|
||||
use futures_util::StreamExt;
|
||||
use zbus::{Connection, MatchRule, MessageStream};
|
||||
use zbus::{OwnedObjectPath, OwnedVariant, Variant};
|
||||
|
||||
use super::{
|
||||
PortalError, PortalInfo, RESPONSE_TIMEOUT, SourceType, TYPE_MONITOR, TYPE_VIRTUAL, TYPE_WINDOW,
|
||||
};
|
||||
|
||||
const BUS: &str = "org.freedesktop.portal.Desktop";
|
||||
const PORTAL_PATH: &str = "/org/freedesktop/portal/desktop";
|
||||
const PROPERTIES_INTERFACE: &str = "org.freedesktop.DBus.Properties";
|
||||
const SCREENCAST_INTERFACE: &str = "org.freedesktop.portal.ScreenCast";
|
||||
const REQUEST_INTERFACE: &str = "org.freedesktop.portal.Request";
|
||||
const SESSION_INTERFACE: &str = "org.freedesktop.portal.Session";
|
||||
|
||||
/// Token counter: one request object per call. A reused token makes the
|
||||
/// portal answer on an already consumed object, and the answer is lost.
|
||||
static COUNTER: AtomicU32 = AtomicU32::new(0);
|
||||
|
||||
/// Token unique within this process, valid in a D-Bus path.
|
||||
fn token(prefix: &str) -> String {
|
||||
let n = COUNTER.fetch_add(1, Ordering::Relaxed);
|
||||
format!("rustscreen_{}_{prefix}_{n}", std::process::id())
|
||||
}
|
||||
|
||||
impl SourceType {
|
||||
pub(super) fn mask(self) -> u32 {
|
||||
match self {
|
||||
Self::Monitor => TYPE_MONITOR,
|
||||
Self::Virtual => TYPE_VIRTUAL,
|
||||
Self::Window => TYPE_WINDOW,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A captured stream: the PipeWire descriptor and its node identifier.
|
||||
pub struct Stream {
|
||||
pub node_id: u32,
|
||||
pub fd: OwnedFd,
|
||||
/// Size announced by the portal, when it provides one.
|
||||
pub size: Option<(u32, u32)>,
|
||||
/// Token that avoids asking for the choice again at the next launch, when
|
||||
/// the portal returns one (persistent mode).
|
||||
pub restore_token: Option<String>,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for Stream {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("Stream")
|
||||
.field("node_id", &self.node_id)
|
||||
.field("size", &self.size)
|
||||
.field("fd", &self.fd)
|
||||
.field("restorable", &self.restore_token.is_some())
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
/// An open screencast session. Keeping it alive keeps the capture going;
|
||||
/// closing it frees the stream and stops the share on the portal side.
|
||||
pub struct Session {
|
||||
connection: Connection,
|
||||
path: OwnedObjectPath,
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// Opens a screencast session.
|
||||
///
|
||||
/// Shows nothing yet: the picker only appears at the `start` step, which
|
||||
/// leaves time to choose the options.
|
||||
pub async fn open() -> Result<Self, PortalError> {
|
||||
let connection = Connection::session()
|
||||
.await
|
||||
.map_err(|e| PortalError::Bus(e.to_string()))?;
|
||||
|
||||
let mut options: HashMap<String, Variant> = HashMap::new();
|
||||
let session_token = token("session");
|
||||
options.insert(
|
||||
"session_handle_token".into(),
|
||||
Variant::from(session_token.as_str()),
|
||||
);
|
||||
let token = token("create");
|
||||
options.insert("handle_token".into(), Variant::from(token.as_str()));
|
||||
|
||||
let results = call(
|
||||
&connection,
|
||||
PORTAL_PATH,
|
||||
SCREENCAST_INTERFACE,
|
||||
"CreateSession",
|
||||
&(options,),
|
||||
&token,
|
||||
)
|
||||
.await?;
|
||||
|
||||
let handle = results
|
||||
.get("session_handle")
|
||||
.ok_or_else(|| PortalError::Response("session_handle missing".into()))?;
|
||||
let path = match &**handle {
|
||||
Variant::Str(path) => {
|
||||
OwnedObjectPath::try_from(path.as_str()).map_err(|e| e.to_string())
|
||||
}
|
||||
// An ObjectPath can be owned without any possible failure.
|
||||
Variant::ObjectPath(path) => Ok::<_, String>(OwnedObjectPath::from(path.clone())),
|
||||
other => {
|
||||
return Err(PortalError::Response(format!(
|
||||
"session_handle of unexpected type: {other:?}"
|
||||
)));
|
||||
}
|
||||
}
|
||||
.map_err(PortalError::Response)?;
|
||||
|
||||
Ok(Self { connection, path })
|
||||
}
|
||||
|
||||
/// Asks to share a whole display, existing or virtual.
|
||||
///
|
||||
/// `multiple` stays false: a second display does not need to be multiple,
|
||||
/// and a simple picker is less intimidating.
|
||||
pub async fn select_monitor(&self, restore: Option<&str>) -> Result<(), PortalError> {
|
||||
self.select_source(SourceType::Monitor, restore).await
|
||||
}
|
||||
|
||||
/// Asks for a source of the given type. For a virtual display, the picker
|
||||
/// has nothing to offer: GNOME creates it directly, at the size the
|
||||
/// PipeWire consumer will set.
|
||||
pub async fn select_source(
|
||||
&self,
|
||||
source_type: SourceType,
|
||||
restore: Option<&str>,
|
||||
) -> Result<(), PortalError> {
|
||||
let mut options: HashMap<String, Variant> = HashMap::new();
|
||||
let token = token("sources");
|
||||
options.insert("handle_token".into(), Variant::from(token.as_str()));
|
||||
options.insert("types".into(), Variant::from(source_type.mask()));
|
||||
options.insert("multiple".into(), Variant::from(false));
|
||||
// Cursor embedded in the frame: without it, a viewer does not see
|
||||
// where the host clicks, which makes the share useless for explaining.
|
||||
options.insert("cursor_mode".into(), Variant::from(2u32));
|
||||
// A virtual display has nothing to restore: it is recreated every
|
||||
// time. For a monitor, 2 = persistent: the portal returns a token that
|
||||
// avoids confirming the choice again at each launch.
|
||||
if source_type == SourceType::Monitor {
|
||||
if let Some(restore_token) = restore {
|
||||
options.insert(
|
||||
"restore_token".into(),
|
||||
Variant::from(restore_token.to_string()),
|
||||
);
|
||||
}
|
||||
options.insert("persist_mode".into(), Variant::from(2u32));
|
||||
}
|
||||
|
||||
call(
|
||||
&self.connection,
|
||||
// The methods live on the portal object; the session is the first
|
||||
// argument, not the target of the call.
|
||||
PORTAL_PATH,
|
||||
SCREENCAST_INTERFACE,
|
||||
"SelectSources",
|
||||
&(&self.path, options),
|
||||
&token,
|
||||
)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Starts the capture. This is where the picker shows up.
|
||||
pub async fn start(&self) -> Result<Stream, PortalError> {
|
||||
let mut options: HashMap<String, Variant> = HashMap::new();
|
||||
let token = token("start");
|
||||
options.insert("handle_token".into(), Variant::from(token.as_str()));
|
||||
|
||||
// Start takes three arguments: session, parent window (empty: no modal
|
||||
// dialog attached to a window), options.
|
||||
let results = call(
|
||||
&self.connection,
|
||||
// The methods live on the portal object; the session is the first
|
||||
// argument, not the target of the call.
|
||||
PORTAL_PATH,
|
||||
SCREENCAST_INTERFACE,
|
||||
"Start",
|
||||
&(&self.path, "", options),
|
||||
&token,
|
||||
)
|
||||
.await?;
|
||||
|
||||
let (node_id, size) = first_stream(results.get("streams"))?;
|
||||
let restore_token = results
|
||||
.get("restore_token")
|
||||
.and_then(|v| String::try_from(v.clone()).ok());
|
||||
|
||||
// The descriptor is not in the answer to `Start`: it is requested
|
||||
// separately, through `OpenPipeWireRemote`, once the capture is granted.
|
||||
let options: HashMap<String, Variant> = HashMap::new();
|
||||
let reply = self
|
||||
.connection
|
||||
.call_method(
|
||||
Some(BUS),
|
||||
PORTAL_PATH,
|
||||
Some(SCREENCAST_INTERFACE),
|
||||
"OpenPipeWireRemote",
|
||||
&(&self.path, options),
|
||||
)
|
||||
.await
|
||||
.map_err(|e| PortalError::NoStream(format!("OpenPipeWireRemote: {e}")))?;
|
||||
// Deserialization duplicates the descriptor (`dup`): the copy belongs
|
||||
// to us and outlives the D-Bus message that carried the original.
|
||||
let fd: OwnedFd = reply
|
||||
.body()
|
||||
.deserialize::<zbus::OwnedFd>()
|
||||
.map_err(|e| PortalError::NoStream(format!("unreadable descriptor: {e}")))?
|
||||
.into();
|
||||
Ok(Stream {
|
||||
node_id,
|
||||
fd,
|
||||
size,
|
||||
restore_token,
|
||||
})
|
||||
}
|
||||
|
||||
/// Closes the session on the portal side. The session object carries
|
||||
/// `Close`, not the request object: calling the latter closes nothing.
|
||||
pub async fn close(&self) {
|
||||
let _ = self
|
||||
.connection
|
||||
.call_method(
|
||||
Some(BUS),
|
||||
self.path.as_str(),
|
||||
Some(SESSION_INTERFACE),
|
||||
"Close",
|
||||
&(),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
|
||||
/// Prepares to listen for the desktop closing the session (GNOME's "stop
|
||||
/// sharing" button, revocation). Call it before `start`: a signal emitted
|
||||
/// before the subscription would be lost.
|
||||
pub async fn watch_closed(&self) -> Result<SessionClosed, PortalError> {
|
||||
let rule = MatchRule::builder()
|
||||
.msg_type(zbus::message::Type::Signal)
|
||||
.interface(SESSION_INTERFACE)
|
||||
.member("Closed")
|
||||
.path(self.path.as_str())
|
||||
.build()
|
||||
.map_err(|e| PortalError::Response(e.to_string()))?;
|
||||
let stream = MessageStream::for_match_rule(rule, &self.connection, None)
|
||||
.await
|
||||
.map_err(|e| PortalError::Response(e.to_string()))?;
|
||||
Ok(SessionClosed { stream })
|
||||
}
|
||||
|
||||
pub fn path(&self) -> &str {
|
||||
self.path.as_str()
|
||||
}
|
||||
}
|
||||
|
||||
/// Waiting for the desktop to close a session.
|
||||
pub struct SessionClosed {
|
||||
stream: MessageStream,
|
||||
}
|
||||
|
||||
impl SessionClosed {
|
||||
/// Returns when the desktop has closed the session: the user stopped the
|
||||
/// share, or the compositor removed the display.
|
||||
pub async fn wait(mut self) {
|
||||
// The stream only ends with the connection: either way, the capture
|
||||
// is over.
|
||||
let _ = self.stream.next().await;
|
||||
}
|
||||
}
|
||||
|
||||
/// Extracts the identifier and size of the first stream in the answer.
|
||||
///
|
||||
/// The portal returns `a(ua{sv})`: a node identifier, then properties of which
|
||||
/// only the size matters to us for now.
|
||||
fn first_stream(value: Option<&OwnedVariant>) -> Result<(u32, Option<(u32, u32)>), PortalError> {
|
||||
let value = value.ok_or_else(|| PortalError::NoStream("streams missing".into()))?;
|
||||
let list = match &**value {
|
||||
Variant::Array(list) => list,
|
||||
other => {
|
||||
return Err(PortalError::NoStream(format!(
|
||||
"streams of unexpected type: {other:?}"
|
||||
)));
|
||||
}
|
||||
};
|
||||
let first = list
|
||||
.first()
|
||||
.ok_or_else(|| PortalError::NoStream("no stream in streams".into()))?;
|
||||
let structure = match first {
|
||||
Variant::Structure(structure) => structure,
|
||||
other => {
|
||||
return Err(PortalError::NoStream(format!(
|
||||
"stream of unexpected type: {other:?}"
|
||||
)));
|
||||
}
|
||||
};
|
||||
let fields = structure.fields();
|
||||
let node_id = fields
|
||||
.first()
|
||||
.and_then(|v| u32::try_from(v.clone()).ok())
|
||||
.ok_or_else(|| PortalError::NoStream("unreadable node identifier".into()))?;
|
||||
|
||||
// The size announced by the portal is for the logs; the authoritative one
|
||||
// is the format negotiated on the PipeWire side.
|
||||
let size = fields.get(1).and_then(|properties| match properties {
|
||||
Variant::Dict(dict) => {
|
||||
dict.get::<_, Variant>(&"size")
|
||||
.ok()
|
||||
.flatten()
|
||||
.and_then(|v| match v {
|
||||
Variant::Structure(s) => {
|
||||
let f = s.fields();
|
||||
let w = i32::try_from(f.first()?.clone()).ok()?;
|
||||
let h = i32::try_from(f.get(1)?.clone()).ok()?;
|
||||
Some((u32::try_from(w).ok()?, u32::try_from(h).ok()?))
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
}
|
||||
_ => None,
|
||||
});
|
||||
Ok((node_id, size))
|
||||
}
|
||||
|
||||
/// Calls a portal method and waits for its answer.
|
||||
///
|
||||
/// The signal subscription comes before the call: the signal may leave before
|
||||
/// we subscribe, and a lost answer turns into a two-minute hang.
|
||||
///
|
||||
/// The body is the argument list, not a variant: wrapped in a `Variant`, it
|
||||
/// goes out with signature `(v)` and the portal rejects it (`InvalidArgs`), an
|
||||
/// error that only a real session reveals.
|
||||
async fn call<B>(
|
||||
connection: &Connection,
|
||||
object: &str,
|
||||
interface: &str,
|
||||
method: &str,
|
||||
body: &B,
|
||||
token: &str,
|
||||
) -> Result<HashMap<String, OwnedVariant>, PortalError>
|
||||
where
|
||||
B: serde::Serialize + zbus::zvariant::DynamicType,
|
||||
{
|
||||
let response_path = request_path(connection, token)?;
|
||||
let rule = MatchRule::builder()
|
||||
.msg_type(zbus::message::Type::Signal)
|
||||
.interface(REQUEST_INTERFACE)
|
||||
.member("Response")
|
||||
.path(response_path.as_str())
|
||||
.build()
|
||||
.map_err(|e| PortalError::Response(e.to_string()))?;
|
||||
let mut stream =
|
||||
MessageStream::for_match_rule(rule, connection, std::num::NonZeroUsize::new(4))
|
||||
.await
|
||||
.map_err(|e| PortalError::Response(e.to_string()))?;
|
||||
|
||||
connection
|
||||
.call_method(Some(BUS), object, Some(interface), method, body)
|
||||
.await
|
||||
.map_err(|e| PortalError::Unreachable(e.to_string()))?;
|
||||
|
||||
let message = tokio::time::timeout(RESPONSE_TIMEOUT, stream.next())
|
||||
.await
|
||||
.map_err(|_| PortalError::Timeout)?
|
||||
.ok_or_else(|| PortalError::Response("response stream closed".into()))?
|
||||
.map_err(|e| PortalError::Response(e.to_string()))?;
|
||||
|
||||
let (code, results): (u32, HashMap<String, OwnedVariant>) = message
|
||||
.body()
|
||||
.deserialize()
|
||||
.map_err(|e| PortalError::Response(e.to_string()))?;
|
||||
|
||||
match code {
|
||||
0 => Ok(results),
|
||||
1 => Err(PortalError::Denied("request cancelled by the user".into())),
|
||||
// 2 = "other error". Seen for real: the desktop service
|
||||
// (xdg-desktop-portal-gnome) stops when idle, and its first answer
|
||||
// after a restart fails before ScreenCast is ready. Retrying a few
|
||||
// seconds later is enough.
|
||||
2 => Err(PortalError::Response(
|
||||
"the desktop portal failed (code 2): it may have been restarting, \
|
||||
retry in a few seconds"
|
||||
.into(),
|
||||
)),
|
||||
other => Err(PortalError::Response(format!(
|
||||
"the portal answered {other}"
|
||||
))),
|
||||
}
|
||||
}
|
||||
|
||||
/// The request object path follows a convention derived from the unique name
|
||||
/// on the bus: `:1.42` becomes `1_42`.
|
||||
fn request_path(connection: &Connection, token: &str) -> Result<String, PortalError> {
|
||||
let unique = connection
|
||||
.unique_name()
|
||||
.ok_or_else(|| PortalError::Bus("no unique name on the bus".into()))?
|
||||
.as_str()
|
||||
.to_string();
|
||||
if !token.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') {
|
||||
// The token ends up in a D-Bus path: a forbidden character must be
|
||||
// rejected here, not by an obscure bus message.
|
||||
return Err(PortalError::Response(format!("invalid token: {token}")));
|
||||
}
|
||||
let sender = unique.trim_start_matches(':').replace('.', "_");
|
||||
Ok(format!("{PORTAL_PATH}/request/{sender}/{token}"))
|
||||
}
|
||||
|
||||
/// Queries the portal.
|
||||
///
|
||||
/// Triggers no consent request: we only read the interface version, which
|
||||
/// needs no user authorisation.
|
||||
pub async fn probe() -> Result<PortalInfo, PortalError> {
|
||||
let connection = Connection::session()
|
||||
.await
|
||||
.map_err(|e| PortalError::Bus(e.to_string()))?;
|
||||
let version = property(&connection, "version").await?;
|
||||
// Missing from very old portals: it is then taken as "monitors only",
|
||||
// which is the only thing they could do.
|
||||
let types = property(&connection, "AvailableSourceTypes")
|
||||
.await
|
||||
.unwrap_or(TYPE_MONITOR);
|
||||
Ok(PortalInfo { version, types })
|
||||
}
|
||||
|
||||
/// Reads an integer property of the ScreenCast interface.
|
||||
async fn property(connection: &Connection, name: &str) -> Result<u32, PortalError> {
|
||||
let reply = connection
|
||||
.call_method(
|
||||
Some(BUS),
|
||||
PORTAL_PATH,
|
||||
Some(PROPERTIES_INTERFACE),
|
||||
"Get",
|
||||
&(SCREENCAST_INTERFACE, name),
|
||||
)
|
||||
.await
|
||||
.map_err(|e| match e {
|
||||
zbus::Error::MethodError(error_name, _, _)
|
||||
if error_name.as_str().contains("UnknownInterface")
|
||||
|| error_name.as_str().contains("UnknownObject")
|
||||
|| error_name.as_str().contains("UnknownService") =>
|
||||
{
|
||||
PortalError::Unreachable("the ScreenCast service is not exposed".into())
|
||||
}
|
||||
other => PortalError::Unreachable(other.to_string()),
|
||||
})?;
|
||||
|
||||
// The property arrives wrapped in a variant (`v`).
|
||||
reply
|
||||
.body()
|
||||
.deserialize::<Variant>()
|
||||
.map_err(|e| PortalError::Response(e.to_string()))?
|
||||
.downcast::<u32>()
|
||||
.map_err(|_| PortalError::Response(format!("{name} is not an integer")))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_virtual_display_is_read_from_the_source_types() {
|
||||
// GNOME 46 announces 7 (monitor, window, virtual) in version 5. The
|
||||
// version alone says nothing: a v5 portal without type 4 creates
|
||||
// nothing.
|
||||
let gnome = PortalInfo {
|
||||
version: 5,
|
||||
types: 7,
|
||||
};
|
||||
assert!(gnome.supports_virtual_display());
|
||||
assert!(gnome.supports_window());
|
||||
let old = PortalInfo {
|
||||
version: 5,
|
||||
types: TYPE_MONITOR | TYPE_WINDOW,
|
||||
};
|
||||
assert!(!old.supports_virtual_display());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tokens_are_unique_and_valid_in_a_path() {
|
||||
let a = token("x");
|
||||
let b = token("x");
|
||||
assert_ne!(a, b, "a reused token loses the portal's answer");
|
||||
for t in [a, b] {
|
||||
assert!(
|
||||
t.chars().all(|c| c.is_ascii_alphanumeric() || c == '_'),
|
||||
"{t}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// On a machine without a portal, the failure must be explained, not
|
||||
/// panic. The test accepts both outcomes: it checks the behaviour, not the
|
||||
/// environment of the test machine.
|
||||
#[tokio::test]
|
||||
async fn probing_never_panics_and_explains_failure() {
|
||||
match probe().await {
|
||||
Ok(info) => assert!(info.version > 0, "a zero version makes no sense"),
|
||||
Err(error) => {
|
||||
let message = error.to_string();
|
||||
assert!(!message.is_empty(), "the error must be readable");
|
||||
assert!(
|
||||
message.contains("portal") || message.contains("D-Bus"),
|
||||
"unexpected message: {message}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn opening_a_session_without_portal_fails_cleanly() {
|
||||
// Without a portal, opening must return a readable error, never hang:
|
||||
// this is the case of any machine without xdg-desktop-portal.
|
||||
match Session::open().await {
|
||||
Ok(session) => assert!(session.path().starts_with("/org/freedesktop/portal")),
|
||||
Err(error) => {
|
||||
let message = error.to_string();
|
||||
assert!(
|
||||
message.contains("portal") || message.contains("D-Bus"),
|
||||
"unexpected message: {message}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
//! No portal outside Linux: the same API, which always says so.
|
||||
|
||||
use super::{PortalError, PortalInfo, SourceType};
|
||||
|
||||
/// A captured stream. Never produced here.
|
||||
#[derive(Debug)]
|
||||
pub struct Stream {
|
||||
pub node_id: u32,
|
||||
pub size: Option<(u32, u32)>,
|
||||
pub restore_token: Option<String>,
|
||||
}
|
||||
|
||||
/// A screencast session. Never opened here.
|
||||
#[derive(Debug)]
|
||||
pub struct Session {
|
||||
_never: (),
|
||||
}
|
||||
|
||||
impl Session {
|
||||
pub async fn open() -> Result<Self, PortalError> {
|
||||
Err(PortalError::Unsupported)
|
||||
}
|
||||
|
||||
pub async fn select_monitor(&self, _restore: Option<&str>) -> Result<(), PortalError> {
|
||||
Err(PortalError::Unsupported)
|
||||
}
|
||||
|
||||
pub async fn select_source(
|
||||
&self,
|
||||
_source: SourceType,
|
||||
_restore: Option<&str>,
|
||||
) -> Result<(), PortalError> {
|
||||
Err(PortalError::Unsupported)
|
||||
}
|
||||
|
||||
pub async fn start(&self) -> Result<Stream, PortalError> {
|
||||
Err(PortalError::Unsupported)
|
||||
}
|
||||
|
||||
pub async fn close(&self) {}
|
||||
|
||||
pub async fn watch_closed(&self) -> Result<SessionClosed, PortalError> {
|
||||
Err(PortalError::Unsupported)
|
||||
}
|
||||
|
||||
pub fn path(&self) -> &str {
|
||||
""
|
||||
}
|
||||
}
|
||||
|
||||
/// Waiting for the desktop to close a session. Never created here.
|
||||
#[derive(Debug)]
|
||||
pub struct SessionClosed {
|
||||
_never: (),
|
||||
}
|
||||
|
||||
impl SessionClosed {
|
||||
pub async fn wait(self) {}
|
||||
}
|
||||
|
||||
pub async fn probe() -> Result<PortalInfo, PortalError> {
|
||||
Err(PortalError::Unsupported)
|
||||
}
|
||||
+18
-344
@@ -21,32 +21,26 @@
|
||||
//! ScreenSaver daemon under a bare window manager): the inhibition succeeds as
|
||||
//! soon as one of them holds, and [`Inhibition::active`] says which, so the UI
|
||||
//! does not display a promise it does not keep.
|
||||
//!
|
||||
//! On Windows, a power request (`PowerCreateRequest`, system and display
|
||||
//! required) holds both at once, as long as its handle stays open; the
|
||||
//! suspend and resume notification (`PowerRegisterSuspendResumeNotification`)
|
||||
//! plays the part of `PrepareForSleep` (#94).
|
||||
|
||||
use std::fmt;
|
||||
#[cfg(target_os = "linux")]
|
||||
mod linux;
|
||||
#[cfg(target_os = "linux")]
|
||||
pub use linux::{Inhibition, MECHANISM_LOGIN1, MECHANISM_SCREENSAVER, WakeWatcher, watch_wake};
|
||||
|
||||
use futures_util::StreamExt;
|
||||
use zbus::{Connection, MatchRule, MessageStream};
|
||||
#[cfg(windows)]
|
||||
mod windows;
|
||||
#[cfg(windows)]
|
||||
pub use windows::{Inhibition, MECHANISM_POWER_REQUEST, WakeWatcher, watch_wake};
|
||||
|
||||
const LOGIN1_BUS: &str = "org.freedesktop.login1";
|
||||
const LOGIN1_PATH: &str = "/org/freedesktop/login1";
|
||||
const LOGIN1_INTERFACE: &str = "org.freedesktop.login1.Manager";
|
||||
|
||||
const SCREENSAVER_BUS: &str = "org.freedesktop.ScreenSaver";
|
||||
const SCREENSAVER_PATH: &str = "/org/freedesktop/ScreenSaver";
|
||||
const SCREENSAVER_INTERFACE: &str = "org.freedesktop.ScreenSaver";
|
||||
|
||||
/// Name shown by `systemd-inhibit --list` and by the desktop.
|
||||
/// Name shown by `systemd-inhibit --list`, by the desktop and by
|
||||
/// `powercfg /requests`.
|
||||
const APPLICATION: &str = "rustscreen";
|
||||
|
||||
/// What the `login1` lock blocks: suspend and idle sleep, not the lid nor the
|
||||
/// power keys.
|
||||
const LOGIN1_WHAT: &str = "sleep:idle";
|
||||
|
||||
/// Name of the `login1` mechanism in [`Inhibition::active`] and the logs.
|
||||
pub const MECHANISM_LOGIN1: &str = "login1";
|
||||
/// Name of the ScreenSaver mechanism in [`Inhibition::active`] and the logs.
|
||||
pub const MECHANISM_SCREENSAVER: &str = "screensaver";
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum SleepError {
|
||||
/// Neither lock could be taken.
|
||||
@@ -56,182 +50,9 @@ pub enum SleepError {
|
||||
Bus(String),
|
||||
#[error("cannot subscribe to PrepareForSleep: {0}")]
|
||||
Subscription(String),
|
||||
}
|
||||
|
||||
/// List of the mechanisms held, in a stable order.
|
||||
fn active_names(login1: bool, screensaver: bool) -> Vec<&'static str> {
|
||||
let mut names = Vec::with_capacity(2);
|
||||
if login1 {
|
||||
names.push(MECHANISM_LOGIN1);
|
||||
}
|
||||
if screensaver {
|
||||
names.push(MECHANISM_SCREENSAVER);
|
||||
}
|
||||
names
|
||||
}
|
||||
|
||||
/// Locks against sleep, held as long as the value lives.
|
||||
///
|
||||
/// [`Inhibition::release`] frees everything immediately. Failing that, `Drop`
|
||||
/// closes the `login1` descriptor (synchronous close, no D-Bus call) and drops
|
||||
/// the session connection: the ScreenSaver daemon then forgets the cookie on
|
||||
/// its own, without an explicit `UnInhibit`, which may take the time the
|
||||
/// connection needs to close.
|
||||
pub struct Inhibition {
|
||||
/// Descriptor returned by `login1`: the lock lasts as long as it is open.
|
||||
login1_lock: Option<zbus::OwnedFd>,
|
||||
/// Session connection and ScreenSaver cookie. The connection is kept alive
|
||||
/// on purpose: closing it releases the cookie.
|
||||
screensaver: Option<(Connection, u32)>,
|
||||
}
|
||||
|
||||
impl fmt::Debug for Inhibition {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.debug_struct("Inhibition")
|
||||
.field("active", &self.active())
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
impl Inhibition {
|
||||
/// Prevents sleep and screen blanking.
|
||||
///
|
||||
/// `reason` is shown by the desktop and `systemd-inhibit --list`: a fixed
|
||||
/// text from the caller, never a window title. It is not logged.
|
||||
///
|
||||
/// Fails only if neither lock could be taken.
|
||||
pub async fn acquire(reason: &str) -> Result<Self, SleepError> {
|
||||
let login1 = inhibit_login1(reason).await;
|
||||
let screensaver = inhibit_screensaver(reason).await;
|
||||
|
||||
let (login1_lock, screensaver) = match (login1, screensaver) {
|
||||
(Err(login1), Err(screensaver)) => {
|
||||
tracing::warn!(
|
||||
event = "sleep_not_inhibited",
|
||||
login1 = %login1,
|
||||
screensaver = %screensaver,
|
||||
"no lock against sleep"
|
||||
);
|
||||
return Err(SleepError::Inhibition {
|
||||
login1,
|
||||
screensaver,
|
||||
});
|
||||
}
|
||||
(login1, screensaver) => {
|
||||
if let Err(error) = &login1 {
|
||||
tracing::warn!(%error, "login1 lock unavailable");
|
||||
}
|
||||
if let Err(error) = &screensaver {
|
||||
tracing::warn!(%error, "ScreenSaver lock unavailable");
|
||||
}
|
||||
(login1.ok(), screensaver.ok())
|
||||
}
|
||||
};
|
||||
|
||||
let inhibition = Self {
|
||||
login1_lock,
|
||||
screensaver,
|
||||
};
|
||||
tracing::info!(
|
||||
event = "sleep_inhibited",
|
||||
mechanisms = ?inhibition.active(),
|
||||
"sleep prevented during the share"
|
||||
);
|
||||
Ok(inhibition)
|
||||
}
|
||||
|
||||
/// Mechanisms actually held: [`MECHANISM_LOGIN1`],
|
||||
/// [`MECHANISM_SCREENSAVER`], or both.
|
||||
pub fn active(&self) -> Vec<&'static str> {
|
||||
active_names(self.login1_lock.is_some(), self.screensaver.is_some())
|
||||
}
|
||||
|
||||
/// Frees the locks right away: `UnInhibit`, then closing the `login1`
|
||||
/// descriptor.
|
||||
pub async fn release(mut self) {
|
||||
let active = self.active();
|
||||
if let Some((connection, cookie)) = self.screensaver.take() {
|
||||
// A failure here prevents nothing: the connection closes right
|
||||
// after, and the daemon forgets the cookie with it.
|
||||
if let Err(error) = connection
|
||||
.call_method(
|
||||
Some(SCREENSAVER_BUS),
|
||||
SCREENSAVER_PATH,
|
||||
Some(SCREENSAVER_INTERFACE),
|
||||
"UnInhibit",
|
||||
&(cookie,),
|
||||
)
|
||||
.await
|
||||
{
|
||||
tracing::debug!(%error, "UnInhibit refused, closing will be enough");
|
||||
}
|
||||
}
|
||||
// Closing the descriptor is enough to hand the lock back to logind.
|
||||
drop(self.login1_lock.take());
|
||||
tracing::info!(
|
||||
event = "sleep_released",
|
||||
mechanisms = ?active,
|
||||
"sleep allowed again"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Inhibition {
|
||||
fn drop(&mut self) {
|
||||
// Nothing to do if `release` already ran.
|
||||
let active = self.active();
|
||||
if active.is_empty() {
|
||||
return;
|
||||
}
|
||||
// The descriptor closes with the field, the connection too: no D-Bus
|
||||
// call is possible in a synchronous `Drop`, and none is needed.
|
||||
tracing::info!(
|
||||
event = "sleep_released",
|
||||
mechanisms = ?active,
|
||||
"sleep allowed again"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Takes the `login1` lock and returns its descriptor.
|
||||
async fn inhibit_login1(reason: &str) -> Result<zbus::OwnedFd, String> {
|
||||
let connection = Connection::system().await.map_err(|e| e.to_string())?;
|
||||
let reply = connection
|
||||
.call_method(
|
||||
Some(LOGIN1_BUS),
|
||||
LOGIN1_PATH,
|
||||
Some(LOGIN1_INTERFACE),
|
||||
"Inhibit",
|
||||
&(LOGIN1_WHAT, APPLICATION, reason, "block"),
|
||||
)
|
||||
.await
|
||||
.map_err(|e| e.to_string())?;
|
||||
// Deserialization duplicates the descriptor: the copy belongs to us and
|
||||
// keeps the lock once the message and the connection are gone.
|
||||
reply
|
||||
.body()
|
||||
.deserialize::<zbus::OwnedFd>()
|
||||
.map_err(|e| format!("unreadable descriptor: {e}"))
|
||||
}
|
||||
|
||||
/// Takes the ScreenSaver lock and returns the connection that carries it.
|
||||
async fn inhibit_screensaver(reason: &str) -> Result<(Connection, u32), String> {
|
||||
let connection = Connection::session().await.map_err(|e| e.to_string())?;
|
||||
let reply = connection
|
||||
.call_method(
|
||||
Some(SCREENSAVER_BUS),
|
||||
SCREENSAVER_PATH,
|
||||
Some(SCREENSAVER_INTERFACE),
|
||||
"Inhibit",
|
||||
&(APPLICATION, reason),
|
||||
)
|
||||
.await
|
||||
.map_err(|e| e.to_string())?;
|
||||
let cookie = reply
|
||||
.body()
|
||||
.deserialize::<u32>()
|
||||
.map_err(|e| format!("unreadable cookie: {e}"))?;
|
||||
Ok((connection, cookie))
|
||||
/// Windows: the power request or the resume notification was refused.
|
||||
#[error("power management refused: {0}")]
|
||||
Power(String),
|
||||
}
|
||||
|
||||
/// Transition announced by `PrepareForSleep`.
|
||||
@@ -243,150 +64,3 @@ pub enum SleepEvent {
|
||||
/// connections are probably dead, and so is the capture.
|
||||
WokeUp,
|
||||
}
|
||||
|
||||
impl SleepEvent {
|
||||
fn from_signal(going_to_sleep: bool) -> Self {
|
||||
if going_to_sleep {
|
||||
Self::GoingToSleep
|
||||
} else {
|
||||
Self::WokeUp
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Listens for the sleeps and wake-ups announced by `login1`.
|
||||
pub struct WakeWatcher {
|
||||
stream: MessageStream,
|
||||
}
|
||||
|
||||
impl fmt::Debug for WakeWatcher {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.debug_struct("WakeWatcher").finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
/// Subscribes to `PrepareForSleep` on the system bus.
|
||||
///
|
||||
/// Call it before it is needed: a signal emitted before the subscription is
|
||||
/// lost, and a missed wake-up leaves the share frozen.
|
||||
pub async fn watch_wake() -> Result<WakeWatcher, SleepError> {
|
||||
let connection = Connection::system()
|
||||
.await
|
||||
.map_err(|e| SleepError::Bus(e.to_string()))?;
|
||||
let rule = MatchRule::builder()
|
||||
.msg_type(zbus::message::Type::Signal)
|
||||
// No sender filter: the signal arrives under logind's unique name, not
|
||||
// under `org.freedesktop.login1`. Only root can emit on this path of
|
||||
// the system bus.
|
||||
.interface(LOGIN1_INTERFACE)
|
||||
.member("PrepareForSleep")
|
||||
.path(LOGIN1_PATH)
|
||||
.build()
|
||||
.map_err(|e| SleepError::Subscription(e.to_string()))?;
|
||||
let stream = MessageStream::for_match_rule(rule, &connection, None)
|
||||
.await
|
||||
.map_err(|e| SleepError::Subscription(e.to_string()))?;
|
||||
Ok(WakeWatcher { stream })
|
||||
}
|
||||
|
||||
impl WakeWatcher {
|
||||
/// Waits for the next transition. `None` when the connection to the
|
||||
/// system bus is lost: no wake-up will be announced anymore.
|
||||
pub async fn next_event(&mut self) -> Option<SleepEvent> {
|
||||
loop {
|
||||
let message = match self.stream.next().await? {
|
||||
Ok(message) => message,
|
||||
Err(error) => {
|
||||
tracing::debug!(%error, "unreadable message on the system bus");
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let Ok(going_to_sleep) = message.body().deserialize::<bool>() else {
|
||||
continue;
|
||||
};
|
||||
let event = SleepEvent::from_signal(going_to_sleep);
|
||||
match event {
|
||||
SleepEvent::GoingToSleep => {
|
||||
tracing::info!(event = "going_to_sleep", "the machine is going to sleep");
|
||||
}
|
||||
SleepEvent::WokeUp => {
|
||||
tracing::info!(event = "woke_up", "the machine is waking up");
|
||||
}
|
||||
}
|
||||
return Some(event);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn active_mechanisms_are_named_in_a_stable_order() {
|
||||
assert_eq!(active_names(true, true), ["login1", "screensaver"]);
|
||||
assert_eq!(active_names(false, true), ["screensaver"]);
|
||||
assert_eq!(active_names(true, false), ["login1"]);
|
||||
assert!(active_names(false, false).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prepare_for_sleep_maps_true_to_sleep_and_false_to_wake() {
|
||||
assert_eq!(SleepEvent::from_signal(true), SleepEvent::GoingToSleep);
|
||||
assert_eq!(SleepEvent::from_signal(false), SleepEvent::WokeUp);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_lid_switch_is_never_inhibited() {
|
||||
// Closing the lid is an explicit gesture: blocking it would surprise.
|
||||
assert!(!LOGIN1_WHAT.contains("handle-lid-switch"));
|
||||
assert_eq!(LOGIN1_WHAT, "sleep:idle");
|
||||
}
|
||||
|
||||
/// Lines of `systemd-inhibit --list` that come from this process.
|
||||
fn locks_of_this_process() -> Vec<String> {
|
||||
let output = std::process::Command::new("systemd-inhibit")
|
||||
.args(["--list", "--no-pager", "--no-legend"])
|
||||
.output()
|
||||
.expect("systemd-inhibit not found");
|
||||
let pid = std::process::id().to_string();
|
||||
String::from_utf8_lossy(&output.stdout)
|
||||
.lines()
|
||||
.filter(|l| {
|
||||
let fields: Vec<&str> = l.split_whitespace().collect();
|
||||
fields.first() == Some(&APPLICATION) && fields.contains(&pid.as_str())
|
||||
})
|
||||
.map(str::to_string)
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Takes a real lock on this machine: needs logind and a desktop that
|
||||
/// exposes ScreenSaver. `cargo test -p rs-platform sleep -- --ignored`.
|
||||
#[tokio::test]
|
||||
#[ignore = "needs logind and a desktop session"]
|
||||
async fn a_real_inhibition_shows_in_systemd_inhibit_then_goes_away() {
|
||||
let inhibition = Inhibition::acquire("screen sharing in progress (test)")
|
||||
.await
|
||||
.expect("no lock taken");
|
||||
let active = inhibition.active();
|
||||
assert!(active.contains(&MECHANISM_LOGIN1), "{active:?}");
|
||||
eprintln!("mechanisms held: {active:?}");
|
||||
|
||||
let lines = locks_of_this_process();
|
||||
assert_eq!(lines.len(), 1, "{lines:?}");
|
||||
assert!(lines[0].contains("sleep:idle"), "{}", lines[0]);
|
||||
assert!(lines[0].contains("block"), "{}", lines[0]);
|
||||
|
||||
inhibition.release().await;
|
||||
let lines = locks_of_this_process();
|
||||
assert!(lines.is_empty(), "lock still held: {lines:?}");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn subscribing_to_resume_never_panics() {
|
||||
// Without a system bus, the error must be readable, never a panic.
|
||||
if let Err(error) = watch_wake().await {
|
||||
assert!(!error.to_string().is_empty());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,348 @@
|
||||
//! Sleep on Linux: `login1` and ScreenSaver over D-Bus.
|
||||
|
||||
use std::fmt;
|
||||
|
||||
use futures_util::StreamExt;
|
||||
use zbus::{Connection, MatchRule, MessageStream};
|
||||
|
||||
use super::{APPLICATION, SleepError, SleepEvent};
|
||||
|
||||
const LOGIN1_BUS: &str = "org.freedesktop.login1";
|
||||
const LOGIN1_PATH: &str = "/org/freedesktop/login1";
|
||||
const LOGIN1_INTERFACE: &str = "org.freedesktop.login1.Manager";
|
||||
|
||||
const SCREENSAVER_BUS: &str = "org.freedesktop.ScreenSaver";
|
||||
const SCREENSAVER_PATH: &str = "/org/freedesktop/ScreenSaver";
|
||||
const SCREENSAVER_INTERFACE: &str = "org.freedesktop.ScreenSaver";
|
||||
|
||||
/// What the `login1` lock blocks: suspend and idle sleep, not the lid nor the
|
||||
/// power keys.
|
||||
const LOGIN1_WHAT: &str = "sleep:idle";
|
||||
|
||||
/// Name of the `login1` mechanism in [`Inhibition::active`] and the logs.
|
||||
pub const MECHANISM_LOGIN1: &str = "login1";
|
||||
/// Name of the ScreenSaver mechanism in [`Inhibition::active`] and the logs.
|
||||
pub const MECHANISM_SCREENSAVER: &str = "screensaver";
|
||||
|
||||
/// List of the mechanisms held, in a stable order.
|
||||
fn active_names(login1: bool, screensaver: bool) -> Vec<&'static str> {
|
||||
let mut names = Vec::with_capacity(2);
|
||||
if login1 {
|
||||
names.push(MECHANISM_LOGIN1);
|
||||
}
|
||||
if screensaver {
|
||||
names.push(MECHANISM_SCREENSAVER);
|
||||
}
|
||||
names
|
||||
}
|
||||
|
||||
/// Locks against sleep, held as long as the value lives.
|
||||
///
|
||||
/// [`Inhibition::release`] frees everything immediately. Failing that, `Drop`
|
||||
/// closes the `login1` descriptor (synchronous close, no D-Bus call) and drops
|
||||
/// the session connection: the ScreenSaver daemon then forgets the cookie on
|
||||
/// its own, without an explicit `UnInhibit`, which may take the time the
|
||||
/// connection needs to close.
|
||||
pub struct Inhibition {
|
||||
/// Descriptor returned by `login1`: the lock lasts as long as it is open.
|
||||
login1_lock: Option<zbus::OwnedFd>,
|
||||
/// Session connection and ScreenSaver cookie. The connection is kept alive
|
||||
/// on purpose: closing it releases the cookie.
|
||||
screensaver: Option<(Connection, u32)>,
|
||||
}
|
||||
|
||||
impl fmt::Debug for Inhibition {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.debug_struct("Inhibition")
|
||||
.field("active", &self.active())
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
impl Inhibition {
|
||||
/// Prevents sleep and screen blanking.
|
||||
///
|
||||
/// `reason` is shown by the desktop and `systemd-inhibit --list`: a fixed
|
||||
/// text from the caller, never a window title. It is not logged.
|
||||
///
|
||||
/// Fails only if neither lock could be taken.
|
||||
pub async fn acquire(reason: &str) -> Result<Self, SleepError> {
|
||||
let login1 = inhibit_login1(reason).await;
|
||||
let screensaver = inhibit_screensaver(reason).await;
|
||||
|
||||
let (login1_lock, screensaver) = match (login1, screensaver) {
|
||||
(Err(login1), Err(screensaver)) => {
|
||||
tracing::warn!(
|
||||
event = "sleep_not_inhibited",
|
||||
login1 = %login1,
|
||||
screensaver = %screensaver,
|
||||
"no lock against sleep"
|
||||
);
|
||||
return Err(SleepError::Inhibition {
|
||||
login1,
|
||||
screensaver,
|
||||
});
|
||||
}
|
||||
(login1, screensaver) => {
|
||||
if let Err(error) = &login1 {
|
||||
tracing::warn!(%error, "login1 lock unavailable");
|
||||
}
|
||||
if let Err(error) = &screensaver {
|
||||
tracing::warn!(%error, "ScreenSaver lock unavailable");
|
||||
}
|
||||
(login1.ok(), screensaver.ok())
|
||||
}
|
||||
};
|
||||
|
||||
let inhibition = Self {
|
||||
login1_lock,
|
||||
screensaver,
|
||||
};
|
||||
tracing::info!(
|
||||
event = "sleep_inhibited",
|
||||
mechanisms = ?inhibition.active(),
|
||||
"sleep prevented during the share"
|
||||
);
|
||||
Ok(inhibition)
|
||||
}
|
||||
|
||||
/// Mechanisms actually held: [`MECHANISM_LOGIN1`],
|
||||
/// [`MECHANISM_SCREENSAVER`], or both.
|
||||
pub fn active(&self) -> Vec<&'static str> {
|
||||
active_names(self.login1_lock.is_some(), self.screensaver.is_some())
|
||||
}
|
||||
|
||||
/// Frees the locks right away: `UnInhibit`, then closing the `login1`
|
||||
/// descriptor.
|
||||
pub async fn release(mut self) {
|
||||
let active = self.active();
|
||||
if let Some((connection, cookie)) = self.screensaver.take() {
|
||||
// A failure here prevents nothing: the connection closes right
|
||||
// after, and the daemon forgets the cookie with it.
|
||||
if let Err(error) = connection
|
||||
.call_method(
|
||||
Some(SCREENSAVER_BUS),
|
||||
SCREENSAVER_PATH,
|
||||
Some(SCREENSAVER_INTERFACE),
|
||||
"UnInhibit",
|
||||
&(cookie,),
|
||||
)
|
||||
.await
|
||||
{
|
||||
tracing::debug!(%error, "UnInhibit refused, closing will be enough");
|
||||
}
|
||||
}
|
||||
// Closing the descriptor is enough to hand the lock back to logind.
|
||||
drop(self.login1_lock.take());
|
||||
tracing::info!(
|
||||
event = "sleep_released",
|
||||
mechanisms = ?active,
|
||||
"sleep allowed again"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Inhibition {
|
||||
fn drop(&mut self) {
|
||||
// Nothing to do if `release` already ran.
|
||||
let active = self.active();
|
||||
if active.is_empty() {
|
||||
return;
|
||||
}
|
||||
// The descriptor closes with the field, the connection too: no D-Bus
|
||||
// call is possible in a synchronous `Drop`, and none is needed.
|
||||
tracing::info!(
|
||||
event = "sleep_released",
|
||||
mechanisms = ?active,
|
||||
"sleep allowed again"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Takes the `login1` lock and returns its descriptor.
|
||||
async fn inhibit_login1(reason: &str) -> Result<zbus::OwnedFd, String> {
|
||||
let connection = Connection::system().await.map_err(|e| e.to_string())?;
|
||||
let reply = connection
|
||||
.call_method(
|
||||
Some(LOGIN1_BUS),
|
||||
LOGIN1_PATH,
|
||||
Some(LOGIN1_INTERFACE),
|
||||
"Inhibit",
|
||||
&(LOGIN1_WHAT, APPLICATION, reason, "block"),
|
||||
)
|
||||
.await
|
||||
.map_err(|e| e.to_string())?;
|
||||
// Deserialization duplicates the descriptor: the copy belongs to us and
|
||||
// keeps the lock once the message and the connection are gone.
|
||||
reply
|
||||
.body()
|
||||
.deserialize::<zbus::OwnedFd>()
|
||||
.map_err(|e| format!("unreadable descriptor: {e}"))
|
||||
}
|
||||
|
||||
/// Takes the ScreenSaver lock and returns the connection that carries it.
|
||||
async fn inhibit_screensaver(reason: &str) -> Result<(Connection, u32), String> {
|
||||
let connection = Connection::session().await.map_err(|e| e.to_string())?;
|
||||
let reply = connection
|
||||
.call_method(
|
||||
Some(SCREENSAVER_BUS),
|
||||
SCREENSAVER_PATH,
|
||||
Some(SCREENSAVER_INTERFACE),
|
||||
"Inhibit",
|
||||
&(APPLICATION, reason),
|
||||
)
|
||||
.await
|
||||
.map_err(|e| e.to_string())?;
|
||||
let cookie = reply
|
||||
.body()
|
||||
.deserialize::<u32>()
|
||||
.map_err(|e| format!("unreadable cookie: {e}"))?;
|
||||
Ok((connection, cookie))
|
||||
}
|
||||
|
||||
impl SleepEvent {
|
||||
fn from_signal(going_to_sleep: bool) -> Self {
|
||||
if going_to_sleep {
|
||||
Self::GoingToSleep
|
||||
} else {
|
||||
Self::WokeUp
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Listens for the sleeps and wake-ups announced by `login1`.
|
||||
pub struct WakeWatcher {
|
||||
stream: MessageStream,
|
||||
}
|
||||
|
||||
impl fmt::Debug for WakeWatcher {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.debug_struct("WakeWatcher").finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
/// Subscribes to `PrepareForSleep` on the system bus.
|
||||
///
|
||||
/// Call it before it is needed: a signal emitted before the subscription is
|
||||
/// lost, and a missed wake-up leaves the share frozen.
|
||||
pub async fn watch_wake() -> Result<WakeWatcher, SleepError> {
|
||||
let connection = Connection::system()
|
||||
.await
|
||||
.map_err(|e| SleepError::Bus(e.to_string()))?;
|
||||
let rule = MatchRule::builder()
|
||||
.msg_type(zbus::message::Type::Signal)
|
||||
// No sender filter: the signal arrives under logind's unique name, not
|
||||
// under `org.freedesktop.login1`. Only root can emit on this path of
|
||||
// the system bus.
|
||||
.interface(LOGIN1_INTERFACE)
|
||||
.member("PrepareForSleep")
|
||||
.path(LOGIN1_PATH)
|
||||
.build()
|
||||
.map_err(|e| SleepError::Subscription(e.to_string()))?;
|
||||
let stream = MessageStream::for_match_rule(rule, &connection, None)
|
||||
.await
|
||||
.map_err(|e| SleepError::Subscription(e.to_string()))?;
|
||||
Ok(WakeWatcher { stream })
|
||||
}
|
||||
|
||||
impl WakeWatcher {
|
||||
/// Waits for the next transition. `None` when the connection to the
|
||||
/// system bus is lost: no wake-up will be announced anymore.
|
||||
pub async fn next_event(&mut self) -> Option<SleepEvent> {
|
||||
loop {
|
||||
let message = match self.stream.next().await? {
|
||||
Ok(message) => message,
|
||||
Err(error) => {
|
||||
tracing::debug!(%error, "unreadable message on the system bus");
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let Ok(going_to_sleep) = message.body().deserialize::<bool>() else {
|
||||
continue;
|
||||
};
|
||||
let event = SleepEvent::from_signal(going_to_sleep);
|
||||
match event {
|
||||
SleepEvent::GoingToSleep => {
|
||||
tracing::info!(event = "going_to_sleep", "the machine is going to sleep");
|
||||
}
|
||||
SleepEvent::WokeUp => {
|
||||
tracing::info!(event = "woke_up", "the machine is waking up");
|
||||
}
|
||||
}
|
||||
return Some(event);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn active_mechanisms_are_named_in_a_stable_order() {
|
||||
assert_eq!(active_names(true, true), ["login1", "screensaver"]);
|
||||
assert_eq!(active_names(false, true), ["screensaver"]);
|
||||
assert_eq!(active_names(true, false), ["login1"]);
|
||||
assert!(active_names(false, false).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prepare_for_sleep_maps_true_to_sleep_and_false_to_wake() {
|
||||
assert_eq!(SleepEvent::from_signal(true), SleepEvent::GoingToSleep);
|
||||
assert_eq!(SleepEvent::from_signal(false), SleepEvent::WokeUp);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_lid_switch_is_never_inhibited() {
|
||||
// Closing the lid is an explicit gesture: blocking it would surprise.
|
||||
assert!(!LOGIN1_WHAT.contains("handle-lid-switch"));
|
||||
assert_eq!(LOGIN1_WHAT, "sleep:idle");
|
||||
}
|
||||
|
||||
/// Lines of `systemd-inhibit --list` that come from this process.
|
||||
fn locks_of_this_process() -> Vec<String> {
|
||||
let output = std::process::Command::new("systemd-inhibit")
|
||||
.args(["--list", "--no-pager", "--no-legend"])
|
||||
.output()
|
||||
.expect("systemd-inhibit not found");
|
||||
let pid = std::process::id().to_string();
|
||||
String::from_utf8_lossy(&output.stdout)
|
||||
.lines()
|
||||
.filter(|l| {
|
||||
let fields: Vec<&str> = l.split_whitespace().collect();
|
||||
fields.first() == Some(&APPLICATION) && fields.contains(&pid.as_str())
|
||||
})
|
||||
.map(str::to_string)
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Takes a real lock on this machine: needs logind and a desktop that
|
||||
/// exposes ScreenSaver. `cargo test -p rs-platform sleep -- --ignored`.
|
||||
#[tokio::test]
|
||||
#[ignore = "needs logind and a desktop session"]
|
||||
async fn a_real_inhibition_shows_in_systemd_inhibit_then_goes_away() {
|
||||
let inhibition = Inhibition::acquire("screen sharing in progress (test)")
|
||||
.await
|
||||
.expect("no lock taken");
|
||||
let active = inhibition.active();
|
||||
assert!(active.contains(&MECHANISM_LOGIN1), "{active:?}");
|
||||
eprintln!("mechanisms held: {active:?}");
|
||||
|
||||
let lines = locks_of_this_process();
|
||||
assert_eq!(lines.len(), 1, "{lines:?}");
|
||||
assert!(lines[0].contains("sleep:idle"), "{}", lines[0]);
|
||||
assert!(lines[0].contains("block"), "{}", lines[0]);
|
||||
|
||||
inhibition.release().await;
|
||||
let lines = locks_of_this_process();
|
||||
assert!(lines.is_empty(), "lock still held: {lines:?}");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn subscribing_to_resume_never_panics() {
|
||||
// Without a system bus, the error must be readable, never a panic.
|
||||
if let Err(error) = watch_wake().await {
|
||||
assert!(!error.to_string().is_empty());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,230 @@
|
||||
//! Sleep on Windows: a power request, and the suspend and resume notification.
|
||||
|
||||
use std::ffi::c_void;
|
||||
use std::fmt;
|
||||
|
||||
use tokio::sync::mpsc;
|
||||
use windows_sys::Win32::Foundation::{CloseHandle, ERROR_SUCCESS, HANDLE};
|
||||
use windows_sys::Win32::System::Power::{
|
||||
DEVICE_NOTIFY_SUBSCRIBE_PARAMETERS, PowerClearRequest, PowerCreateRequest,
|
||||
PowerRegisterSuspendResumeNotification, PowerRequestDisplayRequired,
|
||||
PowerRequestSystemRequired, PowerSetRequest, PowerUnregisterSuspendResumeNotification,
|
||||
};
|
||||
use windows_sys::Win32::System::SystemServices::POWER_REQUEST_CONTEXT_VERSION;
|
||||
use windows_sys::Win32::System::Threading::{POWER_REQUEST_CONTEXT_SIMPLE_STRING, REASON_CONTEXT};
|
||||
use windows_sys::Win32::UI::WindowsAndMessaging::{
|
||||
DEVICE_NOTIFY_CALLBACK, PBT_APMRESUMEAUTOMATIC, PBT_APMSUSPEND,
|
||||
};
|
||||
|
||||
use super::{APPLICATION, SleepError, SleepEvent};
|
||||
|
||||
/// Name of the power request in [`Inhibition::active`] and the logs.
|
||||
pub const MECHANISM_POWER_REQUEST: &str = "power_request";
|
||||
|
||||
/// A power request, held as long as the value lives: the system stays awake
|
||||
/// and the display on. `powercfg /requests` lists it under `rustscreen`.
|
||||
pub struct Inhibition {
|
||||
request: Option<HANDLE>,
|
||||
}
|
||||
|
||||
// The handle is a kernel object, usable from any thread.
|
||||
unsafe impl Send for Inhibition {}
|
||||
unsafe impl Sync for Inhibition {}
|
||||
|
||||
impl fmt::Debug for Inhibition {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.debug_struct("Inhibition")
|
||||
.field("active", &self.active())
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
impl Inhibition {
|
||||
/// Prevents sleep and screen blanking. `reason` is shown by
|
||||
/// `powercfg /requests`: a fixed text from the caller, never a window
|
||||
/// title. It is not logged.
|
||||
pub async fn acquire(reason: &str) -> Result<Self, SleepError> {
|
||||
let request = create_request(reason).map_err(|error| {
|
||||
tracing::warn!(event = "sleep_not_inhibited", %error, "no lock against sleep");
|
||||
SleepError::Power(error)
|
||||
})?;
|
||||
let inhibition = Self {
|
||||
request: Some(request),
|
||||
};
|
||||
tracing::info!(
|
||||
event = "sleep_inhibited",
|
||||
mechanisms = ?inhibition.active(),
|
||||
"sleep prevented during the share"
|
||||
);
|
||||
Ok(inhibition)
|
||||
}
|
||||
|
||||
pub fn active(&self) -> Vec<&'static str> {
|
||||
if self.request.is_some() {
|
||||
vec![MECHANISM_POWER_REQUEST]
|
||||
} else {
|
||||
Vec::new()
|
||||
}
|
||||
}
|
||||
|
||||
/// Frees the request right away.
|
||||
pub async fn release(mut self) {
|
||||
self.close();
|
||||
}
|
||||
|
||||
fn close(&mut self) {
|
||||
let Some(request) = self.request.take() else {
|
||||
return;
|
||||
};
|
||||
// SAFETY: `request` comes from `PowerCreateRequest` and is closed once.
|
||||
unsafe {
|
||||
PowerClearRequest(request, PowerRequestSystemRequired);
|
||||
PowerClearRequest(request, PowerRequestDisplayRequired);
|
||||
CloseHandle(request);
|
||||
}
|
||||
tracing::info!(
|
||||
event = "sleep_released",
|
||||
mechanisms = ?[MECHANISM_POWER_REQUEST],
|
||||
"sleep allowed again"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Inhibition {
|
||||
fn drop(&mut self) {
|
||||
self.close();
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates the request, system and display required.
|
||||
fn create_request(reason: &str) -> Result<HANDLE, String> {
|
||||
// Windows reads the string while the request lives, not only during the
|
||||
// call: it is leaked on purpose, a few bytes per share.
|
||||
let text: Vec<u16> = format!("{APPLICATION}: {reason}")
|
||||
.encode_utf16()
|
||||
.chain(Some(0))
|
||||
.collect();
|
||||
let text = Box::leak(text.into_boxed_slice());
|
||||
let mut context = REASON_CONTEXT {
|
||||
Version: POWER_REQUEST_CONTEXT_VERSION,
|
||||
Flags: POWER_REQUEST_CONTEXT_SIMPLE_STRING,
|
||||
..Default::default()
|
||||
};
|
||||
context.Reason.SimpleReasonString = text.as_mut_ptr();
|
||||
// SAFETY: `context` and the string it points to outlive the call.
|
||||
let request = unsafe { PowerCreateRequest(&context) };
|
||||
if request.is_null() || request as isize == -1 {
|
||||
return Err(format!(
|
||||
"PowerCreateRequest: {}",
|
||||
std::io::Error::last_os_error()
|
||||
));
|
||||
}
|
||||
// SAFETY: `request` is a valid power request handle.
|
||||
let held = unsafe {
|
||||
PowerSetRequest(request, PowerRequestSystemRequired) != 0
|
||||
&& PowerSetRequest(request, PowerRequestDisplayRequired) != 0
|
||||
};
|
||||
if !held {
|
||||
let error = std::io::Error::last_os_error();
|
||||
// SAFETY: closed once, on the failure path only.
|
||||
unsafe { CloseHandle(request) };
|
||||
return Err(format!("PowerSetRequest: {error}"));
|
||||
}
|
||||
Ok(request)
|
||||
}
|
||||
|
||||
/// Listens for the suspends and resumes Windows announces.
|
||||
pub struct WakeWatcher {
|
||||
events: mpsc::UnboundedReceiver<SleepEvent>,
|
||||
registration: *mut c_void,
|
||||
/// Given to Windows as the callback context: freed after unregistering.
|
||||
sender: *mut mpsc::UnboundedSender<SleepEvent>,
|
||||
}
|
||||
|
||||
// The registration handle and the sender are only touched by `Drop`, after
|
||||
// Windows stopped calling back.
|
||||
unsafe impl Send for WakeWatcher {}
|
||||
unsafe impl Sync for WakeWatcher {}
|
||||
|
||||
impl fmt::Debug for WakeWatcher {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.debug_struct("WakeWatcher").finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
/// Called by Windows on a thread of its own, for each power transition.
|
||||
unsafe extern "system" fn on_power(
|
||||
context: *const c_void,
|
||||
kind: u32,
|
||||
_setting: *const c_void,
|
||||
) -> u32 {
|
||||
let event = match kind {
|
||||
PBT_APMSUSPEND => SleepEvent::GoingToSleep,
|
||||
PBT_APMRESUMEAUTOMATIC => SleepEvent::WokeUp,
|
||||
_ => return ERROR_SUCCESS,
|
||||
};
|
||||
// SAFETY: `context` is the sender boxed by `watch_wake`, alive until the
|
||||
// registration is withdrawn.
|
||||
let sender = unsafe { &*context.cast::<mpsc::UnboundedSender<SleepEvent>>() };
|
||||
let _ = sender.send(event);
|
||||
ERROR_SUCCESS
|
||||
}
|
||||
|
||||
/// Subscribes to the suspend and resume notification.
|
||||
pub async fn watch_wake() -> Result<WakeWatcher, SleepError> {
|
||||
let (sender, events) = mpsc::unbounded_channel();
|
||||
let sender = Box::into_raw(Box::new(sender));
|
||||
let mut parameters = DEVICE_NOTIFY_SUBSCRIBE_PARAMETERS {
|
||||
Callback: Some(on_power),
|
||||
Context: sender.cast(),
|
||||
};
|
||||
let mut registration = std::ptr::null_mut();
|
||||
// SAFETY: with DEVICE_NOTIFY_CALLBACK, the recipient is the parameter
|
||||
// block, which Windows copies; the context stays valid until `Drop`.
|
||||
let status = unsafe {
|
||||
PowerRegisterSuspendResumeNotification(
|
||||
DEVICE_NOTIFY_CALLBACK,
|
||||
(&raw mut parameters).cast(),
|
||||
&mut registration,
|
||||
)
|
||||
};
|
||||
if status != ERROR_SUCCESS {
|
||||
// SAFETY: never handed to Windows.
|
||||
drop(unsafe { Box::from_raw(sender) });
|
||||
return Err(SleepError::Subscription(
|
||||
std::io::Error::from_raw_os_error(status as i32).to_string(),
|
||||
));
|
||||
}
|
||||
Ok(WakeWatcher {
|
||||
events,
|
||||
registration,
|
||||
sender,
|
||||
})
|
||||
}
|
||||
|
||||
impl WakeWatcher {
|
||||
/// Waits for the next transition.
|
||||
pub async fn next_event(&mut self) -> Option<SleepEvent> {
|
||||
let event = self.events.recv().await?;
|
||||
match event {
|
||||
SleepEvent::GoingToSleep => {
|
||||
tracing::info!(event = "going_to_sleep", "the machine is going to sleep");
|
||||
}
|
||||
SleepEvent::WokeUp => {
|
||||
tracing::info!(event = "woke_up", "the machine is waking up");
|
||||
}
|
||||
}
|
||||
Some(event)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for WakeWatcher {
|
||||
fn drop(&mut self) {
|
||||
// SAFETY: the registration comes from `watch_wake`; once withdrawn,
|
||||
// Windows no longer calls back, and the sender can go.
|
||||
unsafe {
|
||||
PowerUnregisterSuspendResumeNotification(self.registration as isize);
|
||||
drop(Box::from_raw(self.sender));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -6,12 +6,13 @@
|
||||
pub mod messages;
|
||||
pub mod pairing;
|
||||
pub mod session;
|
||||
pub mod trust;
|
||||
|
||||
pub use messages::{ClientMessage, ErrorCode, ServerMessage};
|
||||
pub use pairing::{LINK_VERSION, PairingRequest, PairingResponse, normalize_code};
|
||||
pub use session::{
|
||||
DeviceId, DeviceInfo, QualityPreset, RoomId, SessionToken, SourceId, SourceInfo, SourceKind,
|
||||
StreamSettings,
|
||||
DEVICE_NAME_MAX, DeviceId, DeviceInfo, QualityPreset, RoomId, SessionToken, SourceId,
|
||||
SourceInfo, SourceKind, StreamSettings, clean_name,
|
||||
};
|
||||
|
||||
/// Protocol version, negotiated in `hello`.
|
||||
|
||||
@@ -19,6 +19,10 @@ pub enum ErrorCode {
|
||||
/// a new one: distinct from `BadToken` so the viewer knows it needs a
|
||||
/// fresh QR code, not that it made a mistake (#19).
|
||||
TokenExpired,
|
||||
/// The token was valid and still in time, but another device used it
|
||||
/// first: the link is good for one viewer (#35). The viewer asks for the
|
||||
/// new QR code shown by the host, exactly as for `TokenExpired`.
|
||||
TokenUsed,
|
||||
RoomFull,
|
||||
SourceUnavailable,
|
||||
ProtocolViolation,
|
||||
@@ -27,6 +31,10 @@ pub enum ErrorCode {
|
||||
Kicked,
|
||||
/// The host stopped sharing: the room no longer exists.
|
||||
ShareEnded,
|
||||
/// The device came back by its key, but the host does not trust it (or no
|
||||
/// longer does), or the signature did not match (#34). The viewer forgets
|
||||
/// that it was trusted and asks for the QR code again.
|
||||
NotTrusted,
|
||||
}
|
||||
|
||||
/// What the viewer sends to the host.
|
||||
@@ -35,12 +43,25 @@ pub enum ErrorCode {
|
||||
#[ts(export)]
|
||||
pub enum ClientMessage {
|
||||
/// First message: the version decides what follows, the token authorizes.
|
||||
///
|
||||
/// A device the host trusts (#34) may come without a room nor a token: it
|
||||
/// carries its public key, the host answers with a [`ServerMessage::Challenge`]
|
||||
/// and the device proves it holds the private key. A device the host does
|
||||
/// not trust goes through the token, key or not.
|
||||
Hello {
|
||||
version: u16,
|
||||
room: RoomId,
|
||||
token: SessionToken,
|
||||
#[serde(default)]
|
||||
room: Option<RoomId>,
|
||||
#[serde(default)]
|
||||
token: Option<SessionToken>,
|
||||
device: DeviceInfo,
|
||||
/// Ed25519 public key of the device, 64 hex digits. Never the private key.
|
||||
#[serde(default)]
|
||||
key: Option<String>,
|
||||
},
|
||||
/// Answer to [`ServerMessage::Challenge`]: the Ed25519 signature, 128 hex
|
||||
/// digits, of [`crate::trust::signed_message`] for the nonce received.
|
||||
Proof { signature: String },
|
||||
/// The viewer's SDP offer: one receive-only video track.
|
||||
///
|
||||
/// The browser offers, the host answers. This choice comes from the spike:
|
||||
@@ -54,6 +75,9 @@ pub enum ClientMessage {
|
||||
},
|
||||
/// Request to change the quality preset.
|
||||
QualityRequest { settings: StreamSettings },
|
||||
/// The viewer renamed this device (#36). The host's alias, if any, still
|
||||
/// wins in its own interface.
|
||||
Rename { name: String },
|
||||
/// Voluntary leave, to free the slot without waiting for the timeout.
|
||||
Bye,
|
||||
}
|
||||
@@ -72,6 +96,18 @@ pub enum ServerMessage {
|
||||
/// Number of viewers already connected, and the limit.
|
||||
connected: u8,
|
||||
limit: u8,
|
||||
/// The device got in by its key: it may come back without a link (#34).
|
||||
trusted: bool,
|
||||
},
|
||||
/// The host trusts the key of the `hello`: sign this nonce (64 hex digits,
|
||||
/// fresh for each connection) to prove the private key is here (#34).
|
||||
Challenge {
|
||||
nonce: String,
|
||||
},
|
||||
/// The host started or stopped trusting this device during the session:
|
||||
/// the viewer remembers it, to come back without a link or to stop trying.
|
||||
Trust {
|
||||
trusted: bool,
|
||||
},
|
||||
/// The host's answer to the viewer's offer.
|
||||
Answer {
|
||||
@@ -117,9 +153,10 @@ mod tests {
|
||||
fn hello_round_trips_through_json() {
|
||||
let msg = ClientMessage::Hello {
|
||||
version: crate::PROTOCOL_VERSION,
|
||||
room: RoomId::parse("abc234").unwrap(),
|
||||
token: SessionToken::new("00112233445566778899aabbccddeeff"),
|
||||
room: Some(RoomId::parse("abc234").unwrap()),
|
||||
token: Some(SessionToken::new("00112233445566778899aabbccddeeff")),
|
||||
device: device(),
|
||||
key: None,
|
||||
};
|
||||
let json = serde_json::to_string(&msg).unwrap();
|
||||
assert!(json.contains("\"type\":\"hello\""), "{json}");
|
||||
@@ -136,12 +173,26 @@ mod tests {
|
||||
settings: StreamSettings::for_preset(crate::session::QualityPreset::Balanced),
|
||||
connected: 1,
|
||||
limit: 5,
|
||||
trusted: false,
|
||||
};
|
||||
let json = serde_json::to_string(&msg).unwrap();
|
||||
assert!(json.contains("\"type\":\"welcome\""), "{json}");
|
||||
assert!(json.contains("\"quality\":\"balanced\""), "{json}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_hello_from_an_older_viewer_still_reads() {
|
||||
// Before #34: no key, room and token always present.
|
||||
let json = r#"{"type":"hello","version":1,"room":"abc234","token":"00112233445566778899aabbccddeeff","device":{"id":"d","name":"","user_agent":null,"platform":null}}"#;
|
||||
match serde_json::from_str::<ClientMessage>(json).unwrap() {
|
||||
ClientMessage::Hello { room, key, .. } => {
|
||||
assert!(room.is_some());
|
||||
assert!(key.is_none());
|
||||
}
|
||||
other => panic!("{other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_message_is_rejected_explicitly() {
|
||||
let err = serde_json::from_str::<ClientMessage>("{\"type\":\"teleport\"}").unwrap_err();
|
||||
|
||||
@@ -118,6 +118,26 @@ pub struct SourceInfo {
|
||||
#[ts(export, type = "string")]
|
||||
pub struct DeviceId(pub String);
|
||||
|
||||
/// Longest device name kept, in characters (#36). The viewer's field has the
|
||||
/// same `maxLength`.
|
||||
pub const DEVICE_NAME_MAX: usize = 40;
|
||||
|
||||
/// A device name as the host keeps it: control characters removed, spaces
|
||||
/// collapsed, at most [`DEVICE_NAME_MAX`] characters. Markup is not removed:
|
||||
/// it is text, and every interface displays it as such (#36).
|
||||
pub fn clean_name(raw: &str) -> String {
|
||||
raw.split(|c: char| c.is_whitespace() || c.is_control())
|
||||
.filter(|part| !part.is_empty())
|
||||
.collect::<Vec<_>>()
|
||||
.join(" ")
|
||||
.chars()
|
||||
.filter(|c| !c.is_control())
|
||||
.take(DEVICE_NAME_MAX)
|
||||
.collect::<String>()
|
||||
.trim_end()
|
||||
.to_string()
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
|
||||
#[ts(export)]
|
||||
pub struct DeviceInfo {
|
||||
@@ -149,19 +169,21 @@ pub struct StreamSettings {
|
||||
impl StreamSettings {
|
||||
pub fn for_preset(quality: QualityPreset) -> Self {
|
||||
match quality {
|
||||
// Sized for a local network (#86): 60 fps by default, the host
|
||||
// lowering its cadence by itself when it cannot keep up.
|
||||
QualityPreset::Saver => Self {
|
||||
quality,
|
||||
max_bitrate_kbps: 1_200,
|
||||
max_fps: 20,
|
||||
max_bitrate_kbps: 2_000,
|
||||
max_fps: 30,
|
||||
},
|
||||
QualityPreset::Balanced => Self {
|
||||
quality,
|
||||
max_bitrate_kbps: 3_000,
|
||||
max_fps: 30,
|
||||
max_bitrate_kbps: 6_000,
|
||||
max_fps: 60,
|
||||
},
|
||||
QualityPreset::Sharp => Self {
|
||||
quality,
|
||||
max_bitrate_kbps: 8_000,
|
||||
max_bitrate_kbps: 12_000,
|
||||
max_fps: 60,
|
||||
},
|
||||
}
|
||||
@@ -202,3 +224,18 @@ mod tests {
|
||||
assert!(sharp.max_fps > saver.max_fps);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod name_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_name_is_cleaned_not_escaped() {
|
||||
assert_eq!(clean_name(" iPad\tdu\n salon "), "iPad du salon");
|
||||
assert_eq!(clean_name("a\u{7}b"), "a b");
|
||||
// Markup stays text: displaying it literally is the interfaces' job.
|
||||
assert_eq!(clean_name("<b>Kitchen</b>"), "<b>Kitchen</b>");
|
||||
assert_eq!(clean_name(&"é".repeat(60)).chars().count(), DEVICE_NAME_MAX);
|
||||
assert_eq!(clean_name(" "), "");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
//! What a trusted device signs to come back without a link (#34).
|
||||
//!
|
||||
//! The host sends a fresh 32-byte nonce, the device signs the bytes below with
|
||||
//! its Ed25519 key. The context prefix is fixed on both sides, never sent by
|
||||
//! the host: a device does not sign whatever it is handed, so its key cannot
|
||||
//! be turned into a signing oracle for something else. The viewer writes the
|
||||
//! same prefix in `apps/viewer/src/lib/trust.ts`, and both test suites check
|
||||
//! the same vector (`TEST_VECTOR`).
|
||||
|
||||
/// Domain separation: names the protocol and its version.
|
||||
pub const TRUST_CONTEXT: &str = "rustscreen-trust-v1";
|
||||
|
||||
/// Length of the nonce, in bytes.
|
||||
pub const NONCE_LEN: usize = 32;
|
||||
|
||||
/// The bytes signed for a nonce: the context, a zero byte, the nonce.
|
||||
pub fn signed_message(nonce: &[u8; NONCE_LEN]) -> Vec<u8> {
|
||||
let mut message = Vec::with_capacity(TRUST_CONTEXT.len() + 1 + NONCE_LEN);
|
||||
message.extend_from_slice(TRUST_CONTEXT.as_bytes());
|
||||
message.push(0);
|
||||
message.extend_from_slice(nonce);
|
||||
message
|
||||
}
|
||||
|
||||
/// Shared test vector, in hex: secret key (seed), public key, nonce, signature.
|
||||
/// The viewer's tests check the same four values.
|
||||
pub const TEST_VECTOR: [&str; 4] = [
|
||||
"9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60",
|
||||
"d75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a",
|
||||
"000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f",
|
||||
"76d5c3961e096b67f6932039110292bb727a9475552afe48961c0073c653001e8fba219441d9795a9aa721224353aa589049d2d1050e0f37ce32b7953ea86f0e",
|
||||
];
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn the_message_starts_with_the_context_and_ends_with_the_nonce() {
|
||||
let nonce = [7u8; NONCE_LEN];
|
||||
let message = signed_message(&nonce);
|
||||
assert!(message.starts_with(b"rustscreen-trust-v1\0"));
|
||||
assert!(message.ends_with(&nonce));
|
||||
assert_eq!(message.len(), TRUST_CONTEXT.len() + 1 + NONCE_LEN);
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,7 @@ repository.workspace = true
|
||||
[dependencies]
|
||||
rs-codec = { path = "../rs-codec" }
|
||||
str0m = "0.24.1"
|
||||
if-addrs = "0.15.0"
|
||||
thiserror.workspace = true
|
||||
tracing.workspace = true
|
||||
tokio = { version = "1.54.1", features = ["rt", "net", "time", "sync", "macros"] }
|
||||
Loaded 100 of 161 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user