Compare commits
92
Commits
v0.1.0
...
b6240c17c5
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b6240c17c5 | ||
|
|
c1b21b32c7 | ||
|
|
b0ff20fe3f | ||
|
|
b5c03e7705 | ||
|
|
31b33e9e5a | ||
|
|
e16b7190bb | ||
|
|
c39ab081d9 | ||
|
|
646f35d3eb | ||
|
|
ff7daee34e | ||
|
|
85fdebeb66 | ||
|
|
cfc480044f | ||
|
|
6d0bf99076 | ||
|
|
04bc0a808a | ||
|
|
b0fa259187 | ||
|
|
1a746461b4 | ||
|
|
9e839ca452 | ||
|
|
f5d0333366 | ||
|
|
14fc1af716 | ||
|
|
9b9328f6a9 | ||
|
|
2d0143f1aa | ||
|
|
e8273b364e | ||
|
|
472991c11f | ||
|
|
ccd8c33f81 | ||
|
|
c876c61ec6 | ||
|
|
b1d73caedf | ||
|
|
40960c7476 | ||
|
|
0a4bb554e9 | ||
|
|
7e470fb2c5 | ||
|
|
9d685c2c48 | ||
|
|
42ffe8928c | ||
|
|
69ddc58133 | ||
|
|
09a07f5303 | ||
|
|
eb077d81f0 | ||
|
|
32131b0ccb | ||
|
|
035aa4b256 | ||
|
|
f85c0c22c7 | ||
|
|
c30418a0f5 | ||
|
|
14245cbf08 | ||
|
|
a740376ea9 | ||
|
|
e1ed89026d | ||
|
|
a7ea1fd9df | ||
|
|
7a03dee12f | ||
|
|
6f1ccf3923 | ||
|
|
8cd2d63a87 | ||
|
|
511927569b | ||
|
|
b260d57dc4 | ||
|
|
ad70ce5ea9 | ||
|
|
6c275faf28 | ||
|
|
2edd7f0fa8 | ||
|
|
f4a4dd37c9 | ||
|
|
56d0d6c2e2 | ||
|
|
675f25f266 | ||
|
|
e54d625f2a | ||
|
|
f926dbea4e | ||
|
|
24e0d0e799 | ||
|
|
e8f86b0ac2 | ||
|
|
5d519ede78 | ||
|
|
ccb183219f | ||
|
|
d23848decc | ||
|
|
48f5510699 | ||
|
|
125e44c033 | ||
|
|
57328f740c | ||
|
|
0187bc9bcf | ||
|
|
90e0dc8621 | ||
|
|
0be92f36a5 | ||
|
|
6f0fd088f6 | ||
|
|
e7ded10db8 | ||
|
|
6619bc9b0f | ||
|
|
29d8850bc5 | ||
|
|
8044a42f98 | ||
|
|
7483b9aae8 | ||
|
|
45e5d7ef37 | ||
|
|
cd127a9704 | ||
|
|
0c9d8eb9f9 | ||
|
|
7fa5d410f9 | ||
|
|
8674f907f2 | ||
|
|
25a5b597f7 | ||
|
|
54ebe96ca1 | ||
|
|
a144665f41 | ||
|
|
339a9d49e4 | ||
|
|
8d32ded412 | ||
|
|
9625511c65 | ||
|
|
e1a018fdf7 | ||
|
|
f939441e31 | ||
|
|
153febe078 | ||
|
|
ffe5a90686 | ||
|
|
74b4101d4f | ||
|
|
6e4d30bfa9 | ||
|
|
15766834f1 | ||
|
|
0a253bd919 | ||
|
|
3aa8d73ea0 | ||
|
|
8619df10d5 |
Generated
+2047
-110
File diff suppressed because it is too large
Load Diff
+57
-1
@@ -2,10 +2,31 @@
|
||||
name = "pixelpass"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
description = "P2P screen sharing CLI over iroh + ffmpeg"
|
||||
description = "P2P screen sharing CLI over iroh"
|
||||
license = "MIT OR Apache-2.0"
|
||||
publish = false
|
||||
|
||||
# Debian/Ubuntu packaging (cargo-deb). Headless default build (no `gui` feature) —
|
||||
# that is exactly what peerspeak spawns as a child. Runtime shared-lib deps
|
||||
# (libpipewire, libc, …) are resolved by dpkg-shlibdeps via `depends = "$auto"`.
|
||||
# Build inside a Debian/Ubuntu distrobox, then `cargo deb --no-build`.
|
||||
[package.metadata.deb]
|
||||
maintainer = "mollusk <jitty+lc1iz0dc@protonmail.com>"
|
||||
section = "net"
|
||||
priority = "optional"
|
||||
# $auto covers linked shared libs (dpkg-shlibdeps). The GStreamer capture stack
|
||||
# and pactl are invoked as *subprocesses* (gst-launch-1.0 / gst-inspect-1.0 /
|
||||
# pactl), so shlibdeps can't see them — list them explicitly or a fresh Ubuntu
|
||||
# host bails at `deps::check_host_binaries` before emitting its ticket. Covers
|
||||
# both backends: pipewiresrc (Wayland), ximagesrc (X11, in plugins-good), the
|
||||
# VAAPI + software H.264 encoders, the AAC/TS mux tail, and the PulseAudio src.
|
||||
depends = "$auto, gstreamer1.0-tools, gstreamer1.0-plugins-base, gstreamer1.0-plugins-good, gstreamer1.0-plugins-bad, gstreamer1.0-plugins-ugly, gstreamer1.0-libav, gstreamer1.0-pipewire, gstreamer1.0-pulseaudio, pulseaudio-utils, x11-utils"
|
||||
recommends = "mpv"
|
||||
extended-description = "Peer-to-peer screen sharing over iroh (QUIC). Companion to peerspeak: shares a window or screen directly to a peer with no central server, driven via the CLI and its JSON event stream."
|
||||
assets = [
|
||||
["target/release/pixelpass", "usr/bin/", "755"],
|
||||
]
|
||||
|
||||
[[bin]]
|
||||
name = "pixelpass"
|
||||
path = "src/main.rs"
|
||||
@@ -30,8 +51,43 @@ uuid = { version = "1", features = ["v4"] }
|
||||
iroh-tickets = "1.0.0-rc.0"
|
||||
dialoguer = { version = "0.12", default-features = false }
|
||||
arboard = { version = "3", default-features = false, features = ["wayland-data-control"] }
|
||||
ureq = { version = "3", default-features = false, features = ["rustls"] }
|
||||
toml = "1"
|
||||
chrono = { version = "0.4", default-features = false, features = ["clock", "serde"] }
|
||||
eframe = { version = "0.34.2", default-features = false, features = ["glow", "default_fonts", "wayland", "x11"], optional = true }
|
||||
# Desktop notifications on viewer join/leave. Default features give the
|
||||
# pure-Rust zbus backend (no system libdbus, no image crate).
|
||||
notify-rust = { version = "4", optional = true }
|
||||
# System-tray icon (StatusNotifierItem over D-Bus). Pure-Rust, riding the same
|
||||
# zbus stack notify-rust already pulls — no GTK, no libappindicator/C libdbus.
|
||||
ksni = { version = "0.3", optional = true }
|
||||
# Hand-rolled windowing stack for the GUI (replaces eframe::run_native) so we
|
||||
# can drop the OS window on "hide to tray" — the only way to truly hide a
|
||||
# toplevel on Wayland — and recreate it on Show. All of these are already pulled
|
||||
# in transitively by eframe; making them direct adds no new crates to vet.
|
||||
# eframe is kept for its egui re-export + icon_data PNG decoder. egui_glow needs
|
||||
# its (non-default) `winit` feature for the `EguiGlow` integration type; eframe
|
||||
# pulls egui_glow but without that feature, so we enable it here.
|
||||
egui_glow = { version = "0.34.2", default-features = false, features = ["winit", "wayland", "x11"], optional = true }
|
||||
# winit's default set minus `wayland-csd-adwaita`: KWin (and most desktop
|
||||
# compositors) draw server-side decorations, and eframe never enabled CSD
|
||||
# either, so dropping it keeps the dependency tree identical to before (no
|
||||
# sctk-adwaita / tiny-skia / ttf-parser pulled in just for a fallback titlebar).
|
||||
winit = { version = "0.30", default-features = false, features = ["rwh_06", "x11", "wayland", "wayland-dlopen"], optional = true }
|
||||
glutin = { version = "0.32", optional = true }
|
||||
glutin-winit = { version = "0.5", optional = true }
|
||||
# QR-encode the host ticket so a phone (or a second laptop with a webcam) can
|
||||
# pick it up without typing 140 chars. default-features = false to skip the
|
||||
# `image` crate dep tree — we render the modules to an `egui::ColorImage`
|
||||
# directly.
|
||||
qrcode = { version = "0.14", default-features = false, optional = true }
|
||||
|
||||
[profile.release]
|
||||
lto = "thin"
|
||||
codegen-units = 1
|
||||
strip = "symbols"
|
||||
|
||||
[features]
|
||||
# Opt-in graphical front-end (pixelpass --gui). Default-off so the headless
|
||||
# build never pulls the GUI toolkit tree.
|
||||
gui = ["dep:eframe", "dep:notify-rust", "dep:ksni", "dep:egui_glow", "dep:winit", "dep:glutin", "dep:glutin-winit", "dep:qrcode"]
|
||||
|
||||
+202
@@ -0,0 +1,202 @@
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright 2026 mollusk
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 mollusk
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -0,0 +1,421 @@
|
||||
# pixelpass
|
||||
|
||||
P2P screen sharing CLI for Linux. Single binary, hole-punched over
|
||||
[iroh](https://www.iroh.computer/) — no port forwarding, no signup, no
|
||||
server-side accounts. Hardware-encoded H.264 + AAC audio, viewed in
|
||||
mpv or VLC.
|
||||
|
||||
Built for people who just want to show their screen to a friend
|
||||
without spinning up a Discord call or fighting with NAT.
|
||||
|
||||
## Status
|
||||
|
||||
**v0.1.0** — verified end-to-end on the public internet (LTE relay path,
|
||||
~2s latency, real carrier-grade NAT) as of 2026-05-20.
|
||||
|
||||
Working:
|
||||
- Wayland capture via the screencast portal (KDE Plasma 6 confirmed; other
|
||||
Wayland compositors with the portal should work but are untested)
|
||||
- X11 capture via `ximagesrc` (whole screen, or a single window with
|
||||
`--window`); selected automatically, or forced with `--display-server x11`
|
||||
- VAAPI H.264 encode in GStreamer (RDNA3 confirmed; other VAAPI-capable
|
||||
GPUs should work), with a software x264 fallback via `--no-hwencode`
|
||||
- Audio capture of the default sink's monitor, with optional per-app
|
||||
routing (`--app <name>`)
|
||||
- `--repair` cleanup of orphaned PipeWire state left by a crashed host
|
||||
- `--doctor` environment diagnostic (capture/encode deps, VA-API H.264,
|
||||
viewer player, relay reachability) — see [Diagnostics](#diagnostics)
|
||||
- iroh QUIC bi-stream tunnel, direct-UDP and relay paths both verified
|
||||
- Interactive Host/View menu with clipboard auto-copy and mpv/VLC picker
|
||||
- Headless mode for scripts (`pixelpass <ticket>`)
|
||||
- Multi-viewer fanout (default 2, configurable via `--max-viewers`;
|
||||
shared gst pipeline, one broadcast channel per host)
|
||||
- First-run upstream bandwidth pre-flight, persisted to
|
||||
`~/.config/pixelpass/config.toml` and used to auto-size the default
|
||||
viewer cap
|
||||
- Quality presets (`--quality source|high|medium|low|auto`) that trade
|
||||
resolution + bitrate for upload bandwidth, plus an `Auto` mode that
|
||||
derives quality from the bandwidth pre-flight
|
||||
|
||||
Not yet built (deferred, not blocking):
|
||||
- Per-monitor selection on a multi-monitor X11 host — `ximagesrc` grabs the
|
||||
whole root canvas; single-monitor cropping needs xrandr region coords
|
||||
- `use-damage=true` CPU optimization for the X11 capture path
|
||||
|
||||
## Quick start
|
||||
|
||||
### Interactive (recommended)
|
||||
|
||||
```sh
|
||||
pixelpass
|
||||
```
|
||||
|
||||
On the host machine: pick "Host", share a monitor via the portal dialog,
|
||||
the ticket lands on your clipboard. Send it to your viewer however you
|
||||
like (chat, email, paste in a note). The same ticket works for multiple
|
||||
viewers up to your `--max-viewers` cap.
|
||||
|
||||
The very first host launch offers a one-time upstream bandwidth test
|
||||
(~5 s, ~5 MB to Cloudflare's open speed-test endpoint) so it can pick
|
||||
a sensible default for the viewer cap. You can skip it and a
|
||||
conservative default (2 viewers) is used; re-run it later with
|
||||
`pixelpass --reconfigure`.
|
||||
|
||||
On the viewer machine: run `pixelpass`, pick "View", paste the ticket,
|
||||
pick mpv or VLC. The player launches detached and the stream starts.
|
||||
|
||||
### Headless
|
||||
|
||||
```sh
|
||||
# host: prints a ticket on stdout, waits for a peer
|
||||
pixelpass
|
||||
|
||||
# viewer: skips the menu
|
||||
pixelpass <ticket>
|
||||
# then run the printed mpv command in another terminal
|
||||
```
|
||||
|
||||
### Graphical (optional)
|
||||
|
||||
A small window front-end is available in builds compiled with the `gui`
|
||||
feature (see [Build](#build)):
|
||||
|
||||
```sh
|
||||
pixelpass --gui
|
||||
```
|
||||
|
||||
Host: pick quality / max-viewers / options, click **Start hosting**, and the
|
||||
share code appears with a copy button. Connected viewers are listed with a
|
||||
**Kick** button each, and a desktop notification fires as they join or leave.
|
||||
View: paste a code, pick mpv or VLC, click **Connect** and the player launches.
|
||||
|
||||
A system-tray icon shows current status. **Settings → "Keep running in the
|
||||
tray when I close the window"** (off by default) makes the close button hide
|
||||
the window — truly, by dropping it — while any active stream keeps running in
|
||||
the child; reopen it from the tray. (Plain close still quits when the option is
|
||||
off, or when no system tray is present.)
|
||||
|
||||
The window is a thin driver — it runs the same headless `pixelpass` as a
|
||||
child process and reads its event stream, so the GUI is purely additive and
|
||||
the capture machinery is untouched by it. On a build without the feature,
|
||||
`--gui` prints a hint to rebuild with it.
|
||||
|
||||
## Requirements
|
||||
|
||||
- Linux (Wayland or X11; the backend is autodetected)
|
||||
- A VAAPI-capable GPU and the right driver:
|
||||
- AMD: `libva-mesa-driver`
|
||||
- Intel: `intel-media-driver` (modern iGPUs) or `intel-vaapi-driver` (older)
|
||||
- NVIDIA: `libva-nvidia-driver` (untested)
|
||||
- `vainfo` from `libva-utils` should list at least one H.264 entrypoint
|
||||
- GStreamer with these plugin packages installed:
|
||||
- `gstreamer`, `gst-plugins-base`, `gst-plugins-good`, `gst-plugins-bad`,
|
||||
`gst-plugins-ugly`, `gst-libav`, `gst-plugin-va`, `gst-plugin-pipewire`
|
||||
- A player: `mpv` (recommended) or `vlc`
|
||||
- If you use VLC, two split plugin packages are also needed on Arch-family
|
||||
distros — the base `vlc` package does not pull them in:
|
||||
- `vlc-plugin-dvb` — provides the MPEG-TS demuxer (`libts_plugin.so`).
|
||||
Without it, VLC can't parse the container.
|
||||
- `vlc-plugin-ffmpeg` — provides the H.264 decoder
|
||||
(`libavcodec_plugin.so`). Without it, VLC parses the container,
|
||||
identifies the codec as H.264, then errors with
|
||||
`Codec h264 ... is not supported`.
|
||||
mpv ships its own decoder stack and doesn't share either dependency.
|
||||
- PipeWire (for screencast portal + audio capture)
|
||||
|
||||
On Arch / CachyOS / EndeavourOS:
|
||||
|
||||
```sh
|
||||
sudo pacman -S gstreamer gst-plugins-base gst-plugins-good gst-plugins-bad \
|
||||
gst-plugins-ugly gst-libav gst-plugin-va gst-plugin-pipewire \
|
||||
libva-utils mpv
|
||||
# plus your GPU's VAAPI driver
|
||||
# plus, if you want to use VLC instead of mpv:
|
||||
sudo pacman -S vlc vlc-plugin-dvb vlc-plugin-ffmpeg
|
||||
```
|
||||
|
||||
If the viewer is running on battery, set the CPU governor to performance
|
||||
or balanced — power-saver can choke even hardware-decoded 1080p H.264.
|
||||
|
||||
## Diagnostics
|
||||
|
||||
`pixelpass --doctor` prints a one-shot report of everything the above
|
||||
requirements cover and exits — run it on any machine before a real session:
|
||||
|
||||
```sh
|
||||
pixelpass --doctor
|
||||
```
|
||||
|
||||
It checks, and prints a `✓ / ! / ✗` line for each:
|
||||
|
||||
- **display server** — Wayland vs. X11 (autodetected), the raw session env
|
||||
vars, and the X server's vendor/version (so an xlibre server is visible)
|
||||
- **capture** — the GStreamer tools plus the source element for your backend
|
||||
(`pipewiresrc` on Wayland, `ximagesrc` on X11)
|
||||
- **encode** — whether hardware H.264 works (the `vah264enc` plugin, a DRM
|
||||
render node, and a VA-API H.264 *encode* entrypoint via `vainfo`), and
|
||||
whether the software `x264enc` fallback is available. This is the usual
|
||||
culprit when a viewer "can't connect": a GPU with no H.264 encode entrypoint
|
||||
produces no video under the default encoder — the report tells you to host
|
||||
with `--no-hwencode`
|
||||
- **mux / audio** — the TS mux + AAC + PulseAudio tail, and `pactl`
|
||||
- **viewer** — whether `mpv` or `vlc` is installed
|
||||
- **network** — binds a real endpoint and checks a relay is reachable
|
||||
|
||||
Each failing line includes a distro-aware install hint, and the closing summary
|
||||
says whether the machine can host and how. The exit code is non-zero if any
|
||||
hard requirement is missing, so it can gate a script or CI.
|
||||
|
||||
## Build
|
||||
|
||||
```sh
|
||||
cargo build --release
|
||||
./target/release/pixelpass --help
|
||||
```
|
||||
|
||||
`rustc` 1.95+ / edition 2024.
|
||||
|
||||
The optional graphical front-end (`pixelpass --gui`) is behind a default-off
|
||||
cargo feature so the headless build stays lean (it pulls the egui/eframe
|
||||
windowing stack). Build it with:
|
||||
|
||||
```sh
|
||||
cargo build --release --features gui
|
||||
```
|
||||
|
||||
## How it works
|
||||
|
||||
```
|
||||
Host Viewer
|
||||
──── ──────
|
||||
Wayland portal (ashpd) ──> PipeWire fd ─┐ (X11: ximagesrc, no portal)
|
||||
│
|
||||
▼
|
||||
gst-launch: <source> -> videorate -> vah264enc/x264enc ->
|
||||
h264parse -> mpegtsmux
|
||||
(audio: pulsesrc <sink>.monitor ->
|
||||
avenc_aac -> aacparse ─┘)
|
||||
│ stdout
|
||||
▼
|
||||
tokio HTTP server (in-process, ~30 lines)
|
||||
│
|
||||
▼
|
||||
iroh QUIC bi-stream (ALPN pixelpass/0) ◄══════════►
|
||||
│
|
||||
▼
|
||||
tokio TcpListener
|
||||
on 127.0.0.1:rand
|
||||
│
|
||||
▼
|
||||
mpv / VLC HTTP client
|
||||
```
|
||||
|
||||
The viewer's player connects to a localhost HTTP server, which is
|
||||
just one end of the iroh tunnel. The host's HTTP server sits on the
|
||||
other end and streams GStreamer's stdout (an MPEG-TS containing
|
||||
H.264 + AAC) through with no demux or remux.
|
||||
|
||||
iroh handles NAT traversal: direct UDP if hole-punching succeeds,
|
||||
relay path otherwise. Both have been verified end-to-end.
|
||||
|
||||
## Why these choices
|
||||
|
||||
- **iroh over Holesail / dumbpipe / Tailscale**: single Rust dep, no Node
|
||||
runtime, no signup, no daemon — fits the "one self-contained binary"
|
||||
goal.
|
||||
- **GStreamer for capture/encode, not ffmpeg**: stride/format pitfalls
|
||||
when bridging raw video between processes; one in-process pipeline
|
||||
sidesteps them.
|
||||
- **In-process Rust HTTP server, not ffmpeg-as-server**: ffmpeg's
|
||||
`-listen 1` is one-shot and probe-budget-sensitive; the Rust task is
|
||||
pure passthrough with no codec assumptions.
|
||||
- **MPEG-TS over fragmented MP4**: every player on Linux handles it
|
||||
out of the box. AV1-in-MPEG-TS was tried and is unworkable through
|
||||
libavformat — if AV1 ever comes back, it has to ride a different
|
||||
container.
|
||||
- **VAAPI H.264 over x264**: ~5% of one CPU core instead of ~50% on
|
||||
the host's hardware.
|
||||
|
||||
## Configuration
|
||||
|
||||
`pixelpass` keeps a small TOML config at `~/.config/pixelpass/config.toml`
|
||||
(or the XDG equivalent). Right now it only stores the result of the
|
||||
bandwidth pre-flight:
|
||||
|
||||
```toml
|
||||
[bandwidth]
|
||||
status = "measured" # measured | skipped | failed | unmeasured
|
||||
upstream_mbps = 8.78 # safe estimate (raw * 0.8)
|
||||
measured_at = "2026-05-21T20:41:16Z"
|
||||
```
|
||||
|
||||
- `pixelpass --reconfigure` re-runs the test (e.g. after an ISP change).
|
||||
- Deleting the file resets pixelpass to first-run state.
|
||||
- Skip is sticky — once you skip the test, pixelpass won't ask again
|
||||
unless you reconfigure.
|
||||
|
||||
## Relay
|
||||
|
||||
By default pixelpass uses iroh's bundled relay servers to coordinate the
|
||||
P2P connection (peers still hole-punch a direct UDP path when they can; the
|
||||
relay is the fallback and the rendezvous point). You can point it at a
|
||||
different relay — a self-hosted one, or n0's staging/production servers —
|
||||
with either:
|
||||
|
||||
```bash
|
||||
pixelpass --relay https://relay.example/ # host or viewer
|
||||
PIXELPASS_RELAY=https://relay.example/ pixelpass … # env-var form
|
||||
```
|
||||
|
||||
The flag applies to both host and viewer and takes precedence over the
|
||||
environment variable. The env-var form is handy for the `--gui` front-end,
|
||||
since the GUI's child host/viewer processes inherit it; the `--gui --relay`
|
||||
flag form is forwarded to them too. Both ends must use the same relay to
|
||||
find each other.
|
||||
|
||||
## Themes
|
||||
|
||||
The `--gui` front-end ships three colour themes — **Default Dark**,
|
||||
**Catppuccin Mocha**, and **Catppuccin Latte** — and you can add your own.
|
||||
Pick one under **Settings → Appearance**; the choice is remembered.
|
||||
|
||||
A theme is a small TOML file of named colours:
|
||||
|
||||
```toml
|
||||
name = "My Theme"
|
||||
dark = true # base egui defaults to start from (dark or light)
|
||||
|
||||
window_bg = "#1b1b1f" # window background
|
||||
panel_bg = "#242429" # panels / frames
|
||||
input_bg = "#141417" # text fields, the ticket box
|
||||
text = "#e6e6ea" # primary text
|
||||
weak_text = "#a0a0a8" # hints, secondary text
|
||||
accent = "#5aa0f2" # selection, links, the active control
|
||||
button_bg = "#33333a" # buttons at rest
|
||||
button_hovered = "#44444d"
|
||||
streaming = "#6fdc8c" # "● Streaming"
|
||||
waiting = "#f2c14e" # "● Waiting for viewers…"
|
||||
success = "#6fdc8c" # "✓ Copied", valid-code confirmation
|
||||
warning = "#f0a85a" # non-fatal warnings
|
||||
error = "#f2756f" # errors
|
||||
```
|
||||
|
||||
Colours are `#rrggbb` hex strings. Any field you leave out falls back to
|
||||
Default Dark, so partial files are fine.
|
||||
|
||||
Two ways to make one:
|
||||
|
||||
- **In the app:** Settings → Appearance → *Edit / create a theme* gives you a
|
||||
colour picker per field with a live preview, and **Save** writes a `.toml`.
|
||||
- **By hand:** drop a `.toml` into `~/.config/pixelpass/themes/` (the XDG
|
||||
config dir). It appears in the picker next time you open Settings.
|
||||
|
||||
Sharing a theme is just sending someone the file. A user theme whose `name`
|
||||
matches a built-in overrides that built-in.
|
||||
|
||||
## Audio
|
||||
|
||||
By default pixelpass captures the default sink's monitor — the viewer
|
||||
hears whatever the host hears. `--app <name>` narrows that to a single
|
||||
application: pixelpass creates a per-PID null-sink and uses libpipewire to
|
||||
reroute matching `Stream/Output/Audio` nodes (by `application.name`) into
|
||||
it, so the viewer hears just that app instead of the whole desktop. In the
|
||||
interactive menu you can pick the app from a list of what's currently
|
||||
playing.
|
||||
|
||||
Microphone capture is intentionally out of scope — pixelpass is a
|
||||
screen-share tool meant to be paired with a dedicated voice app (Mumble,
|
||||
TeamSpeak, Discord, …) for two-way talk.
|
||||
|
||||
If a host crashes mid-session it can leave orphaned `pixelpass_capture_*`
|
||||
null-sinks and their paired loopbacks loaded in PipeWire. Run
|
||||
`pixelpass --repair` to unload them and exit.
|
||||
|
||||
## Display server
|
||||
|
||||
The capture backend is autodetected from the environment
|
||||
(`WAYLAND_DISPLAY` → Wayland, else `DISPLAY` → X11, else
|
||||
`XDG_SESSION_TYPE`). Override it with `--display-server wayland|x11` — for
|
||||
example to force the X11 path while running inside a Wayland session (an
|
||||
Xwayland or Xephyr `DISPLAY`).
|
||||
|
||||
- **Wayland** goes through the screencast portal: a "Share Screen?" dialog
|
||||
appears when the first viewer connects, and you pick the monitor (or
|
||||
window, with `--window`) there.
|
||||
- **X11** uses `ximagesrc` and starts silently when the first viewer
|
||||
connects — the ticket is the access control, there's no portal gate.
|
||||
`--window` runs an `xwininfo` picker (click the window you want to
|
||||
share); without it the whole root window is captured.
|
||||
|
||||
Encoding is hardware VAAPI (`vah264enc`) by default. `--no-hwencode`
|
||||
switches to software x264 (`x264enc tune=zerolatency`) for hosts without a
|
||||
working VAAPI H.264 entrypoint — higher CPU, no GPU needed. This applies
|
||||
to both backends.
|
||||
|
||||
## Multi-viewer
|
||||
|
||||
One gst capture pipeline fans out to N concurrent viewers via a
|
||||
`tokio::sync::broadcast` channel. The same ticket is reusable: as long
|
||||
as a viewer is connected, capture stays alive; when the last one
|
||||
leaves, the pipeline tears down and the portal stops streaming. A new
|
||||
viewer connecting after that re-triggers the portal dialog.
|
||||
|
||||
Capacity is bounded by upstream bandwidth (each viewer is its own
|
||||
encrypted egress). The default cap comes from the bandwidth pre-flight
|
||||
result; `--max-viewers <N>` overrides it. When the cap is hit,
|
||||
additional connections are politely refused with a "host is full"
|
||||
message and the host keeps running.
|
||||
|
||||
For more viewers, drop the per-viewer bitrate: e.g. `pixelpass
|
||||
--bitrate 2500 --max-viewers 4` fits four 2.5 Mbps streams in roughly
|
||||
12 Mbps of upstream. The `--quality` presets below are the friendlier
|
||||
way to do the same thing.
|
||||
|
||||
## Quality
|
||||
|
||||
`--quality <preset>` bundles a max video height, bitrate, and framerate —
|
||||
resolution is a quality-per-bitrate knob, so the three only make sense
|
||||
together. Quality is **host-global**: one encode pipeline fans out to every
|
||||
viewer, so the sharer picks one quality for everyone (per-viewer quality
|
||||
would need per-viewer encodes, which kills the fanout).
|
||||
|
||||
| Preset | Max height | Bitrate | fps |
|
||||
|----------|-------------------|-----------|-----|
|
||||
| `source` | native (no scale) | 6000 kbps | 30 |
|
||||
| `high` | 1080p | 4000 kbps | 30 |
|
||||
| `medium` | 720p | 2500 kbps | 30 |
|
||||
| `low` | 480p | 1000 kbps | 30 |
|
||||
| `auto` | derived (below) | derived | 30 |
|
||||
|
||||
`auto` (the default) picks the highest preset whose bitrate fits your
|
||||
measured safe upstream divided by the viewer cap — so quality is sized for
|
||||
the worst case, since it's baked in when capture starts and can't drop when
|
||||
a second viewer joins. With no `--max-viewers`, it sizes for a single
|
||||
viewer. If there's no bandwidth measurement yet, `auto` falls back to
|
||||
`medium` (run `pixelpass --reconfigure` to measure). In the interactive
|
||||
menu, omitting `--quality` shows a picker instead of assuming `auto`.
|
||||
|
||||
Downscaling preserves the source aspect ratio with square pixels and snaps
|
||||
to even dimensions (H.264 requires them). Power users can override
|
||||
individual fields: `--max-height N`, `--bitrate N`, and `--framerate N`
|
||||
each take precedence over the chosen preset's value for that field.
|
||||
|
||||
## Known limitations and gotchas
|
||||
|
||||
- **VLC needs `vlc-plugin-dvb` and `vlc-plugin-ffmpeg`** on Arch-family
|
||||
distros — the base `vlc` package doesn't pull these in, and missing
|
||||
either one breaks playback (the first kills the demuxer, the second
|
||||
kills the H.264 decoder). pixelpass warns at player-launch time if
|
||||
either plugin isn't on disk. mpv doesn't share these dependencies.
|
||||
- **Audio echo** if the host plays the stream through speakers and
|
||||
captures system audio — expected, the mic / monitor picks up the
|
||||
playback. Headphones bypass it.
|
||||
- **Late joiners see ~2 s of garbage** before the next keyframe lets
|
||||
their decoder lock. Expected behavior, not a bug.
|
||||
- **VAAPI driver must be package-tracked**, not an orphaned `.so` on
|
||||
disk. mpv's `--hwdec=auto` silently falls back to software decode
|
||||
otherwise, which then chokes on a low-power viewer.
|
||||
|
||||
## License
|
||||
|
||||
MIT OR Apache-2.0, your pick.
|
||||
@@ -0,0 +1,93 @@
|
||||
Copyright 2022 The Noto Project Authors (https://github.com/notofonts/latin-greek-cyrillic)
|
||||
|
||||
This Font Software is licensed under the SIL Open Font License, Version 1.1.
|
||||
This license is copied below, and is also available with a FAQ at:
|
||||
https://scripts.sil.org/OFL
|
||||
|
||||
|
||||
-----------------------------------------------------------
|
||||
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
|
||||
-----------------------------------------------------------
|
||||
|
||||
PREAMBLE
|
||||
The goals of the Open Font License (OFL) are to stimulate worldwide
|
||||
development of collaborative font projects, to support the font creation
|
||||
efforts of academic and linguistic communities, and to provide a free and
|
||||
open framework in which fonts may be shared and improved in partnership
|
||||
with others.
|
||||
|
||||
The OFL allows the licensed fonts to be used, studied, modified and
|
||||
redistributed freely as long as they are not sold by themselves. The
|
||||
fonts, including any derivative works, can be bundled, embedded,
|
||||
redistributed and/or sold with any software provided that any reserved
|
||||
names are not used by derivative works. The fonts and derivatives,
|
||||
however, cannot be released under any other type of license. The
|
||||
requirement for fonts to remain under this license does not apply
|
||||
to any document created using the fonts or their derivatives.
|
||||
|
||||
DEFINITIONS
|
||||
"Font Software" refers to the set of files released by the Copyright
|
||||
Holder(s) under this license and clearly marked as such. This may
|
||||
include source files, build scripts and documentation.
|
||||
|
||||
"Reserved Font Name" refers to any names specified as such after the
|
||||
copyright statement(s).
|
||||
|
||||
"Original Version" refers to the collection of Font Software components as
|
||||
distributed by the Copyright Holder(s).
|
||||
|
||||
"Modified Version" refers to any derivative made by adding to, deleting,
|
||||
or substituting -- in part or in whole -- any of the components of the
|
||||
Original Version, by changing formats or by porting the Font Software to a
|
||||
new environment.
|
||||
|
||||
"Author" refers to any designer, engineer, programmer, technical
|
||||
writer or other person who contributed to the Font Software.
|
||||
|
||||
PERMISSION & CONDITIONS
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of the Font Software, to use, study, copy, merge, embed, modify,
|
||||
redistribute, and sell modified and unmodified copies of the Font
|
||||
Software, subject to the following conditions:
|
||||
|
||||
1) Neither the Font Software nor any of its individual components,
|
||||
in Original or Modified Versions, may be sold by itself.
|
||||
|
||||
2) Original or Modified Versions of the Font Software may be bundled,
|
||||
redistributed and/or sold with any software, provided that each copy
|
||||
contains the above copyright notice and this license. These can be
|
||||
included either as stand-alone text files, human-readable headers or
|
||||
in the appropriate machine-readable metadata fields within text or
|
||||
binary files as long as those fields can be easily viewed by the user.
|
||||
|
||||
3) No Modified Version of the Font Software may use the Reserved Font
|
||||
Name(s) unless explicit written permission is granted by the corresponding
|
||||
Copyright Holder. This restriction only applies to the primary font name as
|
||||
presented to the users.
|
||||
|
||||
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
|
||||
Software shall not be used to promote, endorse or advertise any
|
||||
Modified Version, except to acknowledge the contribution(s) of the
|
||||
Copyright Holder(s) and the Author(s) or with their explicit written
|
||||
permission.
|
||||
|
||||
5) The Font Software, modified or unmodified, in part or in whole,
|
||||
must be distributed entirely under this license, and must not be
|
||||
distributed under any other license. The requirement for fonts to
|
||||
remain under this license does not apply to any document created
|
||||
using the Font Software.
|
||||
|
||||
TERMINATION
|
||||
This license becomes null and void if any of the above conditions are
|
||||
not met.
|
||||
|
||||
DISCLAIMER
|
||||
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
|
||||
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
|
||||
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
|
||||
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
|
||||
OTHER DEALINGS IN THE FONT SOFTWARE.
|
||||
Binary file not shown.
Binary file not shown.
|
After Width: | Height: | Size: 7.9 KiB |
@@ -0,0 +1,12 @@
|
||||
[Desktop Entry]
|
||||
Type=Application
|
||||
Name=pixelpass
|
||||
GenericName=Screen Sharing
|
||||
Comment=P2P screen sharing over iroh — no port forwarding, no signup
|
||||
Exec=pixelpass --gui
|
||||
Icon=pixelpass
|
||||
StartupWMClass=pixelpass
|
||||
Terminal=false
|
||||
Categories=Network;RemoteAccess;
|
||||
Keywords=screen;share;sharing;remote;p2p;iroh;cast;
|
||||
StartupNotify=true
|
||||
@@ -0,0 +1,16 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="256" height="256" viewBox="0 0 256 256">
|
||||
<title>pixelpass</title>
|
||||
<defs>
|
||||
<linearGradient id="bg" x1="0" y1="0" x2="256" y2="256" gradientUnits="userSpaceOnUse">
|
||||
<stop offset="0" stop-color="#4338ca"/>
|
||||
<stop offset="1" stop-color="#7c3aed"/>
|
||||
</linearGradient>
|
||||
</defs>
|
||||
<rect x="8" y="8" width="240" height="240" rx="56" fill="url(#bg)"/>
|
||||
<!-- pixel stream: squares fading cyan -> white, "passed" toward the arrow -->
|
||||
<rect x="50.25" y="181.29" width="16" height="16" rx="3.2" fill="#2dd5ef"/>
|
||||
<rect x="67" y="124.44" width="20" height="20" rx="4" fill="#62dff2"/>
|
||||
<rect x="96.25" y="82.09" width="24" height="24" rx="4.8" fill="#98e8f6"/>
|
||||
<rect x="134.04" y="55.77" width="28" height="28" rx="5.6" fill="#c9f1f9"/>
|
||||
<path d="M 225.5 57.5 L 183.1 85.8 L 176.9 42.2 Z" fill="#f8fafc"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 875 B |
@@ -0,0 +1,3 @@
|
||||
.tools/
|
||||
AppDir/
|
||||
*.AppImage
|
||||
Executable
+20
@@ -0,0 +1,20 @@
|
||||
#!/bin/sh
|
||||
# AppRun for the PixelPass AppImage.
|
||||
#
|
||||
# PixelPass is an orchestrator: it shells out to gst-launch-1.0, pactl, and a
|
||||
# player (mpv/vlc) found on the host PATH. We prepend our own usr/bin so any
|
||||
# bundled helpers win, but the host's tools remain reachable — that's why this
|
||||
# app suits AppImage (no sandbox) better than a Flatpak.
|
||||
HERE="$(dirname "$(readlink -f "$0")")"
|
||||
export PATH="$HERE/usr/bin:$PATH"
|
||||
|
||||
BIN="$HERE/usr/bin/pixelpass"
|
||||
|
||||
# With no arguments and no controlling terminal — i.e. launched from a file
|
||||
# manager or the .desktop entry — open the GUI. From a terminal, or with any
|
||||
# argument (a ticket, --host, --gui, --repair, …), pass through so the CLI and
|
||||
# the interactive menu both work.
|
||||
if [ "$#" -eq 0 ] && [ ! -t 0 ]; then
|
||||
exec "$BIN" --gui
|
||||
fi
|
||||
exec "$BIN" "$@"
|
||||
@@ -0,0 +1,72 @@
|
||||
# PixelPass AppImage
|
||||
|
||||
A "thin" AppImage: the gui-enabled `pixelpass` binary, a launcher (`AppRun`),
|
||||
and the desktop entry + icon. Run `./build-appimage.sh` to produce
|
||||
`pixelpass-<version>-x86_64.AppImage`.
|
||||
|
||||
## Why thin
|
||||
|
||||
`pixelpass` is an orchestrator — it links almost nothing (only `libpipewire`,
|
||||
which is excludelisted because it must match the host daemon) and instead
|
||||
**shells out** to `gst-launch-1.0`, `pactl`, and a player (`mpv`/`vlc`) found on
|
||||
the host `PATH`. The GUI's graphics libraries (`libGL`, `libwayland-*`,
|
||||
`libxkbcommon`, X11) are dlopen'd at runtime and are likewise on the AppImage
|
||||
excludelist — every desktop already has a matching set. So there is nothing
|
||||
useful to bundle, and bundling the graphics stack would only risk driver
|
||||
mismatches. The AppImage therefore carries just the binary.
|
||||
|
||||
This also explains why PixelPass suits AppImage better than Flatpak: the
|
||||
no-sandbox model lets the bundled binary freely spawn the host's `gst-launch`,
|
||||
`pactl`, and player, which a Flatpak sandbox would block.
|
||||
|
||||
## Host requirements
|
||||
|
||||
The AppImage runs on any reasonably current glibc-based distro that has:
|
||||
|
||||
- **GStreamer + plugins** — `gst-launch-1.0`/`gst-inspect-1.0` plus base,
|
||||
good/bad/ugly, libav, and the PipeWire plugin (the binary tells you the exact
|
||||
package names for your distro if something is missing).
|
||||
- **PipeWire** (with the PulseAudio shim, for `pactl`).
|
||||
- **A player** — `mpv` (preferred) or `vlc` — for the viewer side.
|
||||
- For X11 single-window capture: `xwininfo`.
|
||||
|
||||
These are the same dependencies the Arch package lists; the AppImage just spares
|
||||
you the Rust toolchain.
|
||||
|
||||
## Building for broad compatibility (lower glibc baseline)
|
||||
|
||||
An AppImage requires a host glibc **at least as new** as the build host's. Built
|
||||
straight on a rolling distro (e.g. CachyOS, glibc 2.43) the AppImage only runs
|
||||
on equally-new systems. Build inside an older base for wider reach. The script
|
||||
honours `CARGO_TARGET_DIR`, so an isolated toolchain won't clobber your host's
|
||||
`target/`:
|
||||
|
||||
```sh
|
||||
# One-time: an Ubuntu 24.04 distrobox (docker or podman backend).
|
||||
distrobox create --yes --image ubuntu:24.04 --name pixelpass-build
|
||||
distrobox enter pixelpass-build -- sudo apt-get update
|
||||
distrobox enter pixelpass-build -- sudo apt-get install -y \
|
||||
build-essential cmake clang libclang-dev pkg-config \
|
||||
libpipewire-0.3-dev libspa-0.2-dev curl ca-certificates file
|
||||
# Install rustup inside the box (edition 2024 needs rustc >= 1.85), then:
|
||||
distrobox enter pixelpass-build -- env \
|
||||
CARGO_TARGET_DIR=~/.cache/pixelpass-ubuntu/target \
|
||||
./packaging/appimage/build-appimage.sh
|
||||
```
|
||||
|
||||
**Why Ubuntu 24.04 and not something older:** PixelPass's `pipewire` crate
|
||||
binds the system's PipeWire headers via bindgen, and anything older than ~PW 1.0
|
||||
(e.g. Ubuntu 22.04's 0.3.48) fails to compile (missing struct fields / wrong
|
||||
types). And since PixelPass *is* a PipeWire/portal/Wayland app, it can only run
|
||||
on distros new enough to have modern PipeWire anyway — so an ancient glibc base
|
||||
buys nothing. 24.04 (glibc 2.39, PW 1.0.5) is the sweet spot.
|
||||
|
||||
The 24.04-built binary's baseline is **glibc 2.39** — and the only 2.39 symbols
|
||||
are two *weak* `pidfd_*` references from Rust std's process spawning (everything
|
||||
else is ≤ 2.35). That covers Ubuntu 24.04+, Debian 13+, Fedora 40+, and current
|
||||
rolling distros.
|
||||
|
||||
## Caveats
|
||||
|
||||
- **Hardware encode (VAAPI `vah264enc`)** uses the host GPU driver; it can't be
|
||||
bundled. The software path (`--no-hwencode`, x264) always works.
|
||||
Executable
+59
@@ -0,0 +1,59 @@
|
||||
#!/usr/bin/env bash
|
||||
# Build a "thin" PixelPass AppImage: the gui-enabled release binary plus only
|
||||
# its non-excludelisted shared libraries. The graphics stack (libGL, wayland,
|
||||
# xkbcommon, X11) is intentionally left to the host — those libs are on the
|
||||
# AppImage excludelist because they must match the host driver — and the
|
||||
# runtime tools PixelPass shells out to (gst-launch-1.0, pactl, mpv/vlc) are
|
||||
# expected on the host PATH, the same contract the Arch package documents.
|
||||
#
|
||||
# Usage: packaging/appimage/build-appimage.sh
|
||||
# Output: packaging/appimage/pixelpass-x86_64.AppImage
|
||||
set -euo pipefail
|
||||
|
||||
here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
repo="$(cd "$here/../.." && pwd)"
|
||||
tools="$here/.tools"
|
||||
appdir="$here/AppDir"
|
||||
mkdir -p "$tools"
|
||||
|
||||
# linuxdeploy is itself an AppImage; run it without FUSE so this works on hosts
|
||||
# (and CI) that lack libfuse2.
|
||||
export APPIMAGE_EXTRACT_AND_RUN=1
|
||||
# Embed the version from Cargo.toml into the AppImage filename metadata.
|
||||
VERSION="$(grep -m1 '^version' "$repo/Cargo.toml" | sed -E 's/.*"(.*)".*/\1/')"
|
||||
export VERSION
|
||||
|
||||
echo ">> building release binary (--features gui)"
|
||||
( cd "$repo" && cargo build --release --features gui )
|
||||
# Honour CARGO_TARGET_DIR so an isolated build (e.g. inside an old-glibc
|
||||
# distrobox) doesn't have to clobber the host's target/.
|
||||
bin="${CARGO_TARGET_DIR:-$repo/target}/release/pixelpass"
|
||||
|
||||
echo ">> fetching linuxdeploy"
|
||||
ld="$tools/linuxdeploy-x86_64.AppImage"
|
||||
if [ ! -x "$ld" ]; then
|
||||
curl -fL --retry 3 -o "$ld" \
|
||||
"https://github.com/linuxdeploy/linuxdeploy/releases/download/continuous/linuxdeploy-x86_64.AppImage"
|
||||
chmod +x "$ld"
|
||||
fi
|
||||
|
||||
echo ">> assembling AppDir"
|
||||
rm -rf "$appdir"
|
||||
mkdir -p "$appdir/usr/bin"
|
||||
install -m755 "$bin" "$appdir/usr/bin/pixelpass"
|
||||
|
||||
echo ">> running linuxdeploy (bundles libs, builds the AppImage)"
|
||||
# -e: analyse this binary for libraries to bundle (only libpipewire et al. that
|
||||
# aren't excludelisted will be copied; glibc + graphics libs are skipped).
|
||||
# -d/-i: desktop entry + icon for desktop integration.
|
||||
# --custom-apprun: our launcher that opens --gui from a file manager.
|
||||
( cd "$here" && OUTPUT="pixelpass-${VERSION}-x86_64.AppImage" "$ld" \
|
||||
--appdir "$appdir" \
|
||||
-e "$bin" \
|
||||
-d "$repo/assets/pixelpass.desktop" \
|
||||
-i "$repo/assets/pixelpass-256.png" \
|
||||
--icon-filename pixelpass \
|
||||
--custom-apprun "$here/AppRun" \
|
||||
--output appimage )
|
||||
|
||||
echo ">> done: $here/pixelpass-${VERSION}-x86_64.AppImage"
|
||||
@@ -0,0 +1,6 @@
|
||||
# makepkg build artifacts
|
||||
src/
|
||||
pkg/
|
||||
/pixelpass/
|
||||
*.pkg.tar.*
|
||||
*.log
|
||||
@@ -0,0 +1,65 @@
|
||||
# Maintainer: mollusk <jitty+lc1iz0dc@protonmail.com>
|
||||
#
|
||||
# Versioned package, built from the public gitbutter repo on `main`.
|
||||
# For a tagged release, switch the source fragment to `#tag=v0.1.0`.
|
||||
|
||||
pkgname=pixelpass
|
||||
pkgver=0.1.0
|
||||
pkgrel=1
|
||||
pkgdesc='P2P screen sharing over iroh — no port forwarding, no signup'
|
||||
arch=('x86_64')
|
||||
url='https://gitbutter.xyz/mollusk/pixelpass'
|
||||
license=('MIT' 'Apache-2.0' 'OFL-1.1')
|
||||
depends=(
|
||||
'gstreamer' # gst-launch-1.0 / gst-inspect-1.0
|
||||
'gst-plugins-base' # videoscale (quality-preset downscale)
|
||||
'gst-plugins-good' # ximagesrc (X11 capture) + pulsesrc
|
||||
'gst-plugins-bad' # h264parse, mpegtsmux, aacparse
|
||||
'gst-libav' # avenc_aac (audio encode)
|
||||
'gst-plugin-va' # vah264enc (default hardware H.264 encoder)
|
||||
'libpulse' # pactl (audio routing / device control)
|
||||
'hicolor-icon-theme' # owns the scalable icon dir
|
||||
'libglvnd' # libGL for the egui (glow) GUI
|
||||
'libxkbcommon' # GUI keyboard handling (winit)
|
||||
'wayland' # GUI Wayland backend libs
|
||||
)
|
||||
optdepends=(
|
||||
'mpv: recommended stream viewer (the GUI launches mpv)'
|
||||
'vlc: alternative stream viewer'
|
||||
'gst-plugins-ugly: software x264 encoding for `pixelpass --no-hwencode`'
|
||||
'gst-plugin-pipewire: screen capture on Wayland sessions'
|
||||
'xorg-xwininfo: share a single window on X11 (`pixelpass --window`)'
|
||||
)
|
||||
makedepends=('cargo' 'git')
|
||||
options=('!lto')
|
||||
_branch='main'
|
||||
source=("$pkgname::git+https://gitbutter.xyz/mollusk/pixelpass.git#branch=$_branch")
|
||||
sha256sums=('SKIP')
|
||||
|
||||
prepare() {
|
||||
cd "$srcdir/$pkgname"
|
||||
export RUSTUP_TOOLCHAIN=stable
|
||||
cargo fetch --locked --target "$(rustc -vV | sed -n 's/host: //p')"
|
||||
}
|
||||
|
||||
build() {
|
||||
cd "$srcdir/$pkgname"
|
||||
export RUSTUP_TOOLCHAIN=stable
|
||||
export CARGO_TARGET_DIR=target
|
||||
# --features gui so the .desktop launcher (pixelpass --gui) works.
|
||||
cargo build --frozen --release --features gui
|
||||
}
|
||||
|
||||
package() {
|
||||
cd "$srcdir/$pkgname"
|
||||
install -Dm0755 "target/release/$pkgname" "$pkgdir/usr/bin/$pkgname"
|
||||
install -Dm0644 assets/pixelpass.desktop \
|
||||
"$pkgdir/usr/share/applications/$pkgname.desktop"
|
||||
install -Dm0644 assets/pixelpass.svg \
|
||||
"$pkgdir/usr/share/icons/hicolor/scalable/apps/$pkgname.svg"
|
||||
install -Dm0644 README.md "$pkgdir/usr/share/doc/$pkgname/README.md"
|
||||
install -Dm0644 LICENSE-MIT "$pkgdir/usr/share/licenses/$pkgname/LICENSE-MIT"
|
||||
install -Dm0644 LICENSE-APACHE "$pkgdir/usr/share/licenses/$pkgname/LICENSE-APACHE"
|
||||
install -Dm0644 assets/NotoSans-OFL.txt \
|
||||
"$pkgdir/usr/share/licenses/$pkgname/NotoSans-OFL.txt"
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
# Debian / Ubuntu `.deb` build
|
||||
|
||||
This documents how the `pixelpass_*.deb` is produced. The deb **recipe itself**
|
||||
lives in-repo as the `[package.metadata.deb]` block in `Cargo.toml` (cargo-deb's
|
||||
equivalent of a PKGBUILD); this file documents only the build environment.
|
||||
|
||||
pixelpass is the screen-share companion to peerspeak and is built the same way
|
||||
in the same box. See peerspeak's `packaging/debian/README.md` for the full
|
||||
rationale behind each step — this is the short version.
|
||||
|
||||
## TL;DR
|
||||
|
||||
```sh
|
||||
distrobox enter peerspeak-bookworm -- bash -lc '
|
||||
source ~/.cargo/env
|
||||
cd ~/git/butter/pixelpass
|
||||
export CARGO_TARGET_DIR=~/.cache/cargo-deb-targets/pixelpass # MANDATORY
|
||||
cargo deb
|
||||
'
|
||||
# output: $CARGO_TARGET_DIR/debian/pixelpass_<version>-1_amd64.deb
|
||||
```
|
||||
|
||||
## Build environment
|
||||
|
||||
- **Base: the same Debian 12 (bookworm) distrobox `peerspeak-bookworm`**
|
||||
(glibc 2.36) used for peerspeak. **Never build on the Arch host** (newer glibc
|
||||
+ shared `$HOME`/`target/` would link Arch C objects into the binary).
|
||||
- **Use a box-local, pixelpass-specific `CARGO_TARGET_DIR`** (distinct from
|
||||
peerspeak's) so the two never share an artifact cache:
|
||||
`export CARGO_TARGET_DIR=~/.cache/cargo-deb-targets/pixelpass`.
|
||||
- Toolchain provisioning (rustup stable + `cargo-deb` + `build-essential`
|
||||
`pkg-config`) is identical to peerspeak's README. pixelpass itself links few
|
||||
C libraries — the heavy GStreamer stack it uses is invoked as subprocesses,
|
||||
not linked (see below), so it adds no extra `*-dev` build-deps beyond the base.
|
||||
|
||||
## Why `Depends` lists the whole GStreamer stack explicitly
|
||||
|
||||
pixelpass does its screen capture by shelling out to the GStreamer CLI
|
||||
(`gst-launch-1.0` / `gst-inspect-1.0`) and to `pactl`, **not** by linking the
|
||||
GStreamer libraries. That means `dpkg-shlibdeps` (which only sees linked `.so`
|
||||
files) cannot detect them, so `$auto` alone would ship a `.deb` whose `Depends`
|
||||
omits the entire capture stack. A fresh Ubuntu host would then fail at
|
||||
pixelpass's own `deps::check_host_binaries` startup probe — *before* it ever
|
||||
prints a connection ticket, which is exactly the field bug that motivated this.
|
||||
|
||||
So the `Cargo.toml` `depends` hard-codes the runtime stack on top of `$auto`:
|
||||
|
||||
```
|
||||
$auto, gstreamer1.0-tools, gstreamer1.0-plugins-base,
|
||||
gstreamer1.0-plugins-good, gstreamer1.0-plugins-bad,
|
||||
gstreamer1.0-plugins-ugly, gstreamer1.0-libav, gstreamer1.0-pipewire,
|
||||
gstreamer1.0-pulseaudio, pulseaudio-utils, x11-utils
|
||||
```
|
||||
|
||||
This covers both capture backends (`pipewiresrc` on Wayland, `ximagesrc` on X11
|
||||
from plugins-good), the VAAPI + software H.264 encoders, the AAC/TS mux tail,
|
||||
the PulseAudio source, and the `pactl`/`xdpyinfo` helpers.
|
||||
|
||||
## glibc floor
|
||||
|
||||
Same as peerspeak: built against glibc 2.36 → runs on Debian 12+ / Ubuntu
|
||||
24.04+. (pixelpass's own linked-library floor is lower, ~2.39-era, but it is
|
||||
always shipped alongside peerspeak, whose 2.36 floor governs the pair.)
|
||||
@@ -51,3 +51,39 @@ else
|
||||
echo "$MPV_LOG" | tail -30 | sed 's/^/ /'
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# ── quality-preset downscale check ────────────────────────────────────────
|
||||
# Mirrors the videoscale step host/pipeline.rs inserts for a non-Source preset:
|
||||
# AFTER videoconvert (scaling system-memory NV12, not the raw source format) and
|
||||
# pinned to an exact even WxH computed from the source size. A 16:9 source @
|
||||
# 480p wants width 853.3 -> 852 even. Asserts the negotiated size matches and
|
||||
# the encoder accepts it. Guards both the "even-width caveat" and the
|
||||
# negotiation/placement regression that squashed the picture.
|
||||
SCALED="${TMPDIR:-/tmp}/pixelpass-smoke-scaled-$$.ts"
|
||||
trap 'rm -f "$OUT" "$SCALED"' EXIT
|
||||
echo "[smoke] downscale check: 1920x1080 -> 852x480 (videoscale after videoconvert)"
|
||||
gst-launch-1.0 -q \
|
||||
mpegtsmux name=mux ! queue ! filesink location="$SCALED" \
|
||||
videotestsrc num-buffers=30 is-live=false \
|
||||
! video/x-raw,width=1920,height=1080,framerate=30/1 \
|
||||
! videorate ! video/x-raw,framerate=30/1 \
|
||||
! queue ! videoconvert ! video/x-raw,format=NV12 \
|
||||
! videoscale ! video/x-raw,format=NV12,width=852,height=480 \
|
||||
! vah264enc rate-control=cbr bitrate=1000 key-int-max=60 \
|
||||
! h264parse config-interval=-1 \
|
||||
! video/x-h264,stream-format=byte-stream,alignment=au ! mux. \
|
||||
audiotestsrc num-buffers=47 is-live=false \
|
||||
! audioconvert ! audioresample ! audio/x-raw,rate=48000,channels=2 \
|
||||
! avenc_aac bitrate=128000 ! aacparse ! mux.
|
||||
|
||||
SCALED_DIMS=$(ffprobe -v error -select_streams v:0 -show_entries stream=width,height \
|
||||
-of csv=p=0 "$SCALED" | head -1)
|
||||
SCALED_W=${SCALED_DIMS%,*}
|
||||
SCALED_H=${SCALED_DIMS#*,}
|
||||
echo " negotiated ${SCALED_W}x${SCALED_H}"
|
||||
if [[ "$SCALED_H" == "480" && $((SCALED_W % 2)) -eq 0 && "$SCALED_W" -lt 1920 ]]; then
|
||||
echo "[smoke] PASS — downscale produced an even width below source (proportional)"
|
||||
else
|
||||
echo "[smoke] FAIL: expected even width < 1920 at height 480, got ${SCALED_W}x${SCALED_H}"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
+124
-18
@@ -4,7 +4,7 @@ use clap::{Parser, ValueEnum};
|
||||
#[command(
|
||||
name = "pixelpass",
|
||||
version,
|
||||
about = "P2P screen sharing over iroh + ffmpeg",
|
||||
about = "P2P screen sharing over iroh",
|
||||
long_about = "Run with no arguments for an interactive Host/View menu. \
|
||||
Pass a ticket positionally to skip the menu and view headlessly."
|
||||
)]
|
||||
@@ -13,6 +13,12 @@ pub struct Cli {
|
||||
pub ticket: Option<String>,
|
||||
|
||||
// ── host options ──────────────────────────────────────────────────
|
||||
/// Run as host without the interactive menu. Equivalent to picking
|
||||
/// "Host" in the menu, but headless — for scripting and the --gui
|
||||
/// front-end, which drives this binary as a child process.
|
||||
#[arg(long)]
|
||||
pub host: bool,
|
||||
|
||||
/// Pick a single window instead of the whole screen.
|
||||
#[arg(long)]
|
||||
pub window: bool,
|
||||
@@ -21,29 +27,51 @@ pub struct Cli {
|
||||
#[arg(long, value_name = "NAME")]
|
||||
pub app: Option<String>,
|
||||
|
||||
/// Mix in the default microphone source.
|
||||
/// With `--app`, never fall back to whole-desktop audio. By default an
|
||||
/// app-filtered host mirrors the default sink's monitor until (and again
|
||||
/// after) the chosen app's streams route, so the viewer isn't left in
|
||||
/// silence. That fallback also captures everything else playing — including
|
||||
/// a voice call the sharer is in — so a caller can hear themselves echoed.
|
||||
/// `--strict-audio` suppresses the fallback entirely: the viewer hears only
|
||||
/// the chosen app, and silence when it isn't producing audio. Ignored
|
||||
/// without `--app`.
|
||||
#[arg(long)]
|
||||
pub mic: bool,
|
||||
pub strict_audio: bool,
|
||||
|
||||
/// Override display server autodetection.
|
||||
#[arg(long, value_enum)]
|
||||
pub display_server: Option<DisplayServerArg>,
|
||||
|
||||
/// Encode bitrate in kbps.
|
||||
#[arg(long, default_value_t = 6000)]
|
||||
pub bitrate: u32,
|
||||
/// Quality preset. Bundles a max video height, bitrate, and framerate.
|
||||
/// `auto` derives them from the saved bandwidth pre-flight (falls back to
|
||||
/// `medium` when no measurement exists). Defaults to `auto`; in the
|
||||
/// interactive menu, omitting this shows a picker instead.
|
||||
#[arg(long, value_enum)]
|
||||
pub quality: Option<Quality>,
|
||||
|
||||
/// Capture framerate.
|
||||
#[arg(long, default_value_t = 30)]
|
||||
pub framerate: u32,
|
||||
/// Cap the encoded video height (px); width follows the source aspect.
|
||||
/// Power-user override — takes precedence over the preset's height.
|
||||
#[arg(long, value_name = "N")]
|
||||
pub max_height: Option<u32>,
|
||||
|
||||
/// Encode bitrate in kbps. Overrides the quality preset's bitrate.
|
||||
#[arg(long)]
|
||||
pub bitrate: Option<u32>,
|
||||
|
||||
/// Capture framerate. Overrides the quality preset's framerate.
|
||||
#[arg(long)]
|
||||
pub framerate: Option<u32>,
|
||||
|
||||
/// Disable VAAPI HW encode; force software x264.
|
||||
#[arg(long)]
|
||||
pub no_hwencode: bool,
|
||||
|
||||
/// Use low-latency SRT transport instead of HTTP MPEG-TS (Phase 2/3).
|
||||
/// Maximum number of concurrent viewers. Additional connections are
|
||||
/// politely refused with a "host full" message. Defaults to the
|
||||
/// connection-aware recommendation from the bandwidth pre-flight if
|
||||
/// available, otherwise 2.
|
||||
#[arg(long)]
|
||||
pub low_latency: bool,
|
||||
pub max_viewers: Option<u32>,
|
||||
|
||||
// ── viewer options ────────────────────────────────────────────────
|
||||
/// Local TCP port for the viewer to expose (default: random).
|
||||
@@ -51,6 +79,24 @@ pub struct Cli {
|
||||
pub port: u16,
|
||||
|
||||
// ── global ────────────────────────────────────────────────────────
|
||||
/// Relay server URL to use instead of the bundled defaults, e.g.
|
||||
/// `https://relay.example/`. Applies to both host and viewer. Falls back
|
||||
/// to the `PIXELPASS_RELAY` environment variable. Use this to get off the
|
||||
/// pre-release default relays or to point at a self-hosted relay.
|
||||
#[arg(long, value_name = "URL")]
|
||||
pub relay: Option<String>,
|
||||
|
||||
/// Launch the graphical front-end (a window with Host/View controls)
|
||||
/// instead of the terminal menu. Requires a build with `--features gui`.
|
||||
#[arg(long)]
|
||||
pub gui: bool,
|
||||
|
||||
/// Emit machine-readable events on stdout (one JSON object per line)
|
||||
/// alongside the human banner on stderr. For scripts and the --gui
|
||||
/// front-end. Currently only `json` is supported.
|
||||
#[arg(long, value_enum, value_name = "FORMAT")]
|
||||
pub output: Option<OutputFormat>,
|
||||
|
||||
/// Trace-level logging.
|
||||
#[arg(long, short)]
|
||||
pub verbose: bool,
|
||||
@@ -58,6 +104,20 @@ pub struct Cli {
|
||||
/// Clean up orphaned PipeWire state from a crashed host run, then exit.
|
||||
#[arg(long)]
|
||||
pub repair: bool,
|
||||
|
||||
/// Print an environment diagnostic report (display server, capture/encode
|
||||
/// dependencies, VA-API H.264 support, viewer player, relay reachability),
|
||||
/// then exit. Use this to check a machine can host or view before a real
|
||||
/// session — especially to confirm hardware H.264 encode works, since a GPU
|
||||
/// without it silently produces no video under the default encoder.
|
||||
#[arg(long)]
|
||||
pub doctor: bool,
|
||||
|
||||
/// Re-run the bandwidth pre-flight test, save the result, then exit.
|
||||
/// Use this if your connection has changed (new ISP, moved house, etc.)
|
||||
/// or if the previously saved test result is stale.
|
||||
#[arg(long)]
|
||||
pub reconfigure: bool,
|
||||
}
|
||||
|
||||
#[derive(ValueEnum, Clone, Copy, Debug)]
|
||||
@@ -66,23 +126,60 @@ pub enum DisplayServerArg {
|
||||
X11,
|
||||
}
|
||||
|
||||
#[derive(ValueEnum, Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum OutputFormat {
|
||||
/// One JSON object per line on stdout.
|
||||
Json,
|
||||
}
|
||||
|
||||
/// Quality preset. Each fixed preset bundles a (max-height, bitrate, fps)
|
||||
/// tuple — resolution is a quality-per-bitrate knob, so the three only make
|
||||
/// sense together. `Auto` has no fixed tuple; it picks one of the others from
|
||||
/// the bandwidth pre-flight at host startup. See `host::quality`.
|
||||
#[derive(ValueEnum, Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Quality {
|
||||
/// Native source resolution, 6000 kbps, 30 fps (no downscale).
|
||||
Source,
|
||||
/// Up to 1080p, 4000 kbps, 30 fps.
|
||||
High,
|
||||
/// Up to 720p, 2500 kbps, 30 fps.
|
||||
Medium,
|
||||
/// Up to 480p, 1000 kbps, 30 fps.
|
||||
Low,
|
||||
/// Derive from the measured upstream; falls back to `medium` when unmeasured.
|
||||
Auto,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct HostOpts {
|
||||
pub window: bool,
|
||||
pub app: Option<String>,
|
||||
pub mic: bool,
|
||||
/// With `app` set, suppress the whole-desktop loopback fallback so the
|
||||
/// viewer only ever hears the chosen app (silence when it's quiet). No
|
||||
/// effect when `app` is None.
|
||||
pub strict_audio: bool,
|
||||
pub display_server: Option<DisplayServerArg>,
|
||||
pub bitrate: u32,
|
||||
pub framerate: u32,
|
||||
/// Chosen preset (Auto = derive at startup). Defaults to Auto.
|
||||
pub quality: Quality,
|
||||
/// Raw `--bitrate` override (kbps); None = use the preset's bitrate.
|
||||
pub bitrate: Option<u32>,
|
||||
/// Raw `--framerate` override; None = use the preset's framerate.
|
||||
pub framerate: Option<u32>,
|
||||
/// Raw `--max-height` override (px); None = use the preset's height.
|
||||
pub max_height: Option<u32>,
|
||||
pub no_hwencode: bool,
|
||||
pub low_latency: bool,
|
||||
pub max_viewers: Option<u32>,
|
||||
pub interactive: bool,
|
||||
/// Relay override (resolved from `--relay` / `PIXELPASS_RELAY`); None = defaults.
|
||||
pub relay: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ViewerOpts {
|
||||
pub port: u16,
|
||||
pub interactive: bool,
|
||||
/// Relay override (resolved from `--relay` / `PIXELPASS_RELAY`); None = defaults.
|
||||
pub relay: Option<String>,
|
||||
}
|
||||
|
||||
impl Cli {
|
||||
@@ -90,17 +187,26 @@ impl Cli {
|
||||
HostOpts {
|
||||
window: self.window,
|
||||
app: self.app,
|
||||
mic: self.mic,
|
||||
strict_audio: self.strict_audio,
|
||||
display_server: self.display_server,
|
||||
// No `--quality` and nothing picked interactively → the documented
|
||||
// default, Auto.
|
||||
quality: self.quality.unwrap_or(Quality::Auto),
|
||||
bitrate: self.bitrate,
|
||||
framerate: self.framerate,
|
||||
max_height: self.max_height,
|
||||
no_hwencode: self.no_hwencode,
|
||||
low_latency: self.low_latency,
|
||||
max_viewers: self.max_viewers,
|
||||
interactive,
|
||||
relay: crate::common::endpoint::relay_override(self.relay.as_deref()),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn into_viewer_opts(self, interactive: bool) -> ViewerOpts {
|
||||
ViewerOpts { port: self.port, interactive }
|
||||
ViewerOpts {
|
||||
port: self.port,
|
||||
interactive,
|
||||
relay: crate::common::endpoint::relay_override(self.relay.as_deref()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+10
-1
@@ -1,5 +1,14 @@
|
||||
/// ALPN identifying the pixelpass wire protocol on the iroh tunnel.
|
||||
/// ALPN identifying the pixelpass video wire protocol on the iroh tunnel.
|
||||
///
|
||||
/// Bump the version suffix whenever the wire format changes. Today the wire is
|
||||
/// "raw MPEG-TS bytes copied bidirectionally," so bumps will be rare.
|
||||
pub const ALPN: &[u8] = b"pixelpass/0";
|
||||
|
||||
/// ALPN for the friends control plane — the always-on presence endpoint that
|
||||
/// carries friend requests and shared codes between peers' GUIs. Separate from
|
||||
/// [`ALPN`] so the same machine can run a control endpoint and a video endpoint
|
||||
/// without their accept loops colliding, and so a control dial never lands on a
|
||||
/// bare video host (which doesn't speak this protocol). GUI-only, like the rest
|
||||
/// of the friends stack.
|
||||
#[cfg(feature = "gui")]
|
||||
pub const CONTROL_ALPN: &[u8] = b"pixelpass/ctrl/0";
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
//! One-shot upstream bandwidth measurement against Cloudflare's open
|
||||
//! speed-test endpoint. POST a fixed payload, time it, derive Mbps.
|
||||
//!
|
||||
//! Run via `tokio::task::spawn_blocking` from async contexts — ureq is a
|
||||
//! blocking client and we don't want to wedge the tokio runtime during
|
||||
//! the test.
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
const ENDPOINT: &str = "https://speed.cloudflare.com/__up";
|
||||
const PAYLOAD_BYTES: usize = 5 * 1024 * 1024; // 5 MiB
|
||||
const HTTP_TIMEOUT: Duration = Duration::from_secs(30);
|
||||
/// Multiplier applied to the raw measurement. TCP slow-start, ramp-up, and
|
||||
/// real-world contention all mean a one-shot upstream test slightly
|
||||
/// overestimates sustainable throughput; clamp to 80% for headroom.
|
||||
const SAFETY_FACTOR: f64 = 0.80;
|
||||
|
||||
/// Result of a successful measurement.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Measurement {
|
||||
/// Raw measured throughput in megabits per second.
|
||||
pub raw_mbps: f64,
|
||||
/// `raw_mbps * SAFETY_FACTOR` — the value to use when sizing things.
|
||||
pub safe_mbps: f64,
|
||||
/// How long the upload took.
|
||||
pub elapsed: Duration,
|
||||
}
|
||||
|
||||
/// Blocking upload-speed test. Call from a `spawn_blocking` task.
|
||||
pub fn measure_upstream_blocking() -> Result<Measurement> {
|
||||
let payload = vec![0u8; PAYLOAD_BYTES];
|
||||
let agent = ureq::Agent::config_builder()
|
||||
.timeout_global(Some(HTTP_TIMEOUT))
|
||||
.build()
|
||||
.new_agent();
|
||||
|
||||
let start = Instant::now();
|
||||
let response = agent
|
||||
.post(ENDPOINT)
|
||||
.content_type("application/octet-stream")
|
||||
.send(&payload[..])
|
||||
.context("upload request to Cloudflare failed")?;
|
||||
let elapsed = start.elapsed();
|
||||
|
||||
let status = response.status();
|
||||
if !status.is_success() {
|
||||
anyhow::bail!("Cloudflare returned HTTP {status}");
|
||||
}
|
||||
|
||||
let bits = (PAYLOAD_BYTES as f64) * 8.0;
|
||||
let seconds = elapsed.as_secs_f64().max(0.001);
|
||||
let raw_mbps = bits / seconds / 1_000_000.0;
|
||||
let safe_mbps = raw_mbps * SAFETY_FACTOR;
|
||||
|
||||
Ok(Measurement {
|
||||
raw_mbps,
|
||||
safe_mbps,
|
||||
elapsed,
|
||||
})
|
||||
}
|
||||
|
||||
/// Convert a safe-upstream Mbps figure plus the host's per-viewer bitrate
|
||||
/// (kbps for video, ignoring audio + protocol overhead which we account for
|
||||
/// via SAFETY_FACTOR) into a recommended viewer count. Floors to at least 1.
|
||||
pub fn recommended_max_viewers(safe_mbps: f64, bitrate_kbps: u32) -> u32 {
|
||||
let per_viewer_mbps = (bitrate_kbps as f64) / 1000.0;
|
||||
// Guard non-finite / non-positive inputs (only reachable from a corrupted
|
||||
// config): a NaN safe_mbps would cast to 0 and an infinite one to u32::MAX,
|
||||
// both of which break the "at least 1" contract.
|
||||
if !safe_mbps.is_finite() || safe_mbps <= 0.0 || per_viewer_mbps <= 0.0 {
|
||||
return 1;
|
||||
}
|
||||
let n = (safe_mbps / per_viewer_mbps).floor();
|
||||
if n < 1.0 { 1 } else { n as u32 }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::recommended_max_viewers;
|
||||
|
||||
#[test]
|
||||
fn divides_bandwidth_by_per_viewer_bitrate() {
|
||||
// 8 Mbps safe / 2 Mbps each = 4 viewers.
|
||||
assert_eq!(recommended_max_viewers(8.0, 2000), 4);
|
||||
// Floors the fractional part: 7.9 / 2 = 3.95 -> 3.
|
||||
assert_eq!(recommended_max_viewers(7.9, 2000), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn floors_to_at_least_one() {
|
||||
// Not even enough for one viewer still allows one (best effort).
|
||||
assert_eq!(recommended_max_viewers(0.5, 2000), 1);
|
||||
// Zero / unknown bitrate can't size a budget; floor to one.
|
||||
assert_eq!(recommended_max_viewers(8.0, 0), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn degenerate_inputs_floor_to_one() {
|
||||
// A corrupted config must not yield 0 (NaN) or u32::MAX (Inf).
|
||||
assert_eq!(recommended_max_viewers(f64::NAN, 2000), 1);
|
||||
assert_eq!(recommended_max_viewers(f64::INFINITY, 2000), 1);
|
||||
assert_eq!(recommended_max_viewers(-5.0, 2000), 1);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
//! Persistent user-level config at `~/.config/pixelpass/config.toml`.
|
||||
//!
|
||||
//! It tracks the bandwidth pre-flight result and the GUI's preferences.
|
||||
//! Further settings can hang off the same file under their own `[section]`.
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
use chrono::{DateTime, Utc};
|
||||
use directories::ProjectDirs;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::fs;
|
||||
use std::io::Write;
|
||||
use std::path::PathBuf;
|
||||
|
||||
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
|
||||
pub struct Config {
|
||||
#[serde(default)]
|
||||
pub bandwidth: BandwidthEntry,
|
||||
#[serde(default)]
|
||||
pub gui: GuiSettings,
|
||||
}
|
||||
|
||||
/// Preferences for the `pixelpass --gui` front-end.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct GuiSettings {
|
||||
/// When true, the window's close button hides the app to the system tray
|
||||
/// (keeping any live stream running) instead of quitting. Defaults to
|
||||
/// false — closing quits, which is what people expect.
|
||||
#[serde(default)]
|
||||
pub close_to_tray: bool,
|
||||
/// When true, the host screen renders a QR-code panel for the ticket.
|
||||
/// Defaults to true; the toggle exists for users who prefer the plain
|
||||
/// text-only host screen.
|
||||
#[serde(default = "default_true")]
|
||||
pub show_qr: bool,
|
||||
/// Name of the active GUI colour theme (a built-in, or a user file in
|
||||
/// `~/.config/pixelpass/themes/`). Defaults to the built-in Default Dark.
|
||||
#[serde(default = "default_theme")]
|
||||
pub theme: String,
|
||||
/// The display name shown to friends (in requests and shared codes).
|
||||
/// Seeded from the login name; editable in Settings.
|
||||
#[serde(default = "default_display_name")]
|
||||
pub display_name: String,
|
||||
}
|
||||
|
||||
impl Default for GuiSettings {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
close_to_tray: false,
|
||||
show_qr: true,
|
||||
theme: default_theme(),
|
||||
display_name: default_display_name(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn default_true() -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
fn default_theme() -> String {
|
||||
"Default Dark".to_string()
|
||||
}
|
||||
|
||||
/// Seed the friends display name from the login name, falling back to a
|
||||
/// generic label when `$USER` isn't set.
|
||||
fn default_display_name() -> String {
|
||||
std::env::var("USER")
|
||||
.ok()
|
||||
.filter(|s| !s.trim().is_empty())
|
||||
.unwrap_or_else(|| "PixelPass user".to_string())
|
||||
}
|
||||
|
||||
/// Result of the first-run upstream measurement.
|
||||
///
|
||||
/// `status = "unmeasured"` means we've never asked the user — show the
|
||||
/// first-run dialog. `"measured"` means we have a number. `"skipped"`
|
||||
/// means the user opted out (sticky — don't ask again). `"failed"`
|
||||
/// means the last attempt errored and we should ask the user on next
|
||||
/// interactive launch whether to retry.
|
||||
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
|
||||
pub struct BandwidthEntry {
|
||||
#[serde(default = "default_status")]
|
||||
pub status: BandwidthStatus,
|
||||
#[serde(default)]
|
||||
pub upstream_mbps: Option<f64>,
|
||||
#[serde(default)]
|
||||
pub measured_at: Option<DateTime<Utc>>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
#[derive(Default)]
|
||||
pub enum BandwidthStatus {
|
||||
#[default]
|
||||
Unmeasured,
|
||||
Measured,
|
||||
Skipped,
|
||||
Failed,
|
||||
}
|
||||
|
||||
fn default_status() -> BandwidthStatus {
|
||||
BandwidthStatus::Unmeasured
|
||||
}
|
||||
|
||||
/// Returns `~/.config/pixelpass/config.toml` (or the XDG equivalent on other
|
||||
/// platforms). The parent directory is created lazily by [`save`].
|
||||
pub fn config_path() -> Result<PathBuf> {
|
||||
let dirs = ProjectDirs::from("", "", "pixelpass")
|
||||
.context("could not locate a config directory for pixelpass")?;
|
||||
Ok(dirs.config_dir().join("config.toml"))
|
||||
}
|
||||
|
||||
/// Returns the loaded config, or a `Default` instance if the file doesn't
|
||||
/// exist yet. Bubble up parse errors so we don't silently overwrite a
|
||||
/// hand-edited config the user is debugging.
|
||||
pub fn load() -> Result<Config> {
|
||||
let path = config_path()?;
|
||||
match fs::read_to_string(&path) {
|
||||
Ok(s) => toml::from_str::<Config>(&s)
|
||||
.with_context(|| format!("failed to parse {}", path.display())),
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(Config::default()),
|
||||
Err(e) => Err(e).with_context(|| format!("failed to read {}", path.display())),
|
||||
}
|
||||
}
|
||||
|
||||
/// Atomic write via tempfile-in-same-dir + rename.
|
||||
pub fn save(cfg: &Config) -> Result<()> {
|
||||
let path = config_path()?;
|
||||
let parent = path
|
||||
.parent()
|
||||
.context("config path has no parent directory")?;
|
||||
fs::create_dir_all(parent).with_context(|| format!("failed to create {}", parent.display()))?;
|
||||
|
||||
let serialized = toml::to_string_pretty(cfg).context("failed to serialize config to TOML")?;
|
||||
|
||||
let tmp = parent.join(format!(".config.toml.tmp.{}", std::process::id()));
|
||||
{
|
||||
let mut f = fs::File::create(&tmp)
|
||||
.with_context(|| format!("failed to create {}", tmp.display()))?;
|
||||
f.write_all(serialized.as_bytes())
|
||||
.with_context(|| format!("failed to write {}", tmp.display()))?;
|
||||
f.sync_all().ok();
|
||||
}
|
||||
fs::rename(&tmp, &path)
|
||||
.with_context(|| format!("failed to rename {} -> {}", tmp.display(), path.display()))?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,260 @@
|
||||
//! Friends control-plane protocol and service.
|
||||
//!
|
||||
//! This is the always-on presence channel that rides the [`CONTROL_ALPN`]
|
||||
//! endpoint (bound with the persistent identity — see
|
||||
//! [`super::endpoint::bind_control`]). It's how two peers' GUIs exchange friend
|
||||
//! requests and pushed share-codes, independent of any video session.
|
||||
//!
|
||||
//! Wire shape: **one message per connection.** The sender opens a bi-stream,
|
||||
//! writes the JSON-encoded [`ControlMsg`], and finishes its send side (EOF
|
||||
//! delimits the message — no length framing needed). The receiver reads to EOF,
|
||||
//! parses, hands the message up, then writes a one-byte [`ACK`] back so the
|
||||
//! sender knows it was delivered *and* parsed. That delivery signal is what
|
||||
//! lets the host-side code-push queue (a later phase) tell "sent" from "friend
|
||||
//! was offline." A friend's *reply* (accept/decline) is a separate later
|
||||
//! connection in the other direction, because acceptance can happen minutes
|
||||
//! after the request — not a response on the same stream.
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
use anyhow::{Context, Result, bail};
|
||||
use iroh::endpoint::{Incoming, VarInt};
|
||||
use iroh::{Endpoint, EndpointAddr, EndpointId};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use tokio::sync::mpsc;
|
||||
|
||||
use super::alpn::CONTROL_ALPN;
|
||||
|
||||
/// Upper bound on a single control message. Generous for a display name plus a
|
||||
/// share-code ticket (~150 chars); rejects a peer trying to make us buffer a
|
||||
/// huge blob.
|
||||
const MAX_MSG: usize = 64 * 1024;
|
||||
|
||||
/// One-byte application acknowledgement the receiver returns once it has parsed
|
||||
/// a message. ASCII ACK (0x06).
|
||||
const ACK: &[u8] = b"\x06";
|
||||
|
||||
/// Bound on each phase of the send handshake, so a half-dead peer or relay
|
||||
/// can't park a sender (or an inbound handler) forever.
|
||||
const IO_TIMEOUT: Duration = Duration::from_secs(10);
|
||||
|
||||
/// A message on the friends control plane.
|
||||
///
|
||||
/// `#[serde(tag = "type")]` keeps the JSON self-describing and lets us add
|
||||
/// variants without breaking older peers (an unknown tag fails to parse and is
|
||||
/// logged, rather than being silently misread as another variant).
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(tag = "type", rename_all = "snake_case")]
|
||||
pub enum ControlMsg {
|
||||
/// "I'm online; here's my current display name." A presence/name refresh.
|
||||
Hello { name: String },
|
||||
/// Ask the recipient to become friends.
|
||||
FriendRequest { name: String },
|
||||
/// Accept a request the recipient previously sent us.
|
||||
FriendAccept { name: String },
|
||||
/// Decline a pending request, or cancel an outgoing one.
|
||||
FriendDecline,
|
||||
/// A host pushing a freshly generated share-code to an accepted friend.
|
||||
ShareCode { name: String, ticket: String },
|
||||
}
|
||||
|
||||
/// A received control message, paired with the *authenticated* sender id (the
|
||||
/// connection's verified remote public key — not a value the peer can spoof in
|
||||
/// the payload, which is why no variant carries a sender id).
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Inbound {
|
||||
pub from: EndpointId,
|
||||
pub msg: ControlMsg,
|
||||
}
|
||||
|
||||
fn encode(msg: &ControlMsg) -> Result<Vec<u8>> {
|
||||
serde_json::to_vec(msg).context("failed to encode control message")
|
||||
}
|
||||
|
||||
fn decode(bytes: &[u8]) -> Result<ControlMsg> {
|
||||
serde_json::from_slice(bytes).context("failed to decode control message")
|
||||
}
|
||||
|
||||
/// Deliver one message to `peer` over `endpoint`, returning once the recipient
|
||||
/// has acknowledged it. An error means it was *not* delivered (peer offline,
|
||||
/// unreachable, or rejected the stream) — the caller can queue and retry.
|
||||
///
|
||||
/// `peer` is usually a bare [`EndpointId`] — friends store only the stable id,
|
||||
/// and n0 DNS discovery resolves it to a live address. The full [`EndpointAddr`]
|
||||
/// form exists for callers that already hold one (and for hermetic tests).
|
||||
pub async fn send(
|
||||
endpoint: &Endpoint,
|
||||
peer: impl Into<EndpointAddr>,
|
||||
msg: &ControlMsg,
|
||||
) -> Result<()> {
|
||||
let payload = encode(msg)?;
|
||||
let conn = tokio::time::timeout(IO_TIMEOUT, endpoint.connect(peer, CONTROL_ALPN))
|
||||
.await
|
||||
.context("timed out connecting to peer")?
|
||||
.context("failed to connect to peer")?;
|
||||
|
||||
let io = async {
|
||||
let (mut send, mut recv) = conn
|
||||
.open_bi()
|
||||
.await
|
||||
.context("failed to open control stream")?;
|
||||
send.write_all(&payload)
|
||||
.await
|
||||
.context("failed to write control message")?;
|
||||
send.finish().context("failed to finish control stream")?;
|
||||
// Read the peer's ACK. read_to_end returns once the peer finishes its
|
||||
// send side, so this also serves as "the peer is done with us."
|
||||
let ack = recv
|
||||
.read_to_end(ACK.len() + 1)
|
||||
.await
|
||||
.context("peer closed the control stream without acknowledging")?;
|
||||
if ack != ACK {
|
||||
bail!(
|
||||
"peer sent an unexpected acknowledgement ({} bytes)",
|
||||
ack.len()
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
};
|
||||
|
||||
let result = tokio::time::timeout(IO_TIMEOUT, io)
|
||||
.await
|
||||
.context("timed out sending control message")?;
|
||||
// Clean close so the peer's `closed().await` returns promptly either way.
|
||||
conn.close(VarInt::from_u32(0), b"done");
|
||||
result
|
||||
}
|
||||
|
||||
/// Run the control-plane accept loop, forwarding every received message to
|
||||
/// `tx`. Returns when the endpoint stops accepting (i.e. it was closed).
|
||||
pub async fn serve(endpoint: Endpoint, tx: mpsc::Sender<Inbound>) {
|
||||
while let Some(incoming) = endpoint.accept().await {
|
||||
let tx = tx.clone();
|
||||
tokio::spawn(async move {
|
||||
if let Err(e) = handle(incoming, &tx).await {
|
||||
tracing::warn!("control: inbound connection failed: {e:#}");
|
||||
}
|
||||
});
|
||||
}
|
||||
tracing::info!("control: endpoint stopped accepting");
|
||||
}
|
||||
|
||||
async fn handle(incoming: Incoming, tx: &mpsc::Sender<Inbound>) -> Result<()> {
|
||||
let conn = incoming
|
||||
.await
|
||||
.context("inbound control connection failed")?;
|
||||
let from = conn.remote_id();
|
||||
|
||||
let msg = async {
|
||||
let (mut send, mut recv) = conn
|
||||
.accept_bi()
|
||||
.await
|
||||
.context("failed to accept control stream")?;
|
||||
let bytes = recv
|
||||
.read_to_end(MAX_MSG)
|
||||
.await
|
||||
.context("failed to read control message")?;
|
||||
let msg = decode(&bytes)?;
|
||||
// ACK only after a successful parse, so the sender's delivery signal
|
||||
// means "received and understood."
|
||||
send.write_all(ACK).await.context("failed to write ack")?;
|
||||
send.finish().context("failed to finish ack stream")?;
|
||||
Ok::<_, anyhow::Error>(msg)
|
||||
};
|
||||
|
||||
let msg = tokio::time::timeout(IO_TIMEOUT, msg)
|
||||
.await
|
||||
.context("timed out reading control message")??;
|
||||
|
||||
// Hand the message up first, so it reaches the UI promptly even when the
|
||||
// sender is slow to close (a degraded link could otherwise delay a friend
|
||||
// request / pushed code by up to IO_TIMEOUT).
|
||||
tx.send(Inbound { from, msg })
|
||||
.await
|
||||
.map_err(|_| anyhow::anyhow!("control: receiver dropped"))?;
|
||||
|
||||
// Then wait (briefly) for the sender's close so our ACK has flushed before
|
||||
// the connection is dropped at the end of this scope.
|
||||
let _ = tokio::time::timeout(IO_TIMEOUT, conn.closed()).await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn control_msg_round_trips() {
|
||||
let cases = [
|
||||
ControlMsg::Hello {
|
||||
name: "alice".into(),
|
||||
},
|
||||
ControlMsg::FriendRequest { name: "bob".into() },
|
||||
ControlMsg::FriendAccept {
|
||||
name: "carol".into(),
|
||||
},
|
||||
ControlMsg::FriendDecline,
|
||||
ControlMsg::ShareCode {
|
||||
name: "dave".into(),
|
||||
ticket: "endpointaa…".into(),
|
||||
},
|
||||
];
|
||||
for msg in cases {
|
||||
let bytes = encode(&msg).unwrap();
|
||||
assert_eq!(decode(&bytes).unwrap(), msg);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_tag_is_rejected() {
|
||||
assert!(decode(br#"{"type":"nonsense"}"#).is_err());
|
||||
}
|
||||
|
||||
/// Bind a control-plane endpoint with a *fresh* random key, so two of them
|
||||
/// in one test get distinct ids (two real machines each have their own
|
||||
/// persistent key; `bind_control` would give both the same one here, and
|
||||
/// iroh refuses "connecting to ourself").
|
||||
async fn bind_test_control() -> Endpoint {
|
||||
iroh::Endpoint::builder(iroh::endpoint::presets::N0)
|
||||
.secret_key(iroh::SecretKey::generate())
|
||||
.alpns(vec![CONTROL_ALPN.to_vec()])
|
||||
.bind()
|
||||
.await
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
/// End-to-end over two real iroh endpoints on this machine. Ignored by
|
||||
/// default — it binds endpoints and waits on the relay, so it's slow and
|
||||
/// network-dependent. Run with `cargo test -- --ignored control`.
|
||||
#[tokio::test]
|
||||
#[ignore = "binds real iroh endpoints; run on demand"]
|
||||
async fn loopback_delivers_and_acks() {
|
||||
let server = bind_test_control().await;
|
||||
let client = bind_test_control().await;
|
||||
// Connect by full addr so the test doesn't depend on DNS discovery.
|
||||
server.online().await;
|
||||
client.online().await;
|
||||
let server_addr = server.addr();
|
||||
|
||||
let (tx, mut rx) = mpsc::channel(4);
|
||||
let server_ep = server.clone();
|
||||
let serve_task = tokio::spawn(async move { serve(server_ep, tx).await });
|
||||
|
||||
let msg = ControlMsg::FriendRequest {
|
||||
name: "tester".into(),
|
||||
};
|
||||
// Full addr (not just the id) so the test doesn't depend on DNS discovery.
|
||||
send(&client, server_addr.clone(), &msg).await.unwrap();
|
||||
|
||||
let got = tokio::time::timeout(Duration::from_secs(15), rx.recv())
|
||||
.await
|
||||
.expect("no inbound within 15s")
|
||||
.expect("channel closed");
|
||||
assert_eq!(got.msg, msg);
|
||||
assert_eq!(got.from, client.addr().id);
|
||||
|
||||
server.close().await;
|
||||
client.close().await;
|
||||
serve_task.abort();
|
||||
}
|
||||
}
|
||||
+119
-32
@@ -2,21 +2,49 @@ use anyhow::{Result, bail};
|
||||
use std::path::PathBuf;
|
||||
use std::process::Command;
|
||||
|
||||
use crate::cli::HostOpts;
|
||||
use crate::common::display::DisplayServer;
|
||||
|
||||
pub fn check_host_binaries(display: DisplayServer) -> Result<()> {
|
||||
if display == DisplayServer::Wayland {
|
||||
require("gst-launch-1.0")?;
|
||||
require("gst-inspect-1.0")?;
|
||||
require("pactl")?;
|
||||
require_gst_element("pipewiresrc")?;
|
||||
require_gst_element("vah264enc")?;
|
||||
require_gst_element("h264parse")?;
|
||||
require_gst_element("mpegtsmux")?;
|
||||
require_gst_element("pulsesrc")?;
|
||||
require_gst_element("avenc_aac")?;
|
||||
require_gst_element("aacparse")?;
|
||||
pub fn check_host_binaries(display: DisplayServer, opts: &HostOpts) -> Result<()> {
|
||||
// Unknown is handled (and rejected) by the caller; nothing to check here.
|
||||
if display == DisplayServer::Unknown {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
// Shared across both backends: the gst tools, audio routing, and the
|
||||
// encode/mux tail elements.
|
||||
require("gst-launch-1.0")?;
|
||||
require("gst-inspect-1.0")?;
|
||||
require("pactl")?;
|
||||
// videoscale (downscale for the quality presets) lives in plugins-base,
|
||||
// the same package the gst tools need, so this rarely fails on its own —
|
||||
// but check it for a clear error if a partial install is missing it.
|
||||
require_gst_element("videoscale")?;
|
||||
require_gst_element("h264parse")?;
|
||||
require_gst_element("mpegtsmux")?;
|
||||
require_gst_element("pulsesrc")?;
|
||||
require_gst_element("avenc_aac")?;
|
||||
require_gst_element("aacparse")?;
|
||||
|
||||
// Encoder depends on --no-hwencode (software x264 vs hardware VAAPI).
|
||||
if opts.no_hwencode {
|
||||
require_gst_element("x264enc")?;
|
||||
} else {
|
||||
require_gst_element("vah264enc")?;
|
||||
}
|
||||
|
||||
// Per-backend video source, plus the X11 window-picker when --window is set.
|
||||
match display {
|
||||
DisplayServer::Wayland => require_gst_element("pipewiresrc")?,
|
||||
DisplayServer::X11 => {
|
||||
require_gst_element("ximagesrc")?;
|
||||
if opts.window {
|
||||
require("xwininfo")?;
|
||||
}
|
||||
}
|
||||
DisplayServer::Unknown => unreachable!("early-returned above"),
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -28,12 +56,7 @@ fn require(bin: &str) -> Result<PathBuf> {
|
||||
}
|
||||
|
||||
fn require_gst_element(name: &str) -> Result<()> {
|
||||
let ok = Command::new("gst-inspect-1.0")
|
||||
.args(["--exists", name])
|
||||
.status()
|
||||
.map(|s| s.success())
|
||||
.unwrap_or(false);
|
||||
if !ok {
|
||||
if !gst_element_exists(name) {
|
||||
bail!(
|
||||
"GStreamer element `{name}` not available.\n{}",
|
||||
install_hint_for_gst_element(name)
|
||||
@@ -42,7 +65,17 @@ fn require_gst_element(name: &str) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn which(bin: &str) -> Option<PathBuf> {
|
||||
/// Whether a GStreamer element is registered, via `gst-inspect-1.0 --exists`.
|
||||
/// Non-bailing counterpart to [`require_gst_element`] for the `doctor` report.
|
||||
pub(crate) fn gst_element_exists(name: &str) -> bool {
|
||||
Command::new("gst-inspect-1.0")
|
||||
.args(["--exists", name])
|
||||
.status()
|
||||
.map(|s| s.success())
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
pub(crate) fn which(bin: &str) -> Option<PathBuf> {
|
||||
let path = std::env::var_os("PATH")?;
|
||||
for dir in std::env::split_paths(&path) {
|
||||
let candidate = dir.join(bin);
|
||||
@@ -53,60 +86,110 @@ fn which(bin: &str) -> Option<PathBuf> {
|
||||
None
|
||||
}
|
||||
|
||||
fn install_hint_for_bin(bin: &str) -> String {
|
||||
pub(crate) fn install_hint_for_bin(bin: &str) -> String {
|
||||
let distro = detect_distro();
|
||||
let pkg = match bin {
|
||||
"gst-launch-1.0" | "gst-inspect-1.0" => match distro.as_deref() {
|
||||
Some("arch" | "cachyos" | "manjaro" | "endeavouros") => "gstreamer gst-plugins-base",
|
||||
Some("arch" | "cachyos" | "manjaro" | "endeavouros" | "artix" | "garuda") => {
|
||||
"gstreamer gst-plugins-base"
|
||||
}
|
||||
Some("debian" | "ubuntu" | "pop" | "linuxmint") => "gstreamer1.0-tools",
|
||||
Some("fedora" | "nobara") => "gstreamer1 gstreamer1-plugins-base-tools",
|
||||
_ => "gstreamer + tools",
|
||||
},
|
||||
"pactl" => match distro.as_deref() {
|
||||
Some("arch" | "cachyos" | "manjaro" | "endeavouros") => "libpulse",
|
||||
Some("arch" | "cachyos" | "manjaro" | "endeavouros" | "artix" | "garuda") => "libpulse",
|
||||
Some("debian" | "ubuntu" | "pop" | "linuxmint") => "pulseaudio-utils",
|
||||
Some("fedora" | "nobara") => "pulseaudio-utils",
|
||||
Some("opensuse" | "opensuse-tumbleweed" | "opensuse-leap") => "pulseaudio-utils",
|
||||
_ => "pulseaudio-utils (provides `pactl`)",
|
||||
},
|
||||
"xwininfo" => match distro.as_deref() {
|
||||
Some("arch" | "cachyos" | "manjaro" | "endeavouros" | "artix" | "garuda") => {
|
||||
"xorg-xwininfo"
|
||||
}
|
||||
Some("debian" | "ubuntu" | "pop" | "linuxmint") => "x11-utils",
|
||||
Some("fedora" | "nobara") => "xorg-x11-utils",
|
||||
Some("opensuse" | "opensuse-tumbleweed" | "opensuse-leap") => "xwininfo",
|
||||
_ => "xwininfo (X11 window-info utility)",
|
||||
},
|
||||
_ => bin,
|
||||
};
|
||||
install_command(&distro, pkg)
|
||||
}
|
||||
|
||||
fn install_hint_for_gst_element(name: &str) -> String {
|
||||
pub(crate) fn install_hint_for_gst_element(name: &str) -> String {
|
||||
let distro = detect_distro();
|
||||
let pkg = match name {
|
||||
"pipewiresrc" => match distro.as_deref() {
|
||||
Some("arch" | "cachyos" | "manjaro" | "endeavouros") => "gst-plugin-pipewire",
|
||||
Some("arch" | "cachyos" | "manjaro" | "endeavouros" | "artix" | "garuda") => {
|
||||
"gst-plugin-pipewire"
|
||||
}
|
||||
Some("debian" | "ubuntu" | "pop" | "linuxmint") => "gstreamer1.0-pipewire",
|
||||
Some("fedora" | "nobara") => "pipewire-gstreamer",
|
||||
Some("opensuse" | "opensuse-tumbleweed" | "opensuse-leap") => "pipewire-gstreamer",
|
||||
_ => "the GStreamer PipeWire plugin",
|
||||
},
|
||||
"vah264enc" => match distro.as_deref() {
|
||||
Some("arch" | "cachyos" | "manjaro" | "endeavouros") => "gst-plugin-va",
|
||||
Some("arch" | "cachyos" | "manjaro" | "endeavouros" | "artix" | "garuda") => {
|
||||
"gst-plugin-va"
|
||||
}
|
||||
Some("debian" | "ubuntu" | "pop" | "linuxmint") => "gstreamer1.0-plugins-bad",
|
||||
Some("fedora" | "nobara") => "gstreamer1-plugins-bad-free",
|
||||
Some("opensuse" | "opensuse-tumbleweed" | "opensuse-leap") => "gstreamer-plugins-bad",
|
||||
_ => "the GStreamer VA-API plugin (requires an H.264-capable GPU; almost all modern GPUs)",
|
||||
_ => {
|
||||
"the GStreamer VA-API plugin (requires an H.264-capable GPU; almost all modern GPUs)"
|
||||
}
|
||||
},
|
||||
"x264enc" => match distro.as_deref() {
|
||||
Some("arch" | "cachyos" | "manjaro" | "endeavouros" | "artix" | "garuda") => {
|
||||
"gst-plugins-ugly"
|
||||
}
|
||||
Some("debian" | "ubuntu" | "pop" | "linuxmint") => "gstreamer1.0-plugins-ugly",
|
||||
Some("fedora" | "nobara") => "gstreamer1-plugins-ugly",
|
||||
Some("opensuse" | "opensuse-tumbleweed" | "opensuse-leap") => "gstreamer-plugins-ugly",
|
||||
_ => "the GStreamer x264 plugin (plugins-ugly)",
|
||||
},
|
||||
"ximagesrc" => match distro.as_deref() {
|
||||
Some("arch" | "cachyos" | "manjaro" | "endeavouros" | "artix" | "garuda") => {
|
||||
"gst-plugins-good"
|
||||
}
|
||||
Some("debian" | "ubuntu" | "pop" | "linuxmint") => "gstreamer1.0-plugins-good",
|
||||
Some("fedora" | "nobara") => "gstreamer1-plugins-good",
|
||||
Some("opensuse" | "opensuse-tumbleweed" | "opensuse-leap") => "gstreamer-plugins-good",
|
||||
_ => "the GStreamer X11 plugin (plugins-good)",
|
||||
},
|
||||
"videoscale" => match distro.as_deref() {
|
||||
Some("arch" | "cachyos" | "manjaro" | "endeavouros" | "artix" | "garuda") => {
|
||||
"gst-plugins-base"
|
||||
}
|
||||
Some("debian" | "ubuntu" | "pop" | "linuxmint") => "gstreamer1.0-plugins-base",
|
||||
Some("fedora" | "nobara") => "gstreamer1-plugins-base",
|
||||
Some("opensuse" | "opensuse-tumbleweed" | "opensuse-leap") => "gstreamer-plugins-base",
|
||||
_ => "the GStreamer plugins-base set",
|
||||
},
|
||||
"h264parse" | "mpegtsmux" | "aacparse" => match distro.as_deref() {
|
||||
Some("arch" | "cachyos" | "manjaro" | "endeavouros") => "gst-plugins-bad",
|
||||
Some("arch" | "cachyos" | "manjaro" | "endeavouros" | "artix" | "garuda") => {
|
||||
"gst-plugins-bad"
|
||||
}
|
||||
Some("debian" | "ubuntu" | "pop" | "linuxmint") => "gstreamer1.0-plugins-bad",
|
||||
Some("fedora" | "nobara") => "gstreamer1-plugins-bad-free",
|
||||
Some("opensuse" | "opensuse-tumbleweed" | "opensuse-leap") => "gstreamer-plugins-bad",
|
||||
_ => "the GStreamer plugins-bad set",
|
||||
},
|
||||
"pulsesrc" => match distro.as_deref() {
|
||||
Some("arch" | "cachyos" | "manjaro" | "endeavouros") => "gst-plugins-good",
|
||||
Some("arch" | "cachyos" | "manjaro" | "endeavouros" | "artix" | "garuda") => {
|
||||
"gst-plugins-good"
|
||||
}
|
||||
Some("debian" | "ubuntu" | "pop" | "linuxmint") => "gstreamer1.0-pulseaudio",
|
||||
Some("fedora" | "nobara") => "gstreamer1-plugins-good",
|
||||
Some("opensuse" | "opensuse-tumbleweed" | "opensuse-leap") => "gstreamer-plugins-good",
|
||||
_ => "the GStreamer PulseAudio plugin",
|
||||
},
|
||||
"avenc_aac" => match distro.as_deref() {
|
||||
Some("arch" | "cachyos" | "manjaro" | "endeavouros") => "gst-libav",
|
||||
Some("arch" | "cachyos" | "manjaro" | "endeavouros" | "artix" | "garuda") => {
|
||||
"gst-libav"
|
||||
}
|
||||
Some("debian" | "ubuntu" | "pop" | "linuxmint") => "gstreamer1.0-libav",
|
||||
Some("fedora" | "nobara") => "gstreamer1-libav",
|
||||
Some("opensuse" | "opensuse-tumbleweed" | "opensuse-leap") => "gstreamer-libav",
|
||||
@@ -119,16 +202,20 @@ fn install_hint_for_gst_element(name: &str) -> String {
|
||||
|
||||
fn install_command(distro: &Option<String>, pkg: &str) -> String {
|
||||
let cmd = match distro.as_deref() {
|
||||
Some("arch" | "cachyos" | "manjaro" | "endeavouros") => format!("sudo pacman -S {pkg}"),
|
||||
Some("arch" | "cachyos" | "manjaro" | "endeavouros" | "artix" | "garuda") => {
|
||||
format!("sudo pacman -S {pkg}")
|
||||
}
|
||||
Some("debian" | "ubuntu" | "pop" | "linuxmint") => format!("sudo apt install {pkg}"),
|
||||
Some("fedora" | "nobara") => format!("sudo dnf install {pkg}"),
|
||||
Some("opensuse" | "opensuse-tumbleweed" | "opensuse-leap") => format!("sudo zypper install {pkg}"),
|
||||
Some("opensuse" | "opensuse-tumbleweed" | "opensuse-leap") => {
|
||||
format!("sudo zypper install {pkg}")
|
||||
}
|
||||
_ => format!("install the `{pkg}` package via your distro's package manager"),
|
||||
};
|
||||
format!("Install hint: {cmd}")
|
||||
}
|
||||
|
||||
fn detect_distro() -> Option<String> {
|
||||
pub(crate) fn detect_distro() -> Option<String> {
|
||||
let contents = std::fs::read_to_string("/etc/os-release").ok()?;
|
||||
for line in contents.lines() {
|
||||
if let Some(rest) = line.strip_prefix("ID=") {
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
//! Shared iroh endpoint construction.
|
||||
//!
|
||||
//! Two planes, two identities:
|
||||
//!
|
||||
//! * The **video** plane (host/viewer sessions) binds with an *ephemeral*
|
||||
//! keypair — a fresh `EndpointId` per run. Each session is a throwaway tunnel,
|
||||
//! and keeping its id ephemeral means a screen-share leaks no stable
|
||||
//! fingerprint.
|
||||
//! * The **control** plane (the always-on friends presence service) binds with
|
||||
//! the machine's *persistent* identity (see [`identity`]), so peers can find
|
||||
//! and recognise each other across launches.
|
||||
//!
|
||||
//! They must use different identities because both can be live at once on the
|
||||
//! same machine (the GUI's control endpoint while a host session runs), and
|
||||
//! iroh routes by `EndpointId` — two live endpoints sharing one id would make
|
||||
//! relay delivery ambiguous.
|
||||
|
||||
use std::str::FromStr;
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
use iroh::endpoint::presets;
|
||||
use iroh::{Endpoint, RelayMap, RelayMode, RelayUrl};
|
||||
|
||||
use super::alpn::ALPN;
|
||||
|
||||
/// Environment variable consulted when `--relay` isn't passed. Lets the GUI's
|
||||
/// child processes and scripted runs inherit a relay choice without a flag.
|
||||
pub const RELAY_ENV: &str = "PIXELPASS_RELAY";
|
||||
|
||||
/// Resolve the relay override: explicit `--relay` wins, else `PIXELPASS_RELAY`,
|
||||
/// else `None` (use the bundled defaults).
|
||||
pub fn relay_override(flag: Option<&str>) -> Option<String> {
|
||||
flag.map(str::to_owned).or_else(|| {
|
||||
std::env::var(RELAY_ENV)
|
||||
.ok()
|
||||
.filter(|s| !s.trim().is_empty())
|
||||
})
|
||||
}
|
||||
|
||||
/// Bind a **video-plane** endpoint (host/viewer) with an ephemeral identity.
|
||||
///
|
||||
/// With no `relay` override we use [`presets::N0`] — n0 DNS discovery, the
|
||||
/// library's default relays, and the chosen crypto provider. With an override
|
||||
/// we keep all of that but swap in a single custom relay via
|
||||
/// [`RelayMode::Custom`]; this is how a user gets off the rc's bundled
|
||||
/// (canary-grade) relays or points at a self-hosted one. Discovery is
|
||||
/// unchanged, so peers still resolve each other by endpoint id.
|
||||
pub async fn bind(relay: Option<&str>) -> Result<Endpoint> {
|
||||
// No `secret_key` set → iroh mints a fresh ephemeral keypair for this run.
|
||||
bind_with(relay, None, ALPN).await
|
||||
}
|
||||
|
||||
/// Bind the **control-plane** endpoint with the machine's persistent identity
|
||||
/// (see [`super::identity`]) and the friends [`super::alpn::CONTROL_ALPN`]. Its
|
||||
/// `EndpointId` is the stable id friends know you by.
|
||||
#[cfg(feature = "gui")]
|
||||
pub async fn bind_control(relay: Option<&str>) -> Result<Endpoint> {
|
||||
let secret_key = super::identity::load_or_create()?;
|
||||
bind_with(relay, Some(secret_key), super::alpn::CONTROL_ALPN).await
|
||||
}
|
||||
|
||||
/// Shared builder: optional persistent key (None → ephemeral) + the plane's ALPN.
|
||||
async fn bind_with(
|
||||
relay: Option<&str>,
|
||||
key: Option<iroh::SecretKey>,
|
||||
alpn: &[u8],
|
||||
) -> Result<Endpoint> {
|
||||
let mut builder = Endpoint::builder(presets::N0).alpns(vec![alpn.to_vec()]);
|
||||
if let Some(key) = key {
|
||||
builder = builder.secret_key(key);
|
||||
}
|
||||
|
||||
if let Some(url) = relay {
|
||||
let url = RelayUrl::from_str(url).with_context(|| {
|
||||
format!("invalid relay URL {url:?} (expected e.g. https://relay.example/)")
|
||||
})?;
|
||||
builder = builder.relay_mode(RelayMode::Custom(RelayMap::from(url)));
|
||||
}
|
||||
|
||||
builder
|
||||
.bind()
|
||||
.await
|
||||
.context("failed to bind the iroh endpoint")
|
||||
}
|
||||
@@ -0,0 +1,331 @@
|
||||
//! Persistent friends store at `~/.config/pixelpass/friends.toml`.
|
||||
//!
|
||||
//! Kept in its own file rather than a `[friends]` section of `config.toml` so
|
||||
//! the headless CLI — which never manages friends and would round-trip the
|
||||
//! config without this knowledge — can't drop the list on a `--reconfigure`.
|
||||
//! Same reasoning as the separate `identity.key`.
|
||||
//!
|
||||
//! A friend is identified by their stable control-plane [`EndpointId`] (the id
|
||||
//! from [`super::endpoint::bind_control`]). `EndpointId` serialises as its
|
||||
//! string form in TOML, so the file is human-readable and hand-editable.
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
use iroh::EndpointId;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::fs;
|
||||
use std::io::Write;
|
||||
use std::path::PathBuf;
|
||||
|
||||
/// Where a friendship sits in the mutual-consent handshake.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum FriendState {
|
||||
/// We've sent them a request and are waiting for them to accept.
|
||||
PendingOutgoing,
|
||||
/// They've requested us; waiting for the local user to accept or decline.
|
||||
PendingIncoming,
|
||||
/// Both sides have agreed — a real friend.
|
||||
Accepted,
|
||||
}
|
||||
|
||||
/// One entry in the friends list.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct Friend {
|
||||
pub id: EndpointId,
|
||||
/// Display name — seeded from the name the peer reported, locally editable.
|
||||
pub name: String,
|
||||
pub state: FriendState,
|
||||
/// Whether the host auto-shares its session code with this friend. Toggled
|
||||
/// on the host's share picker; persisted here so the choice survives a
|
||||
/// restart. Defaults to `true` so a newly added friend is included (and an
|
||||
/// older `friends.toml` without the field loads as share-with-all).
|
||||
#[serde(default = "default_share")]
|
||||
pub share: bool,
|
||||
}
|
||||
|
||||
fn default_share() -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
/// The persisted friends list. Serialises as a TOML array of tables
|
||||
/// (`[[friends]]`).
|
||||
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
|
||||
pub struct FriendStore {
|
||||
#[serde(default)]
|
||||
pub friends: Vec<Friend>,
|
||||
}
|
||||
|
||||
/// Returns `~/.config/pixelpass/friends.toml`. Shares the config directory with
|
||||
/// [`super::config`]; the parent is created on save.
|
||||
pub fn friends_path() -> Result<PathBuf> {
|
||||
Ok(super::config::config_path()?
|
||||
.parent()
|
||||
.context("config path has no parent directory")?
|
||||
.join("friends.toml"))
|
||||
}
|
||||
|
||||
/// Load the store, or a default (empty) one if the file doesn't exist yet.
|
||||
/// Parse errors bubble up so a hand-edit being debugged isn't silently
|
||||
/// overwritten.
|
||||
pub fn load() -> Result<FriendStore> {
|
||||
let path = friends_path()?;
|
||||
match fs::read_to_string(&path) {
|
||||
Ok(s) => toml::from_str(&s).with_context(|| format!("failed to parse {}", path.display())),
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(FriendStore::default()),
|
||||
Err(e) => Err(e).with_context(|| format!("failed to read {}", path.display())),
|
||||
}
|
||||
}
|
||||
|
||||
impl FriendStore {
|
||||
/// Atomic write via tempfile-in-same-dir + rename (mirrors
|
||||
/// [`super::config::save`]).
|
||||
pub fn save(&self) -> Result<()> {
|
||||
let path = friends_path()?;
|
||||
let parent = path
|
||||
.parent()
|
||||
.context("friends path has no parent directory")?;
|
||||
fs::create_dir_all(parent)
|
||||
.with_context(|| format!("failed to create {}", parent.display()))?;
|
||||
|
||||
let serialized = toml::to_string_pretty(self).context("failed to serialize friends")?;
|
||||
let tmp = parent.join(format!(".friends.toml.tmp.{}", std::process::id()));
|
||||
{
|
||||
let mut f = fs::File::create(&tmp)
|
||||
.with_context(|| format!("failed to create {}", tmp.display()))?;
|
||||
f.write_all(serialized.as_bytes())
|
||||
.with_context(|| format!("failed to write {}", tmp.display()))?;
|
||||
f.sync_all().ok();
|
||||
}
|
||||
fs::rename(&tmp, &path)
|
||||
.with_context(|| format!("failed to rename {} -> {}", tmp.display(), path.display()))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn find(&self, id: &EndpointId) -> Option<&Friend> {
|
||||
self.friends.iter().find(|f| &f.id == id)
|
||||
}
|
||||
|
||||
pub fn find_mut(&mut self, id: &EndpointId) -> Option<&mut Friend> {
|
||||
self.friends.iter_mut().find(|f| &f.id == id)
|
||||
}
|
||||
|
||||
/// True iff this id is a fully-accepted friend — the gate the code-push
|
||||
/// (Phase 4) and "is this a known friend?" checks use.
|
||||
pub fn is_accepted(&self, id: &EndpointId) -> bool {
|
||||
matches!(
|
||||
self.find(id),
|
||||
Some(Friend {
|
||||
state: FriendState::Accepted,
|
||||
..
|
||||
})
|
||||
)
|
||||
}
|
||||
|
||||
/// Insert a new friend, or update an existing one's `name`/`state` in place.
|
||||
/// Returns a mutable reference to the stored entry.
|
||||
pub fn upsert(&mut self, id: EndpointId, name: String, state: FriendState) -> &mut Friend {
|
||||
if let Some(idx) = self.friends.iter().position(|f| f.id == id) {
|
||||
let f = &mut self.friends[idx];
|
||||
f.name = name;
|
||||
f.state = state;
|
||||
f
|
||||
} else {
|
||||
self.friends.push(Friend {
|
||||
id,
|
||||
name,
|
||||
state,
|
||||
share: true,
|
||||
});
|
||||
self.friends.last_mut().expect("just pushed")
|
||||
}
|
||||
}
|
||||
|
||||
/// Remove a friend by id. Returns whether an entry was removed.
|
||||
pub fn remove(&mut self, id: &EndpointId) -> bool {
|
||||
let before = self.friends.len();
|
||||
self.friends.retain(|f| &f.id != id);
|
||||
self.friends.len() != before
|
||||
}
|
||||
|
||||
/// Apply an inbound friend request. Returns `true` if the friendship is now
|
||||
/// settled at [`Accepted`] and the caller should reply with a `FriendAccept`
|
||||
/// — either because we'd already sent them a request (a mutual match) or
|
||||
/// because they're an existing friend re-announcing (we never downgrade an
|
||||
/// [`Accepted`] friend back to pending; a peer who lost their store and
|
||||
/// re-adds us just gets re-confirmed). Otherwise it's recorded as
|
||||
/// [`PendingIncoming`] for the user to act on and `false` is returned.
|
||||
///
|
||||
/// [`Accepted`]: FriendState::Accepted
|
||||
/// [`PendingIncoming`]: FriendState::PendingIncoming
|
||||
pub fn on_friend_request(&mut self, id: EndpointId, name: String) -> bool {
|
||||
match self.find(&id).map(|f| f.state) {
|
||||
Some(FriendState::PendingOutgoing | FriendState::Accepted) => {
|
||||
self.upsert(id, name, FriendState::Accepted);
|
||||
true
|
||||
}
|
||||
_ => {
|
||||
self.upsert(id, name, FriendState::PendingIncoming);
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Apply an inbound acceptance of a request we sent. Returns `true` only if
|
||||
/// it advanced one of *our* outgoing requests to [`Accepted`]. An accept for
|
||||
/// any other state is ignored: a stranger's, or one for a peer still in
|
||||
/// [`PendingIncoming`] (their request, awaiting our decision) — honouring the
|
||||
/// latter would let a peer mark itself accepted without the local user's
|
||||
/// consent.
|
||||
///
|
||||
/// [`Accepted`]: FriendState::Accepted
|
||||
/// [`PendingIncoming`]: FriendState::PendingIncoming
|
||||
pub fn on_friend_accept(&mut self, id: EndpointId, name: String) -> bool {
|
||||
if matches!(
|
||||
self.find(&id).map(|f| f.state),
|
||||
Some(FriendState::PendingOutgoing)
|
||||
) {
|
||||
self.upsert(id, name, FriendState::Accepted);
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn sample_id() -> EndpointId {
|
||||
iroh::SecretKey::generate().public()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn round_trips_through_toml() {
|
||||
let mut store = FriendStore::default();
|
||||
store.upsert(sample_id(), "Alice".into(), FriendState::Accepted);
|
||||
store.upsert(sample_id(), "Bob".into(), FriendState::PendingIncoming);
|
||||
|
||||
let toml = toml::to_string_pretty(&store).unwrap();
|
||||
let back: FriendStore = toml::from_str(&toml).unwrap();
|
||||
assert_eq!(back.friends, store.friends);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn new_friends_default_to_shared_and_survive_round_trip() {
|
||||
let mut store = FriendStore::default();
|
||||
let id = sample_id();
|
||||
store.upsert(id, "Alice".into(), FriendState::Accepted);
|
||||
assert!(store.find(&id).unwrap().share, "new friends start shared");
|
||||
|
||||
// An older friends.toml predating the field loads as share-with-all.
|
||||
let toml = format!("[[friends]]\nid = \"{id}\"\nname = \"Legacy\"\nstate = \"accepted\"\n");
|
||||
let back: FriendStore = toml::from_str(&toml).unwrap();
|
||||
assert!(back.friends[0].share);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn upsert_preserves_share_across_refresh() {
|
||||
let mut store = FriendStore::default();
|
||||
let id = sample_id();
|
||||
store.upsert(id, "Alice".into(), FriendState::Accepted);
|
||||
store.find_mut(&id).unwrap().share = false;
|
||||
// A later name/presence refresh re-upserts the same peer; the share
|
||||
// choice must not be reset by it.
|
||||
store.upsert(id, "Alice (new name)".into(), FriendState::Accepted);
|
||||
assert!(!store.find(&id).unwrap().share);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn upsert_updates_in_place() {
|
||||
let mut store = FriendStore::default();
|
||||
let id = sample_id();
|
||||
store.upsert(id, "Old".into(), FriendState::PendingOutgoing);
|
||||
store.upsert(id, "New".into(), FriendState::Accepted);
|
||||
assert_eq!(store.friends.len(), 1);
|
||||
let f = store.find(&id).unwrap();
|
||||
assert_eq!(f.name, "New");
|
||||
assert_eq!(f.state, FriendState::Accepted);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn is_accepted_only_for_accepted_state() {
|
||||
let mut store = FriendStore::default();
|
||||
let pending = sample_id();
|
||||
let friend = sample_id();
|
||||
store.upsert(pending, "P".into(), FriendState::PendingOutgoing);
|
||||
store.upsert(friend, "F".into(), FriendState::Accepted);
|
||||
assert!(!store.is_accepted(&pending));
|
||||
assert!(store.is_accepted(&friend));
|
||||
assert!(!store.is_accepted(&sample_id()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn remove_reports_whether_present() {
|
||||
let mut store = FriendStore::default();
|
||||
let id = sample_id();
|
||||
store.upsert(id, "X".into(), FriendState::Accepted);
|
||||
assert!(store.remove(&id));
|
||||
assert!(!store.remove(&id));
|
||||
assert!(store.friends.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn incoming_request_from_stranger_is_pending() {
|
||||
let mut store = FriendStore::default();
|
||||
let id = sample_id();
|
||||
let mutual = store.on_friend_request(id, "Stranger".into());
|
||||
assert!(!mutual);
|
||||
assert_eq!(store.find(&id).unwrap().state, FriendState::PendingIncoming);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn incoming_request_matching_our_outgoing_is_mutual() {
|
||||
let mut store = FriendStore::default();
|
||||
let id = sample_id();
|
||||
// We asked them first…
|
||||
store.upsert(id, "Pal".into(), FriendState::PendingOutgoing);
|
||||
// …then their request arrives — that's a mutual match.
|
||||
let mutual = store.on_friend_request(id, "Pal".into());
|
||||
assert!(mutual);
|
||||
assert_eq!(store.find(&id).unwrap().state, FriendState::Accepted);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn accept_advances_known_peer_only() {
|
||||
let mut store = FriendStore::default();
|
||||
let known = sample_id();
|
||||
store.upsert(known, "Known".into(), FriendState::PendingOutgoing);
|
||||
assert!(store.on_friend_accept(known, "Known".into()));
|
||||
assert_eq!(store.find(&known).unwrap().state, FriendState::Accepted);
|
||||
// An accept from someone we never asked is ignored.
|
||||
let stranger = sample_id();
|
||||
assert!(!store.on_friend_accept(stranger, "Nope".into()));
|
||||
assert!(store.find(&stranger).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn accept_does_not_advance_a_pending_incoming_peer() {
|
||||
// They asked us and we haven't decided yet; an unsolicited FriendAccept
|
||||
// from them must not auto-accept on our behalf (consent bypass).
|
||||
let mut store = FriendStore::default();
|
||||
let id = sample_id();
|
||||
store.upsert(id, "Theirs".into(), FriendState::PendingIncoming);
|
||||
assert!(!store.on_friend_accept(id, "Theirs".into()));
|
||||
assert_eq!(store.find(&id).unwrap().state, FriendState::PendingIncoming);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn request_does_not_downgrade_an_accepted_friend() {
|
||||
// A current friend re-sending a request (e.g. after losing their store)
|
||||
// must stay accepted; the call signals a re-confirm rather than a
|
||||
// downgrade to pending.
|
||||
let mut store = FriendStore::default();
|
||||
let id = sample_id();
|
||||
store.upsert(id, "Pal".into(), FriendState::Accepted);
|
||||
let settled = store.on_friend_request(id, "Pal (reinstalled)".into());
|
||||
assert!(settled);
|
||||
assert_eq!(store.find(&id).unwrap().state, FriendState::Accepted);
|
||||
assert_eq!(store.find(&id).unwrap().name, "Pal (reinstalled)");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
//! Persistent node identity at `~/.config/pixelpass/identity.key`.
|
||||
//!
|
||||
//! Without this, [`super::endpoint::bind`] would let iroh mint a fresh random
|
||||
//! keypair on every launch, so a peer's `EndpointId` would change each run.
|
||||
//! The friends system identifies people by that id (it's the public key already
|
||||
//! embedded in every share code), so it must stay stable across launches — and
|
||||
//! across roles: the same machine gets the same id whether it's hosting,
|
||||
//! viewing, or just sitting in the GUI.
|
||||
//!
|
||||
//! The key is the ed25519 secret (32 bytes) stored as hex on its own line, in a
|
||||
//! `0600` file separate from `config.toml` — it's a secret, not a preference,
|
||||
//! and keeping it out of the TOML means a hand-edit or a config reset can't
|
||||
//! clobber your identity.
|
||||
|
||||
use anyhow::{Context, Result, bail};
|
||||
use iroh::SecretKey;
|
||||
use std::fs;
|
||||
use std::io::Write;
|
||||
use std::path::PathBuf;
|
||||
|
||||
/// Returns `~/.config/pixelpass/identity.key` (or the XDG equivalent). Shares
|
||||
/// the config directory with [`super::config`]; the parent is created on save.
|
||||
pub fn identity_path() -> Result<PathBuf> {
|
||||
Ok(super::config::config_path()?
|
||||
.parent()
|
||||
.context("config path has no parent directory")?
|
||||
.join("identity.key"))
|
||||
}
|
||||
|
||||
/// Load the persisted secret key, or generate-and-save one on first run.
|
||||
///
|
||||
/// A malformed file is a hard error rather than a silent regenerate: silently
|
||||
/// minting a new identity would orphan every friend who has the old id, so we'd
|
||||
/// rather fail loud and let the user notice (and decide) than lose it quietly.
|
||||
pub fn load_or_create() -> Result<SecretKey> {
|
||||
let path = identity_path()?;
|
||||
match fs::read_to_string(&path) {
|
||||
Ok(s) => parse_key(s.trim())
|
||||
.with_context(|| format!("failed to parse the identity key at {}", path.display())),
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
|
||||
let key = SecretKey::generate();
|
||||
save(&key)?;
|
||||
tracing::info!(id = %key.public(), "generated a new persistent identity");
|
||||
Ok(key)
|
||||
}
|
||||
Err(e) => Err(e).with_context(|| format!("failed to read {}", path.display())),
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_key(hex: &str) -> Result<SecretKey> {
|
||||
let bytes = decode_hex(hex)?;
|
||||
let arr: [u8; 32] = bytes
|
||||
.try_into()
|
||||
.map_err(|_| anyhow::anyhow!("identity key must be 32 bytes (64 hex chars)"))?;
|
||||
Ok(SecretKey::from_bytes(&arr))
|
||||
}
|
||||
|
||||
/// Atomic, `0600` write: tempfile-in-same-dir, chmod, then rename. Same
|
||||
/// approach as [`super::config::save`], but with restrictive perms applied
|
||||
/// before the rename so the secret is never briefly world-readable.
|
||||
pub fn save(key: &SecretKey) -> Result<()> {
|
||||
let path = identity_path()?;
|
||||
let parent = path
|
||||
.parent()
|
||||
.context("identity path has no parent directory")?;
|
||||
fs::create_dir_all(parent).with_context(|| format!("failed to create {}", parent.display()))?;
|
||||
|
||||
let tmp = parent.join(format!(".identity.key.tmp.{}", std::process::id()));
|
||||
{
|
||||
let mut f = fs::File::create(&tmp)
|
||||
.with_context(|| format!("failed to create {}", tmp.display()))?;
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
f.set_permissions(fs::Permissions::from_mode(0o600))
|
||||
.with_context(|| format!("failed to chmod {}", tmp.display()))?;
|
||||
}
|
||||
f.write_all(encode_hex(&key.to_bytes()).as_bytes())
|
||||
.with_context(|| format!("failed to write {}", tmp.display()))?;
|
||||
f.write_all(b"\n").ok();
|
||||
f.sync_all().ok();
|
||||
}
|
||||
fs::rename(&tmp, &path)
|
||||
.with_context(|| format!("failed to rename {} -> {}", tmp.display(), path.display()))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn encode_hex(bytes: &[u8]) -> String {
|
||||
let mut s = String::with_capacity(bytes.len() * 2);
|
||||
for b in bytes {
|
||||
s.push_str(&format!("{b:02x}"));
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
fn decode_hex(s: &str) -> Result<Vec<u8>> {
|
||||
if !s.len().is_multiple_of(2) {
|
||||
bail!("hex string has an odd length");
|
||||
}
|
||||
(0..s.len())
|
||||
.step_by(2)
|
||||
.map(|i| {
|
||||
u8::from_str_radix(&s[i..i + 2], 16)
|
||||
.with_context(|| format!("invalid hex byte at offset {i}"))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn hex_round_trips() {
|
||||
let bytes: Vec<u8> = (0u8..=255).collect();
|
||||
let encoded = encode_hex(&bytes);
|
||||
assert_eq!(encoded.len(), bytes.len() * 2);
|
||||
assert_eq!(decode_hex(&encoded).unwrap(), bytes);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn key_round_trips_through_hex() {
|
||||
let key = SecretKey::generate();
|
||||
let hex = encode_hex(&key.to_bytes());
|
||||
let parsed = parse_key(&hex).unwrap();
|
||||
assert_eq!(parsed.to_bytes(), key.to_bytes());
|
||||
assert_eq!(parsed.public(), key.public());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_wrong_length() {
|
||||
assert!(parse_key("dead").is_err());
|
||||
assert!(parse_key("").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_odd_and_nonhex() {
|
||||
assert!(decode_hex("abc").is_err());
|
||||
assert!(decode_hex("zz").is_err());
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,19 @@
|
||||
pub mod alpn;
|
||||
pub mod bandwidth;
|
||||
pub mod config;
|
||||
// The friends stack (persistent identity + control plane) is GUI-only — a
|
||||
// headless CLI host runs no presence service — so it's gated with the feature
|
||||
// that pulls the rest of the GUI, keeping the headless build lean.
|
||||
#[cfg(feature = "gui")]
|
||||
pub mod control;
|
||||
pub mod deps;
|
||||
pub mod display;
|
||||
pub mod endpoint;
|
||||
#[cfg(feature = "gui")]
|
||||
pub mod friends;
|
||||
#[cfg(feature = "gui")]
|
||||
pub mod identity;
|
||||
pub mod output;
|
||||
pub mod process;
|
||||
pub mod signal;
|
||||
pub mod tunnel;
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
//! Machine-readable event stream for non-interactive front-ends.
|
||||
//!
|
||||
//! When enabled with `--output json`, the host and viewer emit one JSON
|
||||
//! object per line on **stdout**. The human banner and `tracing` logs stay
|
||||
//! on **stderr**, so the two streams never interleave and a parser reading
|
||||
//! stdout sees only events. Each line is flushed immediately so a front-end
|
||||
//! reading the pipe gets events live rather than in block-buffered chunks.
|
||||
//!
|
||||
//! This is the shell-out counterpart to an in-process event channel: the
|
||||
//! `--gui` front-end re-execs this binary as `pixelpass --host --output json`
|
||||
//! and parses these lines to drive its window.
|
||||
|
||||
use std::io::Write;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
|
||||
use serde::Serialize;
|
||||
|
||||
static JSON_ENABLED: AtomicBool = AtomicBool::new(false);
|
||||
|
||||
/// Turn JSON event output on. Called once at startup from `--output json`.
|
||||
pub fn set_json(enabled: bool) {
|
||||
JSON_ENABLED.store(enabled, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
/// Whether the JSON event stream is on — i.e. we're being driven by a
|
||||
/// machine front-end (the `--gui` shell-out) rather than a human terminal.
|
||||
/// Gates features that only make sense under that front-end, like the
|
||||
/// stdin command channel the host reads `kick` requests from.
|
||||
pub fn json_enabled() -> bool {
|
||||
JSON_ENABLED.load(Ordering::Relaxed)
|
||||
}
|
||||
|
||||
/// One event in the stdout stream. Serialized as `{"event":"<tag>", ...}`.
|
||||
#[derive(Serialize)]
|
||||
#[serde(tag = "event", rename_all = "snake_case")]
|
||||
pub enum Event<'a> {
|
||||
/// The relay-only ticket the viewer needs. Emitted once at host startup.
|
||||
Ticket { value: &'a str },
|
||||
/// One-shot host configuration summary, mirroring the banner fields.
|
||||
HostInfo {
|
||||
display_server: &'a str,
|
||||
capture: &'a str,
|
||||
quality: &'a str,
|
||||
dimensions: &'a str,
|
||||
hw_encode: bool,
|
||||
max_viewers: u32,
|
||||
max_viewers_source: &'a str,
|
||||
},
|
||||
/// A viewer joined. `id` is the viewer's endpoint id; `active` is the new
|
||||
/// total after the join.
|
||||
ViewerJoined { id: &'a str, active: u32, max: u32 },
|
||||
/// A viewer left — disconnected on their own or kicked by the host. `id`
|
||||
/// is the viewer's endpoint id; `active` is the new total after.
|
||||
ViewerLeft { id: &'a str, active: u32, max: u32 },
|
||||
/// Capture pipeline lifecycle (spawned on first viewer, torn down on last).
|
||||
Capture { state: CaptureState },
|
||||
/// A viewer was turned away (host full, or capture spawn failed).
|
||||
ViewerRefused { reason: &'a str },
|
||||
/// Viewer-side: the local player URL is ready to open.
|
||||
Connected { url: &'a str },
|
||||
/// Per-app audio routing state (only emitted when `--app` is set). `routed`
|
||||
/// = the chosen app's audio is now reaching viewers; `lost` = its last
|
||||
/// stream went away. Under `--strict-audio`, `lost` means viewers currently
|
||||
/// hear silence; without it, viewers fall back to whole-desktop audio.
|
||||
AppAudio { state: AppAudioState },
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum CaptureState {
|
||||
Started,
|
||||
Stopped,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Clone, Copy, Debug, PartialEq, Eq)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum AppAudioState {
|
||||
Routed,
|
||||
Lost,
|
||||
}
|
||||
|
||||
/// Emit one event as a JSON line on stdout, flushed. No-op unless JSON
|
||||
/// output was enabled with [`set_json`], so call sites can sprinkle these
|
||||
/// unconditionally without branching.
|
||||
pub fn emit(event: Event) {
|
||||
if !json_enabled() {
|
||||
return;
|
||||
}
|
||||
match serde_json::to_string(&event) {
|
||||
Ok(line) => {
|
||||
let mut out = std::io::stdout().lock();
|
||||
// Best-effort: a closed pipe (front-end gone) shouldn't crash the
|
||||
// host — it keeps streaming to any viewers already connected.
|
||||
let _ = writeln!(out, "{line}");
|
||||
let _ = out.flush();
|
||||
}
|
||||
Err(e) => tracing::warn!("failed to serialize event: {e}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
// The app_audio event is the wire contract peerspeak parses to drive its
|
||||
// echo warning; pin the exact shape so a rename here is caught here.
|
||||
#[test]
|
||||
fn app_audio_event_wire_shape() {
|
||||
let routed = serde_json::to_string(&Event::AppAudio {
|
||||
state: AppAudioState::Routed,
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(routed, r#"{"event":"app_audio","state":"routed"}"#);
|
||||
|
||||
let lost = serde_json::to_string(&Event::AppAudio {
|
||||
state: AppAudioState::Lost,
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(lost, r#"{"event":"app_audio","state":"lost"}"#);
|
||||
}
|
||||
}
|
||||
+18
-5
@@ -6,10 +6,19 @@ use std::process::{Command, Stdio};
|
||||
///
|
||||
/// The child gets its own session via `setsid(2)` and null stdio, so it
|
||||
/// survives the parent exiting and doesn't take a SIGKILL cascade when
|
||||
/// pixelpass dies. The `Child` is dropped immediately — `std::process::Child::drop`
|
||||
/// does not kill the process on Unix.
|
||||
/// pixelpass dies.
|
||||
///
|
||||
/// A detached reaper thread `wait()`s the child so it doesn't linger as a
|
||||
/// `<defunct>` zombie under a long-lived parent — the `--gui` front-end launches
|
||||
/// players itself and lives for the whole session, and `std::process::Child`
|
||||
/// (unlike tokio's) has no orphan reaping, so simply dropping the handle would
|
||||
/// leak a zombie per closed player. If the parent exits while the player is
|
||||
/// still up, the reaper thread dies with it but the `setsid`'d player survives
|
||||
/// and is reaped by init. (A double-fork would also avoid the zombie, but
|
||||
/// `fork(2)` followed by non-trivial work in this multithreaded process is
|
||||
/// unsound — the reaper thread is the safe equivalent.)
|
||||
pub fn spawn_detached(prog: &str, args: &[&str]) -> io::Result<()> {
|
||||
unsafe {
|
||||
let child = unsafe {
|
||||
Command::new(prog)
|
||||
.args(args)
|
||||
.stdin(Stdio::null())
|
||||
@@ -19,7 +28,11 @@ pub fn spawn_detached(prog: &str, args: &[&str]) -> io::Result<()> {
|
||||
nix::unistd::setsid().ok();
|
||||
Ok(())
|
||||
})
|
||||
.spawn()?;
|
||||
}
|
||||
.spawn()?
|
||||
};
|
||||
std::thread::spawn(move || {
|
||||
let mut child = child;
|
||||
let _ = child.wait();
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
|
||||
+10
-3
@@ -7,10 +7,17 @@ pub fn install_ctrl_c() -> CancellationToken {
|
||||
let token = CancellationToken::new();
|
||||
let trigger = token.clone();
|
||||
tokio::spawn(async move {
|
||||
if tokio::signal::ctrl_c().await.is_ok() {
|
||||
tracing::info!("ctrl-c received, shutting down");
|
||||
trigger.cancel();
|
||||
if let Err(e) = tokio::signal::ctrl_c().await {
|
||||
// Installing the handler failed — ctrl-c won't trigger a graceful
|
||||
// shutdown. Say so instead of failing silently; the user can still
|
||||
// kill the process, and the second-ctrl-c arm below would only fail
|
||||
// the same way, so bail out of the task.
|
||||
tracing::warn!("could not install ctrl-c handler: {e}; ctrl-c won't shut down cleanly");
|
||||
return;
|
||||
}
|
||||
tracing::info!("ctrl-c received, shutting down");
|
||||
trigger.cancel();
|
||||
|
||||
if tokio::signal::ctrl_c().await.is_ok() {
|
||||
tracing::warn!("second ctrl-c — exiting now");
|
||||
std::process::exit(130);
|
||||
|
||||
+621
@@ -0,0 +1,621 @@
|
||||
//! `pixelpass doctor` — environment diagnostics.
|
||||
//!
|
||||
//! Screen-share failures are usually not pixelpass bugs but environment gaps:
|
||||
//! a missing GStreamer plugin, an X vs. Wayland mismatch, or — the common one —
|
||||
//! a GPU/driver with no working VA-API H.264 encoder, so the default
|
||||
//! `vah264enc` pipeline never produces a byte and the viewer "can't connect."
|
||||
//! `doctor` probes all of that up front and prints one actionable report, so a
|
||||
//! remote tester can read it over a call instead of us guessing from logs. It
|
||||
//! also validates any X11/Wayland test environment we stand up.
|
||||
//!
|
||||
//! Unlike [`crate::common::deps::check_host_binaries`], which bails on the first
|
||||
//! missing dependency, doctor runs *every* check and reports them together — a
|
||||
//! diagnostic wants the whole picture, not the first failure.
|
||||
|
||||
use anyhow::Result;
|
||||
use std::time::Duration;
|
||||
|
||||
use crate::common::deps;
|
||||
use crate::common::display::DisplayServer;
|
||||
use crate::common::endpoint;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Status {
|
||||
/// Working as needed.
|
||||
Ok,
|
||||
/// Degraded but not fatal (e.g. a fallback path is available).
|
||||
Warn,
|
||||
/// Screen-sharing will not work until this is fixed.
|
||||
Fail,
|
||||
/// Neutral fact, no judgement.
|
||||
Info,
|
||||
}
|
||||
|
||||
impl Status {
|
||||
fn icon(self) -> char {
|
||||
match self {
|
||||
Self::Ok => '✓',
|
||||
Self::Warn => '!',
|
||||
Self::Fail => '✗',
|
||||
Self::Info => '·',
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One line in the report: a status, a short label, a detail, and an optional
|
||||
/// remediation hint printed on its own indented line.
|
||||
pub struct Check {
|
||||
pub status: Status,
|
||||
pub label: String,
|
||||
pub detail: String,
|
||||
pub hint: Option<String>,
|
||||
}
|
||||
|
||||
impl Check {
|
||||
fn new(status: Status, label: impl Into<String>, detail: impl Into<String>) -> Self {
|
||||
Self {
|
||||
status,
|
||||
label: label.into(),
|
||||
detail: detail.into(),
|
||||
hint: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn ok(label: impl Into<String>, detail: impl Into<String>) -> Self {
|
||||
Self::new(Status::Ok, label, detail)
|
||||
}
|
||||
fn warn(label: impl Into<String>, detail: impl Into<String>) -> Self {
|
||||
Self::new(Status::Warn, label, detail)
|
||||
}
|
||||
fn fail(label: impl Into<String>, detail: impl Into<String>) -> Self {
|
||||
Self::new(Status::Fail, label, detail)
|
||||
}
|
||||
fn info(label: impl Into<String>, detail: impl Into<String>) -> Self {
|
||||
Self::new(Status::Info, label, detail)
|
||||
}
|
||||
|
||||
fn with_hint(mut self, hint: impl Into<String>) -> Self {
|
||||
self.hint = Some(hint.into());
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
/// Tally of the non-trivial statuses across every section.
|
||||
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct Summary {
|
||||
pub fails: usize,
|
||||
pub warns: usize,
|
||||
}
|
||||
|
||||
/// A named group of checks, printed under a header.
|
||||
struct Section {
|
||||
name: &'static str,
|
||||
checks: Vec<Check>,
|
||||
}
|
||||
|
||||
/// Run all diagnostics and print the report. Always prints; the process exit
|
||||
/// code is non-zero only when a hard failure (a `Fail`) was found, so scripts
|
||||
/// and CI can gate on it while a human still sees everything.
|
||||
pub async fn run(relay: Option<String>) -> Result<()> {
|
||||
let display = DisplayServer::detect();
|
||||
|
||||
let sections = vec![
|
||||
system_section(display),
|
||||
capture_section(display),
|
||||
encode_section(),
|
||||
mux_audio_section(),
|
||||
viewer_section(),
|
||||
network_section(relay.as_deref()).await,
|
||||
];
|
||||
|
||||
print_report(§ions);
|
||||
|
||||
let summary = summarize(sections.iter().flat_map(|s| s.checks.iter()));
|
||||
print_summary(summary, §ions);
|
||||
|
||||
if summary.fails > 0 {
|
||||
std::process::exit(1);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// ── sections ──────────────────────────────────────────────────────────────
|
||||
|
||||
fn system_section(display: DisplayServer) -> Section {
|
||||
let mut checks = vec![
|
||||
Check::info(
|
||||
"pixelpass",
|
||||
format!("{} (gui: {})", env!("CARGO_PKG_VERSION"), gui_built()),
|
||||
),
|
||||
Check::info("distro", distro_detail()),
|
||||
display_check(display),
|
||||
];
|
||||
|
||||
// Probe the actual X server when one is reachable — this is where an xlibre
|
||||
// vs. Xorg difference (the thing we most want to see on a tester's box)
|
||||
// shows up. Skip it on a pure Wayland session with no X at all.
|
||||
if display == DisplayServer::X11 || std::env::var_os("DISPLAY").is_some() {
|
||||
checks.push(x_server_check());
|
||||
}
|
||||
|
||||
Section {
|
||||
name: "System",
|
||||
checks,
|
||||
}
|
||||
}
|
||||
|
||||
fn capture_section(display: DisplayServer) -> Section {
|
||||
let mut checks = vec![
|
||||
bin_check("gst-launch-1.0", "gstreamer tools"),
|
||||
bin_check("gst-inspect-1.0", "gstreamer tools"),
|
||||
];
|
||||
|
||||
match display {
|
||||
DisplayServer::Wayland => {
|
||||
checks.push(gst_check("pipewiresrc", "Wayland capture"));
|
||||
}
|
||||
DisplayServer::X11 => {
|
||||
checks.push(gst_check("ximagesrc", "X11 capture"));
|
||||
checks.push(match deps::which("xwininfo") {
|
||||
Some(p) => Check::ok("window picker", p.display().to_string())
|
||||
.with_hint("needed only for `--window` (share a single window)"),
|
||||
None => Check::info("window picker", "xwininfo not found")
|
||||
.with_hint("optional — only `--window` needs it"),
|
||||
});
|
||||
}
|
||||
DisplayServer::Unknown => {
|
||||
checks.push(
|
||||
Check::info("capture backend", "unknown — cannot probe a source element")
|
||||
.with_hint("force one with `--display-server x11|wayland` when hosting"),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Section {
|
||||
name: "Capture (host)",
|
||||
checks,
|
||||
}
|
||||
}
|
||||
|
||||
fn encode_section() -> Section {
|
||||
Section {
|
||||
name: "Encode",
|
||||
checks: vec![hardware_encode_check(), software_encode_check()],
|
||||
}
|
||||
}
|
||||
|
||||
/// The load-bearing check for the common "viewer can't connect" report: the
|
||||
/// default host pipeline uses `vah264enc`, which needs both the GStreamer VA
|
||||
/// plugin *and* a GPU/driver that actually exposes an H.264 encode entrypoint.
|
||||
/// A box with the plugin but no encode entrypoint (or no render node) produces
|
||||
/// no video — the exact silent failure `--no-hwencode` works around.
|
||||
fn hardware_encode_check() -> Check {
|
||||
if !deps::gst_element_exists("vah264enc") {
|
||||
return Check::warn("hardware H.264", "vah264enc plugin not installed")
|
||||
.with_hint(format!(
|
||||
"{} — or just host with `--no-hwencode` (software x264)",
|
||||
deps::install_hint_for_gst_element("vah264enc")
|
||||
));
|
||||
}
|
||||
|
||||
if !has_render_node() {
|
||||
return Check::warn(
|
||||
"hardware H.264",
|
||||
"vah264enc present, but no DRM render node (/dev/dri/renderD*)",
|
||||
)
|
||||
.with_hint("GPU encode is unavailable here — host with `--no-hwencode`");
|
||||
}
|
||||
|
||||
match vainfo_output() {
|
||||
Some(out) if vainfo_has_h264_encode(&out) => {
|
||||
Check::ok("hardware H.264", "VA-API H.264 encode available (vah264enc)")
|
||||
}
|
||||
Some(_) => Check::warn(
|
||||
"hardware H.264",
|
||||
"vah264enc present, but VA-API reports no H.264 encode entrypoint",
|
||||
)
|
||||
.with_hint("this GPU/driver can't hardware-encode H.264 — host with `--no-hwencode`"),
|
||||
None => Check::info(
|
||||
"hardware H.264",
|
||||
"vah264enc + render node present; couldn't confirm the VA-API encode entrypoint",
|
||||
)
|
||||
.with_hint("install `vainfo` (libva-utils) to verify, or just test a real host session"),
|
||||
}
|
||||
}
|
||||
|
||||
fn software_encode_check() -> Check {
|
||||
if deps::gst_element_exists("x264enc") {
|
||||
Check::ok("software H.264", "x264enc available (`--no-hwencode`)")
|
||||
} else {
|
||||
Check::warn("software H.264", "x264enc not installed").with_hint(format!(
|
||||
"{} — the fallback for GPUs without VA-API H.264 encode",
|
||||
deps::install_hint_for_gst_element("x264enc")
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
fn mux_audio_section() -> Section {
|
||||
// These live in plugins-bad/-good/-libav and plugins-base; all are required
|
||||
// for either backend, so a miss here is a hard Fail.
|
||||
let tail = ["h264parse", "mpegtsmux", "aacparse", "avenc_aac", "pulsesrc", "videoscale"];
|
||||
let missing: Vec<&str> = tail.iter().copied().filter(|e| !deps::gst_element_exists(e)).collect();
|
||||
|
||||
let tail_check = if missing.is_empty() {
|
||||
Check::ok("mux + audio tail", tail.join(", "))
|
||||
} else {
|
||||
Check::fail("mux + audio tail", format!("missing: {}", missing.join(", "))).with_hint(
|
||||
deps::install_hint_for_gst_element(missing[0]),
|
||||
)
|
||||
};
|
||||
|
||||
Section {
|
||||
name: "Mux / audio",
|
||||
checks: vec![tail_check, bin_check("pactl", "pactl")],
|
||||
}
|
||||
}
|
||||
|
||||
fn viewer_section() -> Section {
|
||||
let mpv = deps::which("mpv");
|
||||
let vlc = deps::which("vlc");
|
||||
|
||||
let check = match (mpv, vlc) {
|
||||
(Some(p), _) => Check::ok("player", format!("mpv ({})", p.display())),
|
||||
(None, Some(p)) => Check::ok("player", format!("vlc ({})", p.display()))
|
||||
.with_hint("mpv is the recommended player; vlc needs the dvb + ffmpeg plugins"),
|
||||
(None, None) => Check::warn("player", "neither mpv nor vlc found")
|
||||
.with_hint("a viewer needs one of them; the GUI launches mpv by default"),
|
||||
};
|
||||
|
||||
Section {
|
||||
name: "Viewer",
|
||||
checks: vec![check],
|
||||
}
|
||||
}
|
||||
|
||||
/// Bind a real video-plane endpoint and wait briefly for a relay, mirroring
|
||||
/// what a host does. Directly relevant to "couldn't connect": if this machine
|
||||
/// can't reach a relay, hole-punching to a peer is unlikely to work either.
|
||||
async fn network_section(relay: Option<&str>) -> Section {
|
||||
let check = match endpoint::bind(relay).await {
|
||||
Ok(ep) => {
|
||||
let online = tokio::time::timeout(Duration::from_secs(8), ep.online()).await.is_ok();
|
||||
let relay_count = ep.addr().addrs.iter().filter(|a| a.is_relay()).count();
|
||||
let where_ = relay.map(|r| format!(" ({r})")).unwrap_or_default();
|
||||
// Close gracefully so iroh doesn't log a scary "Endpoint dropped
|
||||
// without calling close" error into the middle of the report.
|
||||
ep.close().await;
|
||||
|
||||
if online && relay_count > 0 {
|
||||
Check::ok("relay", format!("home relay reachable{where_}"))
|
||||
} else if online {
|
||||
Check::warn("relay", format!("endpoint online but no relay address{where_}"))
|
||||
.with_hint("n0 DNS discovery may still connect peers, but relay fallback is degraded")
|
||||
} else {
|
||||
Check::warn("relay", format!("no relay connected within 8s{where_}"))
|
||||
.with_hint("check connectivity/firewall; peers behind NAT rely on the relay to rendezvous")
|
||||
}
|
||||
}
|
||||
Err(e) => Check::fail("relay", format!("could not bind endpoint: {e}")),
|
||||
};
|
||||
|
||||
Section {
|
||||
name: "Network",
|
||||
checks: vec![check],
|
||||
}
|
||||
}
|
||||
|
||||
// ── small check builders ────────────────────────────────────────────────────
|
||||
|
||||
fn bin_check(bin: &str, label: &str) -> Check {
|
||||
match deps::which(bin) {
|
||||
Some(p) => Check::ok(label, format!("{bin} ({})", p.display())),
|
||||
None => Check::fail(label, format!("{bin} not found on PATH"))
|
||||
.with_hint(deps::install_hint_for_bin(bin)),
|
||||
}
|
||||
}
|
||||
|
||||
fn gst_check(element: &str, label: &str) -> Check {
|
||||
if deps::gst_element_exists(element) {
|
||||
Check::ok(label, element.to_string())
|
||||
} else {
|
||||
Check::fail(label, format!("GStreamer element `{element}` not available"))
|
||||
.with_hint(deps::install_hint_for_gst_element(element))
|
||||
}
|
||||
}
|
||||
|
||||
fn display_check(display: DisplayServer) -> Check {
|
||||
let env = display_env_summary();
|
||||
match display {
|
||||
DisplayServer::Wayland => Check::ok("display server", format!("Wayland ({env})")),
|
||||
DisplayServer::X11 => Check::ok("display server", format!("X11 ({env})")),
|
||||
DisplayServer::Unknown => Check::fail("display server", format!("undetected ({env})"))
|
||||
.with_hint(
|
||||
"no WAYLAND_DISPLAY/DISPLAY/XDG_SESSION_TYPE — capture can't start; \
|
||||
run inside a graphical session or pass `--display-server`",
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
/// Connect to the X server and report its vendor + version. This is how an
|
||||
/// xlibre server distinguishes itself from stock Xorg (vendor string / release
|
||||
/// number), which is exactly what we want to see on a tester's machine.
|
||||
fn x_server_check() -> Check {
|
||||
use x11rb::connection::Connection;
|
||||
match x11rb::connect(None) {
|
||||
Ok((conn, _screen)) => {
|
||||
let setup = conn.setup();
|
||||
let vendor = String::from_utf8_lossy(&setup.vendor);
|
||||
let detail = format!(
|
||||
"vendor \"{}\", protocol {}.{}, release {}",
|
||||
vendor.trim(),
|
||||
setup.protocol_major_version,
|
||||
setup.protocol_minor_version,
|
||||
setup.release_number,
|
||||
);
|
||||
let label = "X server";
|
||||
if vendor.to_lowercase().contains("xlibre") {
|
||||
Check::info(label, format!("XLibre — {detail}"))
|
||||
} else {
|
||||
Check::info(label, detail)
|
||||
}
|
||||
}
|
||||
Err(_) => Check::info("X server", "DISPLAY set but the X server is unreachable"),
|
||||
}
|
||||
}
|
||||
|
||||
// ── environment helpers ─────────────────────────────────────────────────────
|
||||
|
||||
fn gui_built() -> &'static str {
|
||||
if cfg!(feature = "gui") { "yes" } else { "no" }
|
||||
}
|
||||
|
||||
fn distro_detail() -> String {
|
||||
let id = deps::detect_distro();
|
||||
let pretty = os_release_field("PRETTY_NAME");
|
||||
match (id, pretty) {
|
||||
(Some(id), Some(p)) => format!("{id} ({p})"),
|
||||
(Some(id), None) => id,
|
||||
(None, Some(p)) => p,
|
||||
(None, None) => "unknown".to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
fn os_release_field(key: &str) -> Option<String> {
|
||||
let contents = std::fs::read_to_string("/etc/os-release").ok()?;
|
||||
for line in contents.lines() {
|
||||
if let Some(rest) = line.strip_prefix(&format!("{key}=")) {
|
||||
return Some(rest.trim_matches('"').to_string());
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn display_env_summary() -> String {
|
||||
let mut parts = Vec::new();
|
||||
for var in ["WAYLAND_DISPLAY", "DISPLAY", "XDG_SESSION_TYPE", "XDG_CURRENT_DESKTOP"] {
|
||||
if let Some(v) = std::env::var_os(var) {
|
||||
parts.push(format!("{var}={}", v.to_string_lossy()));
|
||||
}
|
||||
}
|
||||
if parts.is_empty() {
|
||||
"no display env vars set".to_string()
|
||||
} else {
|
||||
parts.join(", ")
|
||||
}
|
||||
}
|
||||
|
||||
fn has_render_node() -> bool {
|
||||
let Ok(entries) = std::fs::read_dir("/dev/dri") else {
|
||||
return false;
|
||||
};
|
||||
entries.flatten().any(|e| {
|
||||
e.file_name()
|
||||
.to_string_lossy()
|
||||
.starts_with("renderD")
|
||||
})
|
||||
}
|
||||
|
||||
fn vainfo_output() -> Option<String> {
|
||||
deps::which("vainfo")?;
|
||||
let out = std::process::Command::new("vainfo").output().ok()?;
|
||||
// vainfo prints its profile/entrypoint table to stdout; some builds also
|
||||
// spill driver banners to stderr. Concatenate both so parsing is robust.
|
||||
let mut s = String::from_utf8_lossy(&out.stdout).into_owned();
|
||||
s.push_str(&String::from_utf8_lossy(&out.stderr));
|
||||
Some(s)
|
||||
}
|
||||
|
||||
/// Pure: does a `vainfo` dump advertise an H.264 *encode* entrypoint? vainfo
|
||||
/// lists one `VAProfile… : VAEntrypoint…` pair per line; hardware H.264 encode
|
||||
/// is any `VAProfileH264*` profile paired with an `EncSlice`/`EncSliceLP`
|
||||
/// entrypoint. VLD-only H.264 (decode) does not count.
|
||||
fn vainfo_has_h264_encode(output: &str) -> bool {
|
||||
output.lines().any(|line| {
|
||||
line.contains("VAProfileH264")
|
||||
&& (line.contains("VAEntrypointEncSlice") || line.contains("VAEntrypointEncSliceLP"))
|
||||
})
|
||||
}
|
||||
|
||||
// ── reporting ───────────────────────────────────────────────────────────────
|
||||
|
||||
fn print_report(sections: &[Section]) {
|
||||
println!("pixelpass doctor\n");
|
||||
for section in sections {
|
||||
println!("{}", section.name);
|
||||
for check in §ion.checks {
|
||||
println!(
|
||||
" {} {:<16} {}",
|
||||
check.status.icon(),
|
||||
check.label,
|
||||
check.detail
|
||||
);
|
||||
if let Some(hint) = &check.hint {
|
||||
println!(" → {hint}");
|
||||
}
|
||||
}
|
||||
println!();
|
||||
}
|
||||
}
|
||||
|
||||
fn summarize<'a>(checks: impl Iterator<Item = &'a Check>) -> Summary {
|
||||
let mut summary = Summary::default();
|
||||
for check in checks {
|
||||
match check.status {
|
||||
Status::Fail => summary.fails += 1,
|
||||
Status::Warn => summary.warns += 1,
|
||||
Status::Ok | Status::Info => {}
|
||||
}
|
||||
}
|
||||
summary
|
||||
}
|
||||
|
||||
fn print_summary(summary: Summary, sections: &[Section]) {
|
||||
let hosting = hosting_verdict(sections);
|
||||
let counts = match (summary.fails, summary.warns) {
|
||||
(0, 0) => "all checks passed".to_string(),
|
||||
(0, w) => format!("{w} warning{}", plural(w)),
|
||||
(f, 0) => format!("{f} failure{}", plural(f)),
|
||||
(f, w) => format!("{f} failure{}, {w} warning{}", plural(f), plural(w)),
|
||||
};
|
||||
println!("Summary: {counts}. {hosting}");
|
||||
}
|
||||
|
||||
fn plural(n: usize) -> &'static str {
|
||||
if n == 1 { "" } else { "s" }
|
||||
}
|
||||
|
||||
/// A one-line verdict on whether this box can host, and how. Reads the actual
|
||||
/// encode + capture checks rather than the raw tally so the advice is specific.
|
||||
fn hosting_verdict(sections: &[Section]) -> String {
|
||||
let find = |section: &str, label: &str| -> Option<Status> {
|
||||
sections
|
||||
.iter()
|
||||
.find(|s| s.name == section)?
|
||||
.checks
|
||||
.iter()
|
||||
.find(|c| c.label == label)
|
||||
.map(|c| c.status)
|
||||
};
|
||||
|
||||
let hw = find("Encode", "hardware H.264");
|
||||
let sw_ok = find("Encode", "software H.264") == Some(Status::Ok);
|
||||
let capture_broken = sections
|
||||
.iter()
|
||||
.find(|s| s.name == "Capture (host)")
|
||||
.map(|s| s.checks.iter().any(|c| c.status == Status::Fail))
|
||||
.unwrap_or(false);
|
||||
|
||||
if capture_broken {
|
||||
"Hosting will fail: the capture backend is incomplete (see Capture above).".to_string()
|
||||
} else if hw == Some(Status::Ok) {
|
||||
"Hosting will work (hardware H.264 encode).".to_string()
|
||||
} else if hw == Some(Status::Info) && sw_ok {
|
||||
// Plugin + render node present but VA-API unverified (no vainfo): the
|
||||
// default encoder is likely fine; `--no-hwencode` is the safe fallback.
|
||||
"Hosting should work (hardware H.264 likely; `--no-hwencode` is the fallback).".to_string()
|
||||
} else if sw_ok {
|
||||
"Hosting should work with `--no-hwencode` (software H.264 encode).".to_string()
|
||||
} else {
|
||||
"Hosting may fail: no working H.264 encoder found (see Encode above).".to_string()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn vainfo_detects_h264_encode_entrypoint() {
|
||||
// Realistic AMD/RADV-style dump: H.264 has both decode (VLD) and encode.
|
||||
let dump = "\
|
||||
VAProfileH264Main : VAEntrypointVLD
|
||||
VAProfileH264Main : VAEntrypointEncSlice
|
||||
VAProfileH264High : VAEntrypointVLD
|
||||
VAProfileHEVCMain : VAEntrypointEncSlice";
|
||||
assert!(vainfo_has_h264_encode(dump));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vainfo_low_power_encode_counts() {
|
||||
let dump = "VAProfileH264ConstrainedBaseline: VAEntrypointEncSliceLP";
|
||||
assert!(vainfo_has_h264_encode(dump));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vainfo_decode_only_h264_is_not_encode() {
|
||||
// Decode-only H.264 (VLD) plus HEVC encode must NOT be read as H.264
|
||||
// encode — this is exactly the "default encoder fails" case.
|
||||
let dump = "\
|
||||
VAProfileH264Main : VAEntrypointVLD
|
||||
VAProfileH264High : VAEntrypointVLD
|
||||
VAProfileHEVCMain : VAEntrypointEncSlice";
|
||||
assert!(!vainfo_has_h264_encode(dump));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vainfo_empty_is_not_encode() {
|
||||
assert!(!vainfo_has_h264_encode(""));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn summarize_counts_fails_and_warns_only() {
|
||||
let checks = vec![
|
||||
Check::ok("a", "x"),
|
||||
Check::info("b", "x"),
|
||||
Check::warn("c", "x"),
|
||||
Check::warn("d", "x"),
|
||||
Check::fail("e", "x"),
|
||||
];
|
||||
let summary = summarize(checks.iter());
|
||||
assert_eq!(summary, Summary { fails: 1, warns: 2 });
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hosting_verdict_prefers_hardware_then_software() {
|
||||
let hw = vec![Section {
|
||||
name: "Encode",
|
||||
checks: vec![
|
||||
Check::ok("hardware H.264", "ok"),
|
||||
Check::ok("software H.264", "ok"),
|
||||
],
|
||||
}];
|
||||
assert!(hosting_verdict(&hw).contains("hardware"));
|
||||
|
||||
let sw = vec![Section {
|
||||
name: "Encode",
|
||||
checks: vec![
|
||||
Check::warn("hardware H.264", "no"),
|
||||
Check::ok("software H.264", "ok"),
|
||||
],
|
||||
}];
|
||||
assert!(sw_verdict_uses_no_hwencode(&hosting_verdict(&sw)));
|
||||
|
||||
let none = vec![Section {
|
||||
name: "Encode",
|
||||
checks: vec![
|
||||
Check::warn("hardware H.264", "no"),
|
||||
Check::warn("software H.264", "no"),
|
||||
],
|
||||
}];
|
||||
assert!(hosting_verdict(&none).contains("may fail"));
|
||||
}
|
||||
|
||||
fn sw_verdict_uses_no_hwencode(v: &str) -> bool {
|
||||
v.contains("--no-hwencode")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn capture_failure_dominates_verdict() {
|
||||
let sections = vec![
|
||||
Section {
|
||||
name: "Capture (host)",
|
||||
checks: vec![Check::fail("X11 capture", "missing")],
|
||||
},
|
||||
Section {
|
||||
name: "Encode",
|
||||
checks: vec![Check::ok("hardware H.264", "ok")],
|
||||
},
|
||||
];
|
||||
assert!(hosting_verdict(§ions).contains("capture"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,292 @@
|
||||
//! Drives a headless `pixelpass` child process for the GUI.
|
||||
//!
|
||||
//! The GUI re-execs this same binary (via [`std::env::current_exe`]) in
|
||||
//! headless mode with `--output json`, then reads the child's JSON event
|
||||
//! stream on a background thread and forwards parsed events over a channel the
|
||||
//! egui app drains each frame. stderr is captured into a small ring so a
|
||||
//! failed launch (e.g. a missing gst plugin) can be surfaced in the window.
|
||||
|
||||
use std::io::{BufRead, BufReader, Write};
|
||||
use std::process::{Child, ChildStdin, Command, Stdio};
|
||||
use std::sync::mpsc::Receiver;
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::Duration;
|
||||
|
||||
use nix::sys::signal::{Signal, kill};
|
||||
use nix::unistd::Pid;
|
||||
use serde::Deserialize;
|
||||
|
||||
use super::Waker;
|
||||
|
||||
/// One parsed event from the child's stdout. Owned mirror of
|
||||
/// [`crate::common::output::Event`] (which borrows for emit); kept separate so
|
||||
/// the wire format and the parser can evolve independently.
|
||||
#[derive(Deserialize, Debug)]
|
||||
#[serde(tag = "event", rename_all = "snake_case")]
|
||||
pub enum ChildEvent {
|
||||
Ticket {
|
||||
value: String,
|
||||
},
|
||||
HostInfo {
|
||||
display_server: String,
|
||||
capture: String,
|
||||
quality: String,
|
||||
dimensions: String,
|
||||
hw_encode: bool,
|
||||
max_viewers: u32,
|
||||
max_viewers_source: String,
|
||||
},
|
||||
ViewerJoined {
|
||||
id: String,
|
||||
active: u32,
|
||||
max: u32,
|
||||
},
|
||||
ViewerLeft {
|
||||
id: String,
|
||||
active: u32,
|
||||
max: u32,
|
||||
},
|
||||
Capture {
|
||||
state: CaptureState,
|
||||
},
|
||||
ViewerRefused {
|
||||
reason: String,
|
||||
},
|
||||
Connected {
|
||||
url: String,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Debug, Clone, Copy, PartialEq)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum CaptureState {
|
||||
Started,
|
||||
Stopped,
|
||||
}
|
||||
|
||||
const STDERR_TAIL_MAX: usize = 60;
|
||||
|
||||
pub struct ChildProc {
|
||||
/// `Some` while the child is owned here; `Drop` takes it to hand off to a
|
||||
/// detached reaper thread (see the `Drop` impl).
|
||||
child: Option<Child>,
|
||||
pub rx: Receiver<ChildEvent>,
|
||||
stderr_tail: Arc<Mutex<Vec<String>>>,
|
||||
/// Write end of the child's stdin, for the line-based command channel
|
||||
/// (see [`ChildProc::send_command`]). `None` once it's been closed.
|
||||
stdin: Option<ChildStdin>,
|
||||
}
|
||||
|
||||
impl ChildProc {
|
||||
/// Spawn `pixelpass <args>` as a child, wiring up the event reader. The
|
||||
/// `waker` is pinged whenever an event arrives so the UI thread wakes to
|
||||
/// drain it — this wakes the winit event loop directly (via an
|
||||
/// `EventLoopProxy`), so it works even when the window is hidden to the tray
|
||||
/// and no frames are running (egui's own repaint callback would not fire
|
||||
/// repeatedly in that idle state — see [`super::Waker`]).
|
||||
pub fn spawn(args: &[String], waker: Waker) -> std::io::Result<Self> {
|
||||
let exe = std::env::current_exe()?;
|
||||
let mut child = Command::new(exe)
|
||||
.args(args)
|
||||
// Piped so we can send line commands (e.g. `kick <id>`); the host
|
||||
// only reads it when driven this way (`--output json`).
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
.spawn()?;
|
||||
|
||||
let stdin = child.stdin.take();
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
let stdout = child.stdout.take().expect("stdout piped");
|
||||
std::thread::spawn(move || {
|
||||
let reader = BufReader::new(stdout);
|
||||
for line in reader.lines().map_while(Result::ok) {
|
||||
if line.trim().is_empty() {
|
||||
continue;
|
||||
}
|
||||
// Ignore any non-event line rather than dropping the stream.
|
||||
if let Ok(ev) = serde_json::from_str::<ChildEvent>(&line) {
|
||||
if tx.send(ev).is_err() {
|
||||
break; // app gone
|
||||
}
|
||||
waker.wake();
|
||||
}
|
||||
}
|
||||
// stdout closed → the child has exited (player closed, connection
|
||||
// ended, or a failed launch). Wake once more so the UI reaps it and
|
||||
// clears the "running" view, even if no final event was emitted and
|
||||
// the window is hidden to the tray.
|
||||
waker.wake();
|
||||
});
|
||||
|
||||
let stderr_tail = Arc::new(Mutex::new(Vec::<String>::new()));
|
||||
let stderr = child.stderr.take().expect("stderr piped");
|
||||
let tail = stderr_tail.clone();
|
||||
std::thread::spawn(move || {
|
||||
let reader = BufReader::new(stderr);
|
||||
for line in reader.lines().map_while(Result::ok) {
|
||||
let mut t = tail.lock().unwrap();
|
||||
t.push(line);
|
||||
let overflow = t.len().saturating_sub(STDERR_TAIL_MAX);
|
||||
if overflow > 0 {
|
||||
t.drain(0..overflow);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
Ok(Self {
|
||||
child: Some(child),
|
||||
rx,
|
||||
stderr_tail,
|
||||
stdin,
|
||||
})
|
||||
}
|
||||
|
||||
/// Send one newline-terminated command to the child over its stdin (the
|
||||
/// host parses these as `kick <endpoint-id>`). Best-effort: a closed pipe
|
||||
/// (child already gone) just drops the command.
|
||||
pub fn send_command(&mut self, cmd: &str) {
|
||||
let Some(stdin) = self.stdin.as_mut() else {
|
||||
return;
|
||||
};
|
||||
if let Err(e) = writeln!(stdin, "{cmd}") {
|
||||
tracing::warn!("failed to send command to host child: {e}");
|
||||
self.stdin = None; // pipe is dead; stop trying
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the child is still running.
|
||||
pub fn is_alive(&mut self) -> bool {
|
||||
matches!(self.child.as_mut().map(Child::try_wait), Some(Ok(None)))
|
||||
}
|
||||
|
||||
/// The last captured stderr lines, joined — for error display.
|
||||
pub fn stderr_tail(&self) -> String {
|
||||
self.stderr_tail.lock().unwrap().join("\n")
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for ChildProc {
|
||||
fn drop(&mut self) {
|
||||
// Leaving a host/viewer screen, or closing the window, must not orphan
|
||||
// a live child — but it must also not *block*. eframe runs this drop
|
||||
// synchronously while it destroys the window, so a grace-period wait
|
||||
// here freezes the window mid-close: the first click looks like it did
|
||||
// nothing (the stream just drops) and the window only goes away on a
|
||||
// second click. So SIGINT now — synchronously, so the host always gets
|
||||
// its ctrl-c teardown (capture down, endpoint closed) even if we exit
|
||||
// right after — then reap on a detached thread instead of waiting.
|
||||
let Some(mut child) = self.child.take() else {
|
||||
return;
|
||||
};
|
||||
if matches!(child.try_wait(), Ok(Some(_))) {
|
||||
return; // already exited; nothing to signal or reap
|
||||
}
|
||||
let _ = kill(Pid::from_raw(child.id() as i32), Signal::SIGINT);
|
||||
std::thread::spawn(move || {
|
||||
for _ in 0..40 {
|
||||
if matches!(child.try_wait(), Ok(Some(_))) {
|
||||
return;
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(50));
|
||||
}
|
||||
let _ = child.kill();
|
||||
let _ = child.wait();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::common::output::{CaptureState as EmitState, Event};
|
||||
|
||||
// The GUI parses what the headless child emits. These round-trip the
|
||||
// emitter's own types (`common::output::Event`) through the parser
|
||||
// (`ChildEvent`) so a rename on either side of the wire fails here rather
|
||||
// than silently breaking the GUI at runtime.
|
||||
fn parse(emit: Event) -> ChildEvent {
|
||||
let line = serde_json::to_string(&emit).unwrap();
|
||||
serde_json::from_str::<ChildEvent>(&line).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ticket_round_trips() {
|
||||
assert!(matches!(
|
||||
parse(Event::Ticket { value: "endpointXYZ" }),
|
||||
ChildEvent::Ticket { value } if value == "endpointXYZ"
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn host_info_round_trips() {
|
||||
let ev = parse(Event::HostInfo {
|
||||
display_server: "Wayland",
|
||||
capture: "fullscreen + system-audio",
|
||||
quality: "Medium",
|
||||
dimensions: "≤720p / 2500 kbps / 30 fps",
|
||||
hw_encode: true,
|
||||
max_viewers: 3,
|
||||
max_viewers_source: "user-specified",
|
||||
});
|
||||
match ev {
|
||||
ChildEvent::HostInfo {
|
||||
display_server,
|
||||
quality,
|
||||
hw_encode,
|
||||
max_viewers,
|
||||
..
|
||||
} => {
|
||||
assert_eq!(display_server, "Wayland");
|
||||
assert_eq!(quality, "Medium");
|
||||
assert!(hw_encode);
|
||||
assert_eq!(max_viewers, 3);
|
||||
}
|
||||
other => panic!("expected HostInfo, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn viewer_join_leave_round_trip() {
|
||||
assert!(matches!(
|
||||
parse(Event::ViewerJoined { id: "nodeXYZ", active: 2, max: 4 }),
|
||||
ChildEvent::ViewerJoined { id, active: 2, max: 4 } if id == "nodeXYZ"
|
||||
));
|
||||
assert!(matches!(
|
||||
parse(Event::ViewerLeft { id: "nodeXYZ", active: 1, max: 4 }),
|
||||
ChildEvent::ViewerLeft { id, active: 1, max: 4 } if id == "nodeXYZ"
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn capture_state_round_trips() {
|
||||
assert!(matches!(
|
||||
parse(Event::Capture {
|
||||
state: EmitState::Started
|
||||
}),
|
||||
ChildEvent::Capture {
|
||||
state: CaptureState::Started
|
||||
}
|
||||
));
|
||||
assert!(matches!(
|
||||
parse(Event::Capture {
|
||||
state: EmitState::Stopped
|
||||
}),
|
||||
ChildEvent::Capture {
|
||||
state: CaptureState::Stopped
|
||||
}
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refused_and_connected_round_trip() {
|
||||
assert!(matches!(
|
||||
parse(Event::ViewerRefused { reason: "host is full" }),
|
||||
ChildEvent::ViewerRefused { reason } if reason == "host is full"
|
||||
));
|
||||
assert!(matches!(
|
||||
parse(Event::Connected { url: "http://127.0.0.1:5000" }),
|
||||
ChildEvent::Connected { url } if url == "http://127.0.0.1:5000"
|
||||
));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
//! Share-code wrapping: carrying the host's stable friend id alongside the
|
||||
//! one-shot video ticket.
|
||||
//!
|
||||
//! A bare video ticket identifies only the host's *ephemeral* video endpoint,
|
||||
//! so two people who meet over one can't learn each other's stable friend id —
|
||||
//! the thing the friends system needs. The GUI host therefore wraps its ticket
|
||||
//! with its control-plane [`EndpointId`]; the viewer unwraps it, dials the
|
||||
//! video ticket as before, and now also knows who to befriend (and announces
|
||||
//! itself back over the control plane so the host learns the viewer in turn).
|
||||
//!
|
||||
//! Format: `pixelpassF1:<host-control-id>.<bare-ticket>`. Both the id and the
|
||||
//! ticket are base32 text with no `.`, so a single `.` separator is
|
||||
//! unambiguous. [`unwrap`] is lenient: anything without the prefix is treated
|
||||
//! as a bare ticket, so a plain CLI ticket pasted into the GUI still works (it
|
||||
//! just offers no friend option). The host name isn't carried here — the
|
||||
//! viewer's announcement triggers a name exchange over the control plane.
|
||||
|
||||
use std::str::FromStr;
|
||||
|
||||
use iroh::EndpointId;
|
||||
|
||||
/// Prefix marking a wrapped friend code. The `F1` is the wrap-format version,
|
||||
/// bumped if the layout ever changes.
|
||||
const MAGIC: &str = "pixelpassF1:";
|
||||
|
||||
/// Wrap a bare ticket with the host's control id, for display/copy/QR.
|
||||
pub fn wrap(host_id: EndpointId, ticket: &str) -> String {
|
||||
format!("{MAGIC}{host_id}.{ticket}")
|
||||
}
|
||||
|
||||
/// Split an input into `(host control id if it was a wrapped code, bare
|
||||
/// ticket)`. A bare or unrecognised input yields `(None, trimmed input)` so the
|
||||
/// viewer path stays identical to before for plain tickets.
|
||||
pub fn unwrap(code: &str) -> (Option<EndpointId>, String) {
|
||||
let code = code.trim();
|
||||
if let Some(rest) = code.strip_prefix(MAGIC)
|
||||
&& let Some((id_str, ticket)) = rest.split_once('.')
|
||||
&& let Ok(id) = EndpointId::from_str(id_str)
|
||||
&& !ticket.is_empty()
|
||||
{
|
||||
return (Some(id), ticket.to_string());
|
||||
}
|
||||
(None, code.to_string())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn sample_id() -> EndpointId {
|
||||
iroh::SecretKey::generate().public()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wrap_unwrap_round_trips() {
|
||||
let id = sample_id();
|
||||
let ticket = "endpointaabwxjexzensznfvuudiapn5tyzws3angd2merarm";
|
||||
let code = wrap(id, ticket);
|
||||
let (got_id, got_ticket) = unwrap(&code);
|
||||
assert_eq!(got_id, Some(id));
|
||||
assert_eq!(got_ticket, ticket);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bare_ticket_passes_through() {
|
||||
let ticket = "endpointaabwxjexzensznfvuudiapn5tyzws3angd2merarm";
|
||||
let (id, got) = unwrap(ticket);
|
||||
assert_eq!(id, None);
|
||||
assert_eq!(got, ticket);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn trims_surrounding_whitespace() {
|
||||
let ticket = "endpointaabwxjex";
|
||||
let (id, got) = unwrap(&format!(" {} ", wrap(sample_id(), ticket)));
|
||||
assert!(id.is_some());
|
||||
assert_eq!(got, ticket);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn malformed_wrapped_code_falls_back_to_bare() {
|
||||
// Prefix present but the id isn't a valid EndpointId → treat the whole
|
||||
// thing as a (doomed) bare ticket rather than panicking.
|
||||
let (id, got) = unwrap("pixelpassF1:not-an-id.endpointaa");
|
||||
assert_eq!(id, None);
|
||||
assert_eq!(got, "pixelpassF1:not-an-id.endpointaa");
|
||||
}
|
||||
}
|
||||
+2755
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,299 @@
|
||||
//! The always-on friends presence service.
|
||||
//!
|
||||
//! A control-plane iroh endpoint ([`endpoint::bind_control`]) that lives for the
|
||||
//! whole GUI session on its own thread with a current-thread tokio runtime — the
|
||||
//! GUI is a synchronous winit/egui loop, so iroh's async work can't run on it
|
||||
//! (the same reason [`super::tray`] has its own thread + runtime).
|
||||
//!
|
||||
//! Inbound control messages are forwarded over a std mpsc channel the UI drains
|
||||
//! each [`super::PixelPassApp::tick`]; the [`Waker`] is pinged on arrival so a
|
||||
//! message wakes the loop even while the window is hidden to the tray — the same
|
||||
//! trick the headless-child reader uses.
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::sync::mpsc::{self, Receiver};
|
||||
use std::thread;
|
||||
|
||||
use iroh::{Endpoint, EndpointId};
|
||||
use tokio::sync::mpsc as tmpsc;
|
||||
|
||||
use super::Waker;
|
||||
use crate::common::{
|
||||
control::{self, ControlMsg, Inbound},
|
||||
endpoint, identity,
|
||||
};
|
||||
|
||||
/// A command the UI hands the presence service over [`PresenceHandle`].
|
||||
enum Command {
|
||||
/// Deliver one message, once, fire-and-forget (friend request/accept/decline
|
||||
/// and the presence `Hello`). A failure is logged, not retried.
|
||||
Send { peer: EndpointId, msg: ControlMsg },
|
||||
/// Begin — or replace — a share campaign: push `msg` (a
|
||||
/// [`ControlMsg::ShareCode`]) to every peer in `peers`, retrying the ones
|
||||
/// that are offline until they're reached or the campaign is stopped. Each
|
||||
/// success emits a [`PresenceEvent::ShareDelivered`]. Replaces any campaign
|
||||
/// already running (a fresh host session supersedes the previous code).
|
||||
StartShare {
|
||||
msg: ControlMsg,
|
||||
peers: Vec<EndpointId>,
|
||||
},
|
||||
/// Stop the active share campaign — the host stopped or left the screen, so
|
||||
/// the perishable code is no longer valid and offline friends shouldn't keep
|
||||
/// being chased.
|
||||
StopShare,
|
||||
}
|
||||
|
||||
/// Something the service surfaces to the UI, drained each tick.
|
||||
pub enum PresenceEvent {
|
||||
/// A control message arrived from a peer.
|
||||
Message(Inbound),
|
||||
/// A share-campaign code reached `peer` (its ACK came back). Lets the host
|
||||
/// screen flip that friend's row from "retrying" to "delivered."
|
||||
ShareDelivered { peer: EndpointId },
|
||||
}
|
||||
|
||||
/// How long to wait before re-attempting delivery to friends who were offline
|
||||
/// on the previous round of a share campaign.
|
||||
const SHARE_RETRY: std::time::Duration = std::time::Duration::from_secs(5);
|
||||
|
||||
/// Handle the GUI holds for the presence service. Dropping it doesn't stop the
|
||||
/// service (the thread is detached; the endpoint closes when the process exits)
|
||||
/// — it just stops the UI from draining inbound messages.
|
||||
pub struct PresenceHandle {
|
||||
/// Our stable control-plane id — what friends know us by, and what we embed
|
||||
/// in a wrapped share code so a viewer can find us.
|
||||
id: EndpointId,
|
||||
/// Service events (inbound messages + share receipts), drained by
|
||||
/// [`PresenceHandle::drain`] each tick.
|
||||
rx: Receiver<PresenceEvent>,
|
||||
/// Commands handed to the service thread. Unbounded tokio sender so the sync
|
||||
/// UI can enqueue without blocking or being inside the runtime.
|
||||
out_tx: tmpsc::UnboundedSender<Command>,
|
||||
}
|
||||
|
||||
impl PresenceHandle {
|
||||
/// Our stable control-plane id.
|
||||
pub fn id(&self) -> EndpointId {
|
||||
self.id
|
||||
}
|
||||
|
||||
/// Pull every service event received since the last call. Collected by the
|
||||
/// caller so it can take `&mut self` while handling them.
|
||||
pub fn drain(&self) -> Vec<PresenceEvent> {
|
||||
std::iter::from_fn(|| self.rx.try_recv().ok()).collect()
|
||||
}
|
||||
|
||||
/// Enqueue a one-shot message for delivery to `peer`. Fire-and-forget from
|
||||
/// the UI's view; the service connects, delivers, and logs a failure. A send
|
||||
/// error here only means the service thread is gone.
|
||||
pub fn send(&self, peer: EndpointId, msg: ControlMsg) {
|
||||
self.command(Command::Send { peer, msg });
|
||||
}
|
||||
|
||||
/// Begin (or replace) a share campaign pushing `msg` to `peers`, retrying
|
||||
/// offline friends until [`PresenceHandle::stop_share`] or the next call.
|
||||
pub fn start_share(&self, msg: ControlMsg, peers: Vec<EndpointId>) {
|
||||
self.command(Command::StartShare { msg, peers });
|
||||
}
|
||||
|
||||
/// Stop the active share campaign (host stopped — the code is now stale).
|
||||
pub fn stop_share(&self) {
|
||||
self.command(Command::StopShare);
|
||||
}
|
||||
|
||||
fn command(&self, cmd: Command) {
|
||||
if self.out_tx.send(cmd).is_err() {
|
||||
tracing::warn!("presence: service thread gone; dropping command");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Start the presence service. Returns `None` if the persistent identity can't
|
||||
/// be loaded — the GUI then simply runs without friends features rather than
|
||||
/// refusing to start. The endpoint binds asynchronously on the spawned thread;
|
||||
/// our id is known immediately because it derives from the saved key, so we can
|
||||
/// fail-fast and log it without waiting on the relay handshake.
|
||||
pub fn start(waker: Waker, relay: Option<String>) -> Option<PresenceHandle> {
|
||||
let id: EndpointId = match identity::load_or_create() {
|
||||
Ok(key) => key.public(),
|
||||
Err(e) => {
|
||||
tracing::warn!("presence: no identity, friends features disabled: {e:#}");
|
||||
return None;
|
||||
}
|
||||
};
|
||||
tracing::info!(%id, "presence: starting control service");
|
||||
|
||||
let (tx, rx) = mpsc::channel::<PresenceEvent>();
|
||||
let (out_tx, out_rx) = tmpsc::unbounded_channel::<Command>();
|
||||
thread::Builder::new()
|
||||
.name("pixelpass-presence".into())
|
||||
.spawn(move || run(relay, id, tx, out_rx, waker))
|
||||
.map_err(|e| tracing::warn!("presence: could not spawn service thread: {e}"))
|
||||
.ok()?;
|
||||
|
||||
Some(PresenceHandle { id, rx, out_tx })
|
||||
}
|
||||
|
||||
/// Thread body: a current-thread tokio runtime that binds the control endpoint,
|
||||
/// runs the accept loop, bridges inbound messages to the UI channel, and
|
||||
/// delivers outbound messages the UI enqueues.
|
||||
fn run(
|
||||
relay: Option<String>,
|
||||
id: EndpointId,
|
||||
tx: mpsc::Sender<PresenceEvent>,
|
||||
mut out_rx: tmpsc::UnboundedReceiver<Command>,
|
||||
waker: Waker,
|
||||
) {
|
||||
let rt = match tokio::runtime::Builder::new_current_thread()
|
||||
.enable_all()
|
||||
.build()
|
||||
{
|
||||
Ok(rt) => rt,
|
||||
Err(e) => {
|
||||
tracing::error!("presence: failed to build runtime: {e}");
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
rt.block_on(async move {
|
||||
let ep = match endpoint::bind_control(relay.as_deref()).await {
|
||||
Ok(ep) => ep,
|
||||
Err(e) => {
|
||||
tracing::error!("presence: failed to bind control endpoint: {e:#}");
|
||||
return;
|
||||
}
|
||||
};
|
||||
tracing::info!(%id, "presence: control endpoint online");
|
||||
|
||||
// One async→sync bridge for *everything* the UI sees: every producer
|
||||
// (the accept loop and the share campaign) pushes a `PresenceEvent` into
|
||||
// `ui_tx`; this task drains it onto the std channel and wakes the loop so
|
||||
// the event lands even while the window is hidden to the tray.
|
||||
let (ui_tx, mut ui_rx) = tmpsc::channel::<PresenceEvent>(64);
|
||||
let forward = tokio::spawn(async move {
|
||||
while let Some(event) = ui_rx.recv().await {
|
||||
if tx.send(event).is_err() {
|
||||
break; // UI gone
|
||||
}
|
||||
waker.wake();
|
||||
}
|
||||
});
|
||||
|
||||
// Wrap inbound control messages as events and feed the bridge.
|
||||
let (itx, mut irx) = tmpsc::channel::<Inbound>(32);
|
||||
let inbound_ui = ui_tx.clone();
|
||||
let inbound = tokio::spawn(async move {
|
||||
while let Some(msg) = irx.recv().await {
|
||||
if inbound_ui.send(PresenceEvent::Message(msg)).await.is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// Handle UI commands: one-shot sends each on their own task, and a single
|
||||
// abortable share campaign (StartShare replaces it, StopShare cancels it).
|
||||
let cmd_ep = ep.clone();
|
||||
let commands = tokio::spawn(async move {
|
||||
let mut share: Option<tokio::task::JoinHandle<()>> = None;
|
||||
while let Some(cmd) = out_rx.recv().await {
|
||||
match cmd {
|
||||
Command::Send { peer, msg } => {
|
||||
let ep = cmd_ep.clone();
|
||||
tokio::spawn(async move {
|
||||
if let Err(e) = control::send(&ep, peer, &msg).await {
|
||||
tracing::warn!(%peer, "presence: outbound send failed: {e:#}");
|
||||
}
|
||||
});
|
||||
}
|
||||
Command::StartShare { msg, peers } => {
|
||||
if let Some(t) = share.take() {
|
||||
t.abort();
|
||||
}
|
||||
let ep = cmd_ep.clone();
|
||||
let ui = ui_tx.clone();
|
||||
share = Some(tokio::spawn(run_share(ep, msg, peers, ui)));
|
||||
}
|
||||
Command::StopShare => {
|
||||
if let Some(t) = share.take() {
|
||||
t.abort();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
control::serve(ep, itx).await;
|
||||
forward.abort();
|
||||
inbound.abort();
|
||||
commands.abort();
|
||||
});
|
||||
}
|
||||
|
||||
/// Push `msg` to every peer in `peers`, retrying the ones that are offline every
|
||||
/// [`SHARE_RETRY`] until all are delivered (or the task is aborted by a
|
||||
/// StartShare/StopShare). Emits one [`PresenceEvent::ShareDelivered`] per peer
|
||||
/// the moment its ACK comes back — that ACK *is* the delivery signal.
|
||||
///
|
||||
/// Each round fires all still-pending peers **concurrently**, so a single
|
||||
/// offline friend's ~10s connect timeout doesn't serialise the whole round
|
||||
/// (which it did when peers were tried one at a time).
|
||||
async fn run_share(
|
||||
ep: Endpoint,
|
||||
msg: ControlMsg,
|
||||
mut pending: Vec<EndpointId>,
|
||||
ui: tmpsc::Sender<PresenceEvent>,
|
||||
) {
|
||||
// The code is immutable for the campaign's life; share it across the
|
||||
// per-peer tasks via an `Arc` rather than re-cloning the payload each round.
|
||||
let msg = Arc::new(msg);
|
||||
while !pending.is_empty() {
|
||||
let mut round = tokio::task::JoinSet::new();
|
||||
for peer in pending {
|
||||
let ep = ep.clone();
|
||||
let msg = Arc::clone(&msg);
|
||||
round.spawn(async move {
|
||||
match control::send(&ep, peer, &msg).await {
|
||||
Ok(()) => (peer, true),
|
||||
Err(e) => {
|
||||
tracing::debug!(%peer, "presence: share not yet delivered: {e:#}");
|
||||
(peer, false)
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
let mut still = Vec::new();
|
||||
while let Some(joined) = round.join_next().await {
|
||||
let (peer, delivered) = match joined {
|
||||
Ok(outcome) => outcome,
|
||||
// A send task panicking is unexpected; log and drop that peer
|
||||
// from the campaign rather than abort the whole round. (A
|
||||
// campaign-level abort drops this future entirely — we never
|
||||
// observe that as a JoinError here.)
|
||||
Err(e) => {
|
||||
tracing::warn!("presence: share task failed: {e}");
|
||||
continue;
|
||||
}
|
||||
};
|
||||
if delivered {
|
||||
tracing::info!(%peer, "presence: shared code delivered");
|
||||
if ui
|
||||
.send(PresenceEvent::ShareDelivered { peer })
|
||||
.await
|
||||
.is_err()
|
||||
{
|
||||
return; // UI gone — nothing left to report to
|
||||
}
|
||||
} else {
|
||||
still.push(peer);
|
||||
}
|
||||
}
|
||||
|
||||
if still.is_empty() {
|
||||
break;
|
||||
}
|
||||
pending = still;
|
||||
tokio::time::sleep(SHARE_RETRY).await;
|
||||
}
|
||||
tracing::info!("presence: share campaign complete");
|
||||
}
|
||||
@@ -0,0 +1,456 @@
|
||||
//! User-customisable colour themes for the GUI.
|
||||
//!
|
||||
//! A theme is a small, curated *semantic* palette — backgrounds, text, an
|
||||
//! accent, and the handful of status colours the app uses (streaming, waiting,
|
||||
//! success, warning, error). That's deliberately a fixed set rather than a
|
||||
//! passthrough of every [`egui::Visuals`] field: it's easy to author by hand,
|
||||
//! covers the whole look of the app, and stays stable across egui upgrades.
|
||||
//!
|
||||
//! Themes serialise to TOML with colours as `#rrggbb` hex strings. Three
|
||||
//! themes ship built in; users drop their own `*.toml` files in
|
||||
//! `~/.config/pixelpass/themes/` (or save one from the in-app editor) and they
|
||||
//! show up alongside the built-ins. A user file whose `name` matches a built-in
|
||||
//! overrides it.
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
use directories::ProjectDirs;
|
||||
use eframe::egui::{self, Color32};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// One colour theme: a curated semantic palette.
|
||||
///
|
||||
/// `#[serde(default)]` on the container means any field missing from a TOML
|
||||
/// file falls back to the corresponding field of [`Theme::default`] (the
|
||||
/// built-in Default Dark), so a partial or hand-trimmed file still loads.
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(default)]
|
||||
pub struct Theme {
|
||||
/// Display name, shown in the picker and used as the file stem on save.
|
||||
pub name: String,
|
||||
/// Base egui defaults to start from before applying the palette overrides.
|
||||
pub dark: bool,
|
||||
|
||||
// ── chrome ────────────────────────────────────────────────────────
|
||||
/// Window background.
|
||||
#[serde(with = "hex")]
|
||||
pub window_bg: Color32,
|
||||
/// Panel / frame background.
|
||||
#[serde(with = "hex")]
|
||||
pub panel_bg: Color32,
|
||||
/// Text-input and read-only field background (the ticket box, etc.).
|
||||
#[serde(with = "hex")]
|
||||
pub input_bg: Color32,
|
||||
/// Primary text.
|
||||
#[serde(with = "hex")]
|
||||
pub text: Color32,
|
||||
/// Secondary / de-emphasised text (hints, the version line).
|
||||
#[serde(with = "hex")]
|
||||
pub weak_text: Color32,
|
||||
/// Accent: selection, hyperlinks, and the active/pressed widget fill.
|
||||
#[serde(with = "hex")]
|
||||
pub accent: Color32,
|
||||
/// Button (and other interactive widget) resting background.
|
||||
#[serde(with = "hex")]
|
||||
pub button_bg: Color32,
|
||||
/// Button background on hover.
|
||||
#[serde(with = "hex")]
|
||||
pub button_hovered: Color32,
|
||||
|
||||
// ── semantic status colours ───────────────────────────────────────
|
||||
/// "● Streaming" indicator.
|
||||
#[serde(with = "hex")]
|
||||
pub streaming: Color32,
|
||||
/// "● Waiting for viewers…" indicator.
|
||||
#[serde(with = "hex")]
|
||||
pub waiting: Color32,
|
||||
/// Success notes, e.g. "✓ Copied to clipboard".
|
||||
#[serde(with = "hex")]
|
||||
pub success: Color32,
|
||||
/// Non-fatal warnings, e.g. a host-full refusal.
|
||||
#[serde(with = "hex")]
|
||||
pub warning: Color32,
|
||||
/// Errors.
|
||||
#[serde(with = "hex")]
|
||||
pub error: Color32,
|
||||
}
|
||||
|
||||
impl Default for Theme {
|
||||
fn default() -> Self {
|
||||
default_dark()
|
||||
}
|
||||
}
|
||||
|
||||
impl Theme {
|
||||
/// Build the egui [`Visuals`](egui::Visuals) this theme describes. Starts
|
||||
/// from egui's dark or light defaults (so anything the palette doesn't name
|
||||
/// stays sensible) and overrides the curated fields.
|
||||
pub fn visuals(&self) -> egui::Visuals {
|
||||
use egui::{Stroke, Visuals};
|
||||
|
||||
let mut v = if self.dark {
|
||||
Visuals::dark()
|
||||
} else {
|
||||
Visuals::light()
|
||||
};
|
||||
v.dark_mode = self.dark;
|
||||
|
||||
v.window_fill = self.window_bg;
|
||||
v.panel_fill = self.panel_bg;
|
||||
v.faint_bg_color = self.panel_bg;
|
||||
v.extreme_bg_color = self.input_bg;
|
||||
v.override_text_color = Some(self.text);
|
||||
// `.weak()` text resolves via `weak_text_color()`, which derives from
|
||||
// `text` unless this is set — so without it the weak-text field is dead.
|
||||
v.weak_text_color = Some(self.weak_text);
|
||||
v.hyperlink_color = self.accent;
|
||||
v.error_fg_color = self.error;
|
||||
v.warn_fg_color = self.warning;
|
||||
|
||||
// A translucent accent reads well as a selection highlight on either a
|
||||
// light or dark base.
|
||||
v.selection.bg_fill =
|
||||
Color32::from_rgba_unmultiplied(self.accent.r(), self.accent.g(), self.accent.b(), 96);
|
||||
v.selection.stroke = Stroke::new(1.0, self.accent);
|
||||
|
||||
let text_stroke = Stroke::new(1.0, self.text);
|
||||
let weak_stroke = Stroke::new(1.0, self.weak_text);
|
||||
|
||||
v.widgets.noninteractive.bg_fill = self.panel_bg;
|
||||
v.widgets.noninteractive.weak_bg_fill = self.panel_bg;
|
||||
v.widgets.noninteractive.fg_stroke = weak_stroke;
|
||||
|
||||
v.widgets.inactive.bg_fill = self.button_bg;
|
||||
v.widgets.inactive.weak_bg_fill = self.button_bg;
|
||||
v.widgets.inactive.fg_stroke = text_stroke;
|
||||
|
||||
v.widgets.hovered.bg_fill = self.button_hovered;
|
||||
v.widgets.hovered.weak_bg_fill = self.button_hovered;
|
||||
v.widgets.hovered.fg_stroke = text_stroke;
|
||||
|
||||
v.widgets.active.bg_fill = self.accent;
|
||||
v.widgets.active.weak_bg_fill = self.accent;
|
||||
v.widgets.active.fg_stroke = text_stroke;
|
||||
|
||||
v
|
||||
}
|
||||
}
|
||||
|
||||
// ── built-in themes ───────────────────────────────────────────────────────
|
||||
|
||||
/// Names of the built-in themes, in picker order.
|
||||
pub const BUILTIN_NAMES: [&str; 3] = ["Default Dark", "Catppuccin Mocha", "Catppuccin Latte"];
|
||||
|
||||
/// Parse a built-in's hex literal, panicking on a typo (these are compile-time
|
||||
/// constants we control, so a bad value is a bug, not user input).
|
||||
fn c(hex: &str) -> Color32 {
|
||||
parse_hex(hex).expect("built-in theme hex is valid")
|
||||
}
|
||||
|
||||
/// The default theme — a neutral dark palette. Also [`Theme::default`].
|
||||
pub fn default_dark() -> Theme {
|
||||
Theme {
|
||||
name: "Default Dark".to_string(),
|
||||
dark: true,
|
||||
window_bg: c("#1b1b1f"),
|
||||
panel_bg: c("#242429"),
|
||||
input_bg: c("#141417"),
|
||||
text: c("#e6e6ea"),
|
||||
weak_text: c("#a0a0a8"),
|
||||
accent: c("#5aa0f2"),
|
||||
button_bg: c("#33333a"),
|
||||
button_hovered: c("#44444d"),
|
||||
streaming: c("#6fdc8c"),
|
||||
waiting: c("#f2c14e"),
|
||||
success: c("#6fdc8c"),
|
||||
warning: c("#f0a85a"),
|
||||
error: c("#f2756f"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Catppuccin Mocha (dark). <https://github.com/catppuccin/catppuccin>
|
||||
fn catppuccin_mocha() -> Theme {
|
||||
Theme {
|
||||
name: "Catppuccin Mocha".to_string(),
|
||||
dark: true,
|
||||
window_bg: c("#1e1e2e"),
|
||||
panel_bg: c("#181825"),
|
||||
input_bg: c("#11111b"),
|
||||
text: c("#cdd6f4"),
|
||||
weak_text: c("#a6adc8"),
|
||||
accent: c("#cba6f7"),
|
||||
button_bg: c("#313244"),
|
||||
button_hovered: c("#45475a"),
|
||||
streaming: c("#a6e3a1"),
|
||||
waiting: c("#f9e2af"),
|
||||
success: c("#a6e3a1"),
|
||||
warning: c("#fab387"),
|
||||
error: c("#f38ba8"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Catppuccin Latte (light). <https://github.com/catppuccin/catppuccin>
|
||||
fn catppuccin_latte() -> Theme {
|
||||
Theme {
|
||||
name: "Catppuccin Latte".to_string(),
|
||||
dark: false,
|
||||
window_bg: c("#eff1f5"),
|
||||
panel_bg: c("#e6e9ef"),
|
||||
input_bg: c("#dce0e8"),
|
||||
text: c("#4c4f69"),
|
||||
weak_text: c("#6c6f85"),
|
||||
accent: c("#8839ef"),
|
||||
button_bg: c("#ccd0da"),
|
||||
button_hovered: c("#bcc0cc"),
|
||||
streaming: c("#40a02b"),
|
||||
waiting: c("#df8e1d"),
|
||||
success: c("#40a02b"),
|
||||
warning: c("#fe640b"),
|
||||
error: c("#d20f39"),
|
||||
}
|
||||
}
|
||||
|
||||
/// The built-in themes, in [`BUILTIN_NAMES`] order.
|
||||
pub fn builtins() -> Vec<Theme> {
|
||||
vec![default_dark(), catppuccin_mocha(), catppuccin_latte()]
|
||||
}
|
||||
|
||||
/// Whether `name` is one of the built-ins (which are read-only — the editor
|
||||
/// nudges you to save under a new name).
|
||||
pub fn is_builtin(name: &str) -> bool {
|
||||
BUILTIN_NAMES.contains(&name)
|
||||
}
|
||||
|
||||
// ── on-disk themes ──────────────────────────────────────────────────────────
|
||||
|
||||
/// `~/.config/pixelpass/themes/` (or the XDG equivalent). Not created until a
|
||||
/// theme is saved.
|
||||
pub fn themes_dir() -> Result<PathBuf> {
|
||||
let dirs = ProjectDirs::from("", "", "pixelpass")
|
||||
.context("could not locate a config directory for pixelpass")?;
|
||||
Ok(dirs.config_dir().join("themes"))
|
||||
}
|
||||
|
||||
/// Parse every `*.toml` in the themes dir into a [`Theme`]. A file that fails
|
||||
/// to parse is logged and skipped rather than aborting the whole list, so one
|
||||
/// bad file can't hide the rest. Returns themes sorted by name.
|
||||
pub fn list_user_themes() -> Vec<Theme> {
|
||||
let Ok(dir) = themes_dir() else {
|
||||
return Vec::new();
|
||||
};
|
||||
let Ok(entries) = std::fs::read_dir(&dir) else {
|
||||
return Vec::new(); // dir doesn't exist yet → no user themes
|
||||
};
|
||||
|
||||
let mut out = Vec::new();
|
||||
for entry in entries.flatten() {
|
||||
let path = entry.path();
|
||||
if path.extension().and_then(|e| e.to_str()) != Some("toml") {
|
||||
continue;
|
||||
}
|
||||
match std::fs::read_to_string(&path) {
|
||||
Ok(s) => match toml::from_str::<Theme>(&s) {
|
||||
Ok(mut t) => {
|
||||
// Fall back to the file stem if the file omits a name.
|
||||
if t.name.trim().is_empty() {
|
||||
t.name = path
|
||||
.file_stem()
|
||||
.and_then(|s| s.to_str())
|
||||
.unwrap_or("Unnamed")
|
||||
.to_string();
|
||||
}
|
||||
out.push(t);
|
||||
}
|
||||
Err(e) => tracing::warn!("skipping theme {}: {e}", path.display()),
|
||||
},
|
||||
Err(e) => tracing::warn!("could not read theme {}: {e}", path.display()),
|
||||
}
|
||||
}
|
||||
out.sort_by_key(|t| t.name.to_lowercase());
|
||||
out
|
||||
}
|
||||
|
||||
/// Built-ins plus user themes, in picker order: built-ins first (a user file
|
||||
/// with a matching `name` overrides the built-in's colours in place), then any
|
||||
/// remaining user themes alphabetically.
|
||||
pub fn all_themes() -> Vec<Theme> {
|
||||
let users = list_user_themes();
|
||||
let mut out: Vec<Theme> = builtins()
|
||||
.into_iter()
|
||||
.map(|b| {
|
||||
users
|
||||
.iter()
|
||||
.find(|u| u.name == b.name)
|
||||
.cloned()
|
||||
.unwrap_or(b)
|
||||
})
|
||||
.collect();
|
||||
for u in users {
|
||||
if !is_builtin(&u.name) {
|
||||
out.push(u);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The theme with this `name`, or Default Dark if it can't be found (e.g. the
|
||||
/// config names a theme whose file was deleted).
|
||||
pub fn load_named(name: &str) -> Theme {
|
||||
all_themes()
|
||||
.into_iter()
|
||||
.find(|t| t.name == name)
|
||||
.unwrap_or_else(default_dark)
|
||||
}
|
||||
|
||||
/// Write `theme` to `<themes_dir>/<slug>.toml` and return the path. Overwrites
|
||||
/// an existing file with the same slug (i.e. saving a tweaked theme under the
|
||||
/// same name updates it in place).
|
||||
pub fn save_theme(theme: &Theme) -> Result<PathBuf> {
|
||||
let dir = themes_dir()?;
|
||||
std::fs::create_dir_all(&dir).with_context(|| format!("failed to create {}", dir.display()))?;
|
||||
|
||||
let slug = slugify(&theme.name);
|
||||
let path = dir.join(format!("{slug}.toml"));
|
||||
let body = toml::to_string_pretty(theme).context("failed to serialise theme to TOML")?;
|
||||
let contents = format!(
|
||||
"# PixelPass theme. Colours are #rrggbb hex strings.\n\
|
||||
# Edit and re-pick it in Settings, or drop more .toml files in this folder.\n\n\
|
||||
{body}"
|
||||
);
|
||||
std::fs::write(&path, contents)
|
||||
.with_context(|| format!("failed to write {}", path.display()))?;
|
||||
Ok(path)
|
||||
}
|
||||
|
||||
/// Lowercase, replace runs of non-alphanumerics with a single hyphen, trim
|
||||
/// hyphens. Empty input becomes `theme`.
|
||||
fn slugify(name: &str) -> String {
|
||||
let mut slug = String::new();
|
||||
let mut prev_hyphen = false;
|
||||
for ch in name.trim().chars() {
|
||||
if ch.is_ascii_alphanumeric() {
|
||||
slug.push(ch.to_ascii_lowercase());
|
||||
prev_hyphen = false;
|
||||
} else if !prev_hyphen {
|
||||
slug.push('-');
|
||||
prev_hyphen = true;
|
||||
}
|
||||
}
|
||||
let slug = slug.trim_matches('-').to_string();
|
||||
if slug.is_empty() {
|
||||
"theme".to_string()
|
||||
} else {
|
||||
slug
|
||||
}
|
||||
}
|
||||
|
||||
// ── hex colour parsing ────────────────────────────────────────────────────
|
||||
|
||||
/// Parse `#rrggbb` into an opaque [`Color32`] (the leading `#` is optional).
|
||||
/// An 8-digit `#rrggbbaa` is accepted leniently but its alpha is ignored —
|
||||
/// theme colours are opaque, and `Color32`'s premultiplied storage can't
|
||||
/// round-trip a straight alpha losslessly anyway. Returns `None` on malformed
|
||||
/// input.
|
||||
pub fn parse_hex(s: &str) -> Option<Color32> {
|
||||
let s = s.trim();
|
||||
let s = s.strip_prefix('#').unwrap_or(s);
|
||||
if !matches!(s.len(), 6 | 8) || !s.bytes().all(|b| b.is_ascii_hexdigit()) {
|
||||
return None;
|
||||
}
|
||||
let byte = |i: usize| u8::from_str_radix(&s[i..i + 2], 16).ok();
|
||||
Some(Color32::from_rgb(byte(0)?, byte(2)?, byte(4)?))
|
||||
}
|
||||
|
||||
/// Format a [`Color32`] as opaque `#rrggbb`.
|
||||
pub fn to_hex(c: Color32) -> String {
|
||||
let [r, g, b, _] = c.to_srgba_unmultiplied();
|
||||
format!("#{r:02x}{g:02x}{b:02x}")
|
||||
}
|
||||
|
||||
/// serde adaptor so `Color32` fields round-trip as hex strings in TOML.
|
||||
mod hex {
|
||||
use super::{parse_hex, to_hex};
|
||||
use eframe::egui::Color32;
|
||||
use serde::{Deserialize, Deserializer, Serializer, de::Error};
|
||||
|
||||
pub fn serialize<S: Serializer>(c: &Color32, s: S) -> Result<S::Ok, S::Error> {
|
||||
s.serialize_str(&to_hex(*c))
|
||||
}
|
||||
|
||||
pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Color32, D::Error> {
|
||||
let s = String::deserialize(d)?;
|
||||
parse_hex(&s).ok_or_else(|| {
|
||||
D::Error::custom(format!(
|
||||
"invalid hex colour {s:?} (expected #rrggbb or #rrggbbaa)"
|
||||
))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn hex_round_trips() {
|
||||
for (input, expect) in [
|
||||
("#1e1e2e", Color32::from_rgb(0x1e, 0x1e, 0x2e)),
|
||||
("aabbcc", Color32::from_rgb(0xaa, 0xbb, 0xcc)),
|
||||
// 8-digit is accepted but the alpha is dropped (opaque rgb).
|
||||
("#11223344", Color32::from_rgb(0x11, 0x22, 0x33)),
|
||||
] {
|
||||
assert_eq!(parse_hex(input).expect("parses"), expect);
|
||||
}
|
||||
assert_eq!(to_hex(Color32::from_rgb(0x1e, 0x1e, 0x2e)), "#1e1e2e");
|
||||
// Opaque colours round-trip exactly.
|
||||
let c = Color32::from_rgb(0xab, 0xcd, 0xef);
|
||||
assert_eq!(parse_hex(&to_hex(c)), Some(c));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hex_rejects_garbage() {
|
||||
for bad in ["", "#fff", "#12345", "nothex", "#gggggg", "#1234567"] {
|
||||
assert!(parse_hex(bad).is_none(), "{bad:?} should not parse");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn theme_toml_round_trips() {
|
||||
let original = catppuccin_mocha();
|
||||
let toml = toml::to_string_pretty(&original).unwrap();
|
||||
let parsed: Theme = toml::from_str(&toml).unwrap();
|
||||
assert_eq!(original, parsed);
|
||||
// Colours serialise as hex strings, not RGBA tables.
|
||||
assert!(toml.contains("window_bg = \"#1e1e2e\""), "{toml}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn partial_toml_fills_from_default() {
|
||||
// Only a name and one colour; everything else must fall back to Default Dark.
|
||||
let parsed: Theme = toml::from_str("name = \"Partial\"\naccent = \"#ff0000\"").unwrap();
|
||||
let base = default_dark();
|
||||
assert_eq!(parsed.name, "Partial");
|
||||
assert_eq!(parsed.accent, Color32::from_rgb(0xff, 0, 0));
|
||||
assert_eq!(parsed.window_bg, base.window_bg); // filled from default
|
||||
assert_eq!(parsed.text, base.text);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn slugify_is_filesystem_safe() {
|
||||
assert_eq!(slugify("Catppuccin Mocha"), "catppuccin-mocha");
|
||||
assert_eq!(slugify(" My Theme!! "), "my-theme");
|
||||
assert_eq!(slugify("***"), "theme");
|
||||
assert_eq!(slugify("Solarized/Dark"), "solarized-dark");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn builtins_match_names() {
|
||||
let names: Vec<String> = builtins().iter().map(|t| t.name.clone()).collect();
|
||||
let expected: Vec<String> = BUILTIN_NAMES.iter().map(|s| s.to_string()).collect();
|
||||
assert_eq!(names, expected);
|
||||
for t in builtins() {
|
||||
assert!(is_builtin(&t.name));
|
||||
}
|
||||
}
|
||||
}
|
||||
+257
@@ -0,0 +1,257 @@
|
||||
//! System-tray (StatusNotifierItem) integration for the GUI.
|
||||
//!
|
||||
//! The tray runs on its **own dedicated thread** with its own current-thread
|
||||
//! tokio runtime, fully decoupled from the winit event loop (which owns the
|
||||
//! main thread) and from the process-wide `#[tokio::main]` runtime. It talks to
|
||||
//! the egui app purely over winit's event channel and a status channel:
|
||||
//!
|
||||
//! * tray → app: a [`super::UserEvent::Tray`] carrying a [`TrayAction`]
|
||||
//! (Show / Quit), pushed through the [`winit::event_loop::EventLoopProxy`].
|
||||
//! Using the proxy (not egui's repaint) is essential: a tray click must
|
||||
//! wake the winit loop even when the window has been **dropped** (hidden to
|
||||
//! tray), so the loop can recreate it.
|
||||
//! * app → tray: [`TrayStatus`] (idle / hosting / viewing), pushed on change.
|
||||
//!
|
||||
//! Why a separate thread instead of `Handle::current().spawn`: updating the
|
||||
//! tray from the egui thread would need `block_on`, which panics when called
|
||||
//! from inside the running runtime. Keeping ksni's async wholly on its own
|
||||
//! runtime sidesteps that and keeps the frame loop non-blocking.
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
|
||||
use ksni::TrayMethods;
|
||||
use winit::event_loop::EventLoopProxy;
|
||||
|
||||
use super::UserEvent;
|
||||
|
||||
/// What the user picked from the tray icon or its menu (tray thread → app),
|
||||
/// delivered as a [`UserEvent::Tray`].
|
||||
pub enum TrayAction {
|
||||
/// Left-click, or the "Show window" item: bring the window back.
|
||||
Show,
|
||||
/// The "Quit" item: really exit (the close button only hides to tray).
|
||||
Quit,
|
||||
}
|
||||
|
||||
/// What the tray icon's tooltip/menu reflect (app → tray thread).
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
pub enum TrayStatus {
|
||||
Idle,
|
||||
Hosting { active: u32, max: u32 },
|
||||
Viewing,
|
||||
}
|
||||
|
||||
fn status_text(status: TrayStatus) -> String {
|
||||
match status {
|
||||
TrayStatus::Idle => "Idle".to_string(),
|
||||
TrayStatus::Hosting { active, max } => {
|
||||
format!("Hosting — {active} of {max} viewer(s) connected")
|
||||
}
|
||||
TrayStatus::Viewing => "Viewing a stream".to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Handle held by the egui app for the lifetime of the window. Dropping it
|
||||
/// closes the app→tray channel, which ends the tray thread and removes the icon.
|
||||
pub struct TrayHandle {
|
||||
status_tx: tokio::sync::mpsc::UnboundedSender<TrayStatus>,
|
||||
/// Set true once the tray actually registered with a StatusNotifier host.
|
||||
/// The app must not divert the window's close to a tray that never appeared.
|
||||
registered: Arc<AtomicBool>,
|
||||
/// Last status pushed, so we don't spam D-Bus with no-op updates.
|
||||
last_sent: Option<TrayStatus>,
|
||||
}
|
||||
|
||||
impl TrayHandle {
|
||||
/// Whether a system tray is actually showing our icon. Until this is true,
|
||||
/// hiding the window would strand it with no way back.
|
||||
pub fn registered(&self) -> bool {
|
||||
self.registered.load(Ordering::Acquire)
|
||||
}
|
||||
|
||||
/// Push a status change to the tray, deduped against the last one sent.
|
||||
pub fn set_status(&mut self, status: TrayStatus) {
|
||||
if self.last_sent != Some(status) {
|
||||
let _ = self.status_tx.send(status);
|
||||
self.last_sent = Some(status);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct PixelPassTray {
|
||||
status: TrayStatus,
|
||||
/// ARGB pixmap, so the icon shows even where the themed "pixelpass" name
|
||||
/// can't be resolved (e.g. running the dev binary before `make install`).
|
||||
icon: Vec<ksni::Icon>,
|
||||
/// Wakes the winit loop and delivers the action — works even when the
|
||||
/// window has been dropped to the tray (no egui frame is running then).
|
||||
proxy: EventLoopProxy<UserEvent>,
|
||||
/// Shared with [`TrayHandle`]; kept in sync with the watcher's presence via
|
||||
/// the `watcher_online`/`watcher_offline` callbacks so the app never diverts
|
||||
/// a close to a tray that has since disappeared.
|
||||
registered: Arc<AtomicBool>,
|
||||
}
|
||||
|
||||
impl PixelPassTray {
|
||||
fn notify(&self, action: TrayAction) {
|
||||
let _ = self.proxy.send_event(UserEvent::Tray(action));
|
||||
}
|
||||
}
|
||||
|
||||
impl ksni::Tray for PixelPassTray {
|
||||
fn id(&self) -> String {
|
||||
"pixelpass".to_string()
|
||||
}
|
||||
|
||||
fn title(&self) -> String {
|
||||
"PixelPass".to_string()
|
||||
}
|
||||
|
||||
// Themed icon (matches the installed hicolor/scalable/apps/pixelpass.svg);
|
||||
// icon_pixmap below is the always-works fallback.
|
||||
fn icon_name(&self) -> String {
|
||||
"pixelpass".to_string()
|
||||
}
|
||||
|
||||
fn icon_pixmap(&self) -> Vec<ksni::Icon> {
|
||||
self.icon.clone()
|
||||
}
|
||||
|
||||
fn status(&self) -> ksni::Status {
|
||||
ksni::Status::Active
|
||||
}
|
||||
|
||||
fn tool_tip(&self) -> ksni::ToolTip {
|
||||
ksni::ToolTip {
|
||||
title: "PixelPass".to_string(),
|
||||
description: status_text(self.status),
|
||||
icon_name: "pixelpass".to_string(),
|
||||
icon_pixmap: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn activate(&mut self, _x: i32, _y: i32) {
|
||||
self.notify(TrayAction::Show);
|
||||
}
|
||||
|
||||
/// The StatusNotifierWatcher came back (e.g. the panel restarted). Mark the
|
||||
/// tray live again so close-to-tray can resume hiding the window.
|
||||
fn watcher_online(&self) {
|
||||
self.registered.store(true, Ordering::Release);
|
||||
}
|
||||
|
||||
/// The watcher went away (panel restart, tray plugin disabled, …). Clear the
|
||||
/// flag so a subsequent close quits normally instead of destroying the window
|
||||
/// into a tray that no longer exists, and force the window back now in case
|
||||
/// it was already hidden (otherwise it'd be stranded with no way to restore).
|
||||
/// Returning `true` keeps the service alive so it re-registers if the watcher
|
||||
/// returns.
|
||||
fn watcher_offline(&self, reason: ksni::OfflineReason) -> bool {
|
||||
tracing::warn!("tray: StatusNotifierWatcher offline ({reason:?}); restoring window");
|
||||
self.registered.store(false, Ordering::Release);
|
||||
self.notify(TrayAction::Show);
|
||||
true
|
||||
}
|
||||
|
||||
fn menu(&self) -> Vec<ksni::MenuItem<Self>> {
|
||||
use ksni::menu::{MenuItem, StandardItem};
|
||||
vec![
|
||||
// Non-clickable status line.
|
||||
StandardItem {
|
||||
label: status_text(self.status),
|
||||
enabled: false,
|
||||
..Default::default()
|
||||
}
|
||||
.into(),
|
||||
MenuItem::Separator,
|
||||
StandardItem {
|
||||
label: "Show window".to_string(),
|
||||
activate: Box::new(|t: &mut Self| t.notify(TrayAction::Show)),
|
||||
..Default::default()
|
||||
}
|
||||
.into(),
|
||||
StandardItem {
|
||||
label: "Quit PixelPass".to_string(),
|
||||
icon_name: "application-exit".to_string(),
|
||||
activate: Box::new(|t: &mut Self| t.notify(TrayAction::Quit)),
|
||||
..Default::default()
|
||||
}
|
||||
.into(),
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
/// Decode the embedded PNG (RGBA) and convert to the ARGB pixmap ksni wants.
|
||||
/// Reuses eframe's PNG decoder so we don't take a direct `image` dependency.
|
||||
fn load_icon() -> Option<Vec<ksni::Icon>> {
|
||||
let icon =
|
||||
eframe::icon_data::from_png_bytes(include_bytes!("../../assets/pixelpass-256.png")).ok()?;
|
||||
let mut data = icon.rgba; // RGBA8, row-major
|
||||
for px in data.chunks_exact_mut(4) {
|
||||
px.rotate_right(1); // [r,g,b,a] -> [a,r,g,b], network byte order
|
||||
}
|
||||
Some(vec![ksni::Icon {
|
||||
width: icon.width as i32,
|
||||
height: icon.height as i32,
|
||||
data,
|
||||
}])
|
||||
}
|
||||
|
||||
/// Start the tray on its own thread. Returns a handle for the app to drive it,
|
||||
/// or `None` if the icon couldn't be decoded or the thread couldn't spawn (in
|
||||
/// which case the GUI simply runs without a tray — close behaves as before).
|
||||
pub fn start(proxy: EventLoopProxy<UserEvent>) -> Option<TrayHandle> {
|
||||
let icon = load_icon()?;
|
||||
let (status_tx, mut status_rx) = tokio::sync::mpsc::unbounded_channel::<TrayStatus>();
|
||||
let registered = Arc::new(AtomicBool::new(false));
|
||||
let registered_thread = registered.clone();
|
||||
|
||||
std::thread::Builder::new()
|
||||
.name("pixelpass-tray".to_string())
|
||||
.spawn(move || {
|
||||
let rt = match tokio::runtime::Builder::new_current_thread()
|
||||
.enable_all()
|
||||
.build()
|
||||
{
|
||||
Ok(rt) => rt,
|
||||
Err(e) => {
|
||||
tracing::warn!("tray: could not build runtime: {e}");
|
||||
return;
|
||||
}
|
||||
};
|
||||
rt.block_on(async move {
|
||||
let tray = PixelPassTray {
|
||||
status: TrayStatus::Idle,
|
||||
icon,
|
||||
proxy,
|
||||
registered: registered_thread.clone(),
|
||||
};
|
||||
let handle = match tray.spawn().await {
|
||||
Ok(handle) => handle,
|
||||
Err(e) => {
|
||||
// No StatusNotifier host (no system tray) — degrade
|
||||
// gracefully: the window keeps its normal close.
|
||||
tracing::warn!("tray: not available, running without it: {e}");
|
||||
return;
|
||||
}
|
||||
};
|
||||
registered_thread.store(true, Ordering::Release);
|
||||
|
||||
// Apply status changes until the app drops its sender (on quit),
|
||||
// which ends this loop, the runtime, the thread, and the icon.
|
||||
while let Some(status) = status_rx.recv().await {
|
||||
let _ = handle
|
||||
.update(move |t: &mut PixelPassTray| t.status = status)
|
||||
.await;
|
||||
}
|
||||
});
|
||||
})
|
||||
.ok()?;
|
||||
|
||||
Some(TrayHandle {
|
||||
status_tx,
|
||||
registered,
|
||||
last_sent: None,
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,656 @@
|
||||
//! Per-app audio routing.
|
||||
//!
|
||||
//! Two cooperating layers:
|
||||
//!
|
||||
//! - **Null-sink + loopback** (pactl shell-out): a per-PID null-sink
|
||||
//! `pixelpass_capture_<pid>` plus a `module-loopback` that mirrors the
|
||||
//! default sink's monitor into it. gst captures from the null-sink's
|
||||
//! monitor, so the viewer hears whatever the user hears — by default.
|
||||
//!
|
||||
//! - **Per-stream rerouting** (libpipewire on a dedicated OS thread):
|
||||
//! when [`HostOpts::app`] is set, a [`StreamRouter`] subscribes to the
|
||||
//! PipeWire registry, finds `Stream/Output/Audio` nodes whose
|
||||
//! `application.name` matches the filter, and writes
|
||||
//! `target.object` to the "default" metadata so WirePlumber reroutes
|
||||
//! them to our null-sink. Once at least one stream is actually routed,
|
||||
//! the loopback is unloaded — otherwise the viewer would hear the
|
||||
//! filtered audio twice (once via the routed stream, once via the
|
||||
//! default-sink monitor loopback).
|
||||
//!
|
||||
//! - **Local monitor** (pactl shell-out, app mode only): rerouting *moves*
|
||||
//! the chosen app off the sharer's speakers into the null-sink, so without
|
||||
//! this the sharer would go deaf to the very content they're sharing. We
|
||||
//! mirror the null-sink's monitor back to `@DEFAULT_SINK@` so the sharer
|
||||
//! hears it too. Only the chosen app is in the null-sink — never the
|
||||
//! desktop/call — so this can't echo back into the capture. It is loaded on
|
||||
//! the first routed stream (after the default-sink loopback is gone, so the
|
||||
//! two never coexist and feed back) and unloaded when the app stops.
|
||||
//!
|
||||
//! pactl is the right tool for the one-shot null-sink/loopback graph
|
||||
//! mutations. libpipewire is dragged in only when per-stream filtering
|
||||
//! is requested, because that needs registry-event subscription.
|
||||
|
||||
use anyhow::{Context, Result, bail};
|
||||
use std::cell::RefCell;
|
||||
use std::collections::BTreeMap;
|
||||
use std::process::Command;
|
||||
use std::rc::Rc;
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::thread::JoinHandle;
|
||||
|
||||
use crate::cli::HostOpts;
|
||||
|
||||
/// Owns the pactl-loaded modules plus, when filtering is active, the
|
||||
/// libpipewire stream-router thread. Drop unloads modules as a backstop;
|
||||
/// prefer [`Routing::shutdown`] explicitly so failures get logged.
|
||||
pub struct Routing {
|
||||
sink_module: Option<u32>,
|
||||
/// Shared with the event task so it can `take()` and unload on the
|
||||
/// first successful route. `Routing::shutdown` unloads whatever
|
||||
/// remains.
|
||||
loopback_module: Arc<Mutex<Option<u32>>>,
|
||||
/// The `null-sink.monitor → @DEFAULT_SINK@` loopback that lets the sharer
|
||||
/// hear the routed app. Shared with the event task, which loads it on the
|
||||
/// first routed stream and unloads it when the app stops. `None` outside
|
||||
/// app mode and whenever no app is currently routed.
|
||||
local_monitor_module: Arc<Mutex<Option<u32>>>,
|
||||
sink_name: String,
|
||||
stream_router: Option<StreamRouter>,
|
||||
event_task: Option<tokio::task::JoinHandle<()>>,
|
||||
}
|
||||
|
||||
impl Routing {
|
||||
/// Create the per-PID null-sink + loopback. If `opts.app` is set,
|
||||
/// also spawn the libpipewire thread that reroutes matching streams.
|
||||
pub async fn start(opts: &HostOpts) -> Result<Self> {
|
||||
let pid = std::process::id();
|
||||
let sink_name = format!("pixelpass_capture_{pid}");
|
||||
|
||||
let sink_module = load_module(&["module-null-sink", &format!("sink_name={sink_name}")])
|
||||
.context("failed to load module-null-sink")?;
|
||||
|
||||
// In strict per-app mode we never mirror the default sink: the viewer
|
||||
// must hear *only* the chosen app, never the whole desktop (which would
|
||||
// leak e.g. a voice call the sharer is in back to viewers — the echo
|
||||
// bug A23). Without strict mode (whole-desktop share, or best-effort
|
||||
// app filtering) we load the monitor loopback so the viewer hears
|
||||
// system audio immediately and during any gap before the app routes.
|
||||
// 20ms loopback latency keeps the mirrored audio tight; pactl's
|
||||
// default of 200ms is enough to be perceptible.
|
||||
let strict_app = opts.app.is_some() && opts.strict_audio;
|
||||
let loopback_module = if strict_app {
|
||||
None
|
||||
} else {
|
||||
Some(
|
||||
load_module(&[
|
||||
"module-loopback",
|
||||
"source=@DEFAULT_SINK@.monitor",
|
||||
&format!("sink={sink_name}"),
|
||||
"latency_msec=20",
|
||||
])
|
||||
.context("failed to load module-loopback (null-sink cleaned up on Drop)")?,
|
||||
)
|
||||
};
|
||||
|
||||
tracing::info!(
|
||||
sink_module,
|
||||
?loopback_module,
|
||||
strict_app,
|
||||
%sink_name,
|
||||
"audio routing: null-sink ready (loopback skipped in strict app mode)"
|
||||
);
|
||||
|
||||
let loopback_arc = Arc::new(Mutex::new(loopback_module));
|
||||
let local_monitor_arc = Arc::new(Mutex::new(None));
|
||||
let mut routing = Self {
|
||||
sink_module: Some(sink_module),
|
||||
loopback_module: Arc::clone(&loopback_arc),
|
||||
local_monitor_module: Arc::clone(&local_monitor_arc),
|
||||
sink_name: sink_name.clone(),
|
||||
stream_router: None,
|
||||
event_task: None,
|
||||
};
|
||||
|
||||
if let Some(app) = &opts.app {
|
||||
let (router, mut event_rx) = StreamRouter::spawn(app.clone(), sink_name.clone())?;
|
||||
let loopback_for_task = Arc::clone(&loopback_arc);
|
||||
let local_monitor_for_task = Arc::clone(&local_monitor_arc);
|
||||
let sink_name_for_task = sink_name.clone();
|
||||
let strict = opts.strict_audio;
|
||||
let event_task = tokio::spawn(async move {
|
||||
use crate::common::output::{self, AppAudioState};
|
||||
while let Some(ev) = event_rx.recv().await {
|
||||
match ev {
|
||||
Event::FirstRoutedStream => {
|
||||
let mid = loopback_for_task.lock().unwrap().take();
|
||||
if let Some(id) = mid {
|
||||
tracing::info!(
|
||||
"audio routing: first stream routed → unloading default-sink loopback"
|
||||
);
|
||||
unload_module(id);
|
||||
}
|
||||
// Mirror the routed app back to the sharer's own
|
||||
// speakers so they hear the content they're sharing.
|
||||
// Loaded *after* the default-sink loopback is gone so
|
||||
// the two never coexist (which would feed back), and
|
||||
// sourced from the null-sink monitor — the chosen app
|
||||
// only, never the desktop/call — so it can't echo into
|
||||
// the capture.
|
||||
if local_monitor_for_task.lock().unwrap().is_none() {
|
||||
match load_module(&[
|
||||
"module-loopback",
|
||||
&format!("source={sink_name_for_task}.monitor"),
|
||||
"sink=@DEFAULT_SINK@",
|
||||
"latency_msec=20",
|
||||
]) {
|
||||
Ok(id) => {
|
||||
tracing::info!(
|
||||
module = id,
|
||||
"audio routing: local monitor loaded (sharer hears the shared app)"
|
||||
);
|
||||
*local_monitor_for_task.lock().unwrap() = Some(id);
|
||||
}
|
||||
Err(e) => tracing::warn!(
|
||||
"audio routing: failed to load local monitor loopback: {e:#}"
|
||||
),
|
||||
}
|
||||
}
|
||||
// Tell the front-end the chosen app's audio is live.
|
||||
output::emit(output::Event::AppAudio {
|
||||
state: AppAudioState::Routed,
|
||||
});
|
||||
}
|
||||
Event::LastRoutedStreamGone => {
|
||||
// Routed app exited/paused mid-session. Notify the
|
||||
// front-end either way; the recovery differs by mode.
|
||||
output::emit(output::Event::AppAudio {
|
||||
state: AppAudioState::Lost,
|
||||
});
|
||||
// The shared app is gone, so its null-sink is silent:
|
||||
// stop mirroring it to the sharer's speakers. Re-loads
|
||||
// on the next FirstRoutedStream if the app resumes.
|
||||
if let Some(id) = local_monitor_for_task.lock().unwrap().take() {
|
||||
tracing::info!(
|
||||
module = id,
|
||||
"audio routing: last routed stream gone → unloading local monitor"
|
||||
);
|
||||
unload_module(id);
|
||||
}
|
||||
if strict {
|
||||
// Strict mode: do NOT restore the whole-desktop
|
||||
// loopback. Viewers hear silence until the app
|
||||
// produces audio again — never the rest of the
|
||||
// desktop (call included).
|
||||
tracing::info!(
|
||||
"audio routing: strict mode — last routed stream gone, leaving viewers silent"
|
||||
);
|
||||
continue;
|
||||
}
|
||||
// Best-effort mode: restore the default-sink loopback
|
||||
// so the viewer hears system audio again instead of
|
||||
// silence.
|
||||
if loopback_for_task.lock().unwrap().is_some() {
|
||||
continue;
|
||||
}
|
||||
tracing::info!(
|
||||
"audio routing: last routed stream gone → restoring default-sink loopback"
|
||||
);
|
||||
match load_module(&[
|
||||
"module-loopback",
|
||||
"source=@DEFAULT_SINK@.monitor",
|
||||
&format!("sink={sink_name_for_task}"),
|
||||
"latency_msec=20",
|
||||
]) {
|
||||
Ok(id) => {
|
||||
*loopback_for_task.lock().unwrap() = Some(id);
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!(
|
||||
"audio routing: failed to re-load loopback: {e:#}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
routing.stream_router = Some(router);
|
||||
routing.event_task = Some(event_task);
|
||||
}
|
||||
|
||||
// Strict per-app mode suppresses the default-sink loopback, so until the
|
||||
// chosen app's first stream routes the viewer hears *silence*. Emit an
|
||||
// initial `lost` at capture start (capture is lazy — this runs on the
|
||||
// first viewer) so the front-end can warn from the outset rather than
|
||||
// only after an app that *was* routed later stops (audit A23 P2/F1):
|
||||
// `LastRoutedStreamGone`→`lost` never fires for an app that never routed.
|
||||
if let Some(state) = initial_app_audio_state(opts) {
|
||||
crate::common::output::emit(crate::common::output::Event::AppAudio { state });
|
||||
}
|
||||
|
||||
Ok(routing)
|
||||
}
|
||||
|
||||
pub fn sink_name(&self) -> &str {
|
||||
&self.sink_name
|
||||
}
|
||||
|
||||
/// Stop the stream router (if any), then unload loopback (if still
|
||||
/// loaded), then unload the null-sink. Order matters: PipeWire can
|
||||
/// leave zombie links if you destroy a sink with active inputs.
|
||||
///
|
||||
/// Every step is a `take()`, so this is idempotent — `Drop` calls it again
|
||||
/// as a backstop and the second run is a no-op.
|
||||
fn cleanup(&mut self) {
|
||||
if let Some(router) = self.stream_router.take() {
|
||||
router.shutdown();
|
||||
}
|
||||
if let Some(task) = self.event_task.take() {
|
||||
task.abort();
|
||||
}
|
||||
if let Some(id) = self.loopback_module.lock().unwrap().take() {
|
||||
unload_module(id);
|
||||
}
|
||||
// Unload the local monitor before the null-sink it reads from, so the
|
||||
// sink has no active loopback reader when it's destroyed.
|
||||
if let Some(id) = self.local_monitor_module.lock().unwrap().take() {
|
||||
unload_module(id);
|
||||
}
|
||||
if let Some(id) = self.sink_module.take() {
|
||||
unload_module(id);
|
||||
}
|
||||
}
|
||||
|
||||
/// Consume the routing and tear it all down now. `Drop` is the backstop;
|
||||
/// the real work lives in [`cleanup`](Self::cleanup).
|
||||
pub fn shutdown(mut self) {
|
||||
self.cleanup();
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Routing {
|
||||
fn drop(&mut self) {
|
||||
self.cleanup();
|
||||
}
|
||||
}
|
||||
|
||||
/// The app-audio state to announce at capture start, if any. Only strict per-app
|
||||
/// mode warrants one: there the loopback is suppressed, so the viewer hears
|
||||
/// silence until the chosen app's first stream routes — surface that as an
|
||||
/// initial `lost`. In every other mode (whole-desktop, or best-effort app
|
||||
/// filtering) the loopback keeps audio flowing from the outset, so there is no
|
||||
/// initial gap to report. Pure: no I/O, so the emit decision is unit-testable.
|
||||
pub(super) fn initial_app_audio_state(
|
||||
opts: &HostOpts,
|
||||
) -> Option<crate::common::output::AppAudioState> {
|
||||
(opts.app.is_some() && opts.strict_audio).then_some(crate::common::output::AppAudioState::Lost)
|
||||
}
|
||||
|
||||
// ──────────────────────────────────────────────────────────────────────
|
||||
// App enumeration (interactive picker source)
|
||||
// ──────────────────────────────────────────────────────────────────────
|
||||
|
||||
/// One deduplicated app currently producing audio. The picker in
|
||||
/// interactive mode shows these as the per-app capture choices.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct App {
|
||||
pub name: String,
|
||||
pub stream_count: u32,
|
||||
}
|
||||
|
||||
/// Enumerate apps currently sending audio to any sink, deduplicated by
|
||||
/// `application.name`. Returns an empty Vec if nothing is playing.
|
||||
pub fn list_playing_apps() -> Result<Vec<App>> {
|
||||
let output = Command::new("pactl")
|
||||
.args(["-f", "json", "list", "sink-inputs"])
|
||||
.output()
|
||||
.context("failed to run `pactl -f json list sink-inputs`")?;
|
||||
if !output.status.success() {
|
||||
bail!(
|
||||
"pactl list sink-inputs failed: {}",
|
||||
String::from_utf8_lossy(&output.stderr).trim()
|
||||
);
|
||||
}
|
||||
parse_sink_inputs(&output.stdout)
|
||||
}
|
||||
|
||||
fn parse_sink_inputs(stdout: &[u8]) -> Result<Vec<App>> {
|
||||
let entries: Vec<SinkInput> =
|
||||
serde_json::from_slice(stdout).context("pactl returned unparseable JSON")?;
|
||||
let mut counts: BTreeMap<String, u32> = BTreeMap::new();
|
||||
for entry in entries {
|
||||
let Some(name) = entry.properties.application_name else {
|
||||
continue;
|
||||
};
|
||||
let trimmed = name.trim();
|
||||
if trimmed.is_empty() {
|
||||
continue;
|
||||
}
|
||||
*counts.entry(trimmed.to_string()).or_insert(0) += 1;
|
||||
}
|
||||
Ok(counts
|
||||
.into_iter()
|
||||
.map(|(name, stream_count)| App { name, stream_count })
|
||||
.collect())
|
||||
}
|
||||
|
||||
#[derive(serde::Deserialize)]
|
||||
struct SinkInput {
|
||||
properties: SinkInputProperties,
|
||||
}
|
||||
|
||||
#[derive(serde::Deserialize)]
|
||||
struct SinkInputProperties {
|
||||
#[serde(rename = "application.name")]
|
||||
application_name: Option<String>,
|
||||
}
|
||||
|
||||
// ──────────────────────────────────────────────────────────────────────
|
||||
// pactl module helpers
|
||||
// ──────────────────────────────────────────────────────────────────────
|
||||
|
||||
fn load_module(args: &[&str]) -> Result<u32> {
|
||||
let output = Command::new("pactl")
|
||||
.arg("load-module")
|
||||
.args(args)
|
||||
.output()
|
||||
.context("failed to run pactl load-module")?;
|
||||
if !output.status.success() {
|
||||
bail!(
|
||||
"pactl load-module failed: {}",
|
||||
String::from_utf8_lossy(&output.stderr).trim()
|
||||
);
|
||||
}
|
||||
let id_str = String::from_utf8(output.stdout)
|
||||
.context("pactl returned non-UTF-8")?
|
||||
.trim()
|
||||
.to_string();
|
||||
id_str
|
||||
.parse::<u32>()
|
||||
.with_context(|| format!("pactl returned unexpected module ID: {id_str:?}"))
|
||||
}
|
||||
|
||||
fn unload_module(id: u32) {
|
||||
let result = Command::new("pactl")
|
||||
.arg("unload-module")
|
||||
.arg(id.to_string())
|
||||
.output();
|
||||
match result {
|
||||
Ok(output) if output.status.success() => {
|
||||
tracing::info!(module = id, "audio routing: unloaded pactl module");
|
||||
}
|
||||
Ok(output) => {
|
||||
tracing::warn!(
|
||||
module = id,
|
||||
stderr = %String::from_utf8_lossy(&output.stderr).trim(),
|
||||
"audio routing: pactl unload-module exited non-zero"
|
||||
);
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!(
|
||||
module = id,
|
||||
"audio routing: failed to run pactl unload-module: {e}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ──────────────────────────────────────────────────────────────────────
|
||||
// Per-stream routing (libpipewire thread)
|
||||
// ──────────────────────────────────────────────────────────────────────
|
||||
|
||||
/// Command from tokio → libpipewire thread.
|
||||
enum Cmd {
|
||||
/// Clear `target.object` for everything we routed, then quit the
|
||||
/// MainLoop so the thread joins.
|
||||
Shutdown,
|
||||
}
|
||||
|
||||
/// Event from libpipewire thread → tokio. The pair drives loopback
|
||||
/// oscillation: unload on `FirstRoutedStream`, re-load on
|
||||
/// `LastRoutedStreamGone`. Both fire on count-transitions (0→N and N→0
|
||||
/// respectively), not on every change.
|
||||
enum Event {
|
||||
/// At least one stream is now routed to our sink. Receiver unloads
|
||||
/// the default-sink loopback so the filtered audio isn't doubled.
|
||||
FirstRoutedStream,
|
||||
/// The last routed stream just disappeared (app closed, paused,
|
||||
/// switched output). Receiver re-loads the default-sink loopback so
|
||||
/// the viewer doesn't go silent.
|
||||
LastRoutedStreamGone,
|
||||
}
|
||||
|
||||
/// Handle to the libpipewire stream-router thread.
|
||||
pub struct StreamRouter {
|
||||
cmd_tx: pipewire::channel::Sender<Cmd>,
|
||||
thread: Option<JoinHandle<()>>,
|
||||
}
|
||||
|
||||
impl StreamRouter {
|
||||
/// Spawn the libpipewire thread. Returns the router handle and the
|
||||
/// event receiver tokio side polls.
|
||||
fn spawn(
|
||||
filter_name: String,
|
||||
sink_name: String,
|
||||
) -> Result<(Self, tokio::sync::mpsc::UnboundedReceiver<Event>)> {
|
||||
let (cmd_tx, cmd_rx) = pipewire::channel::channel::<Cmd>();
|
||||
let (event_tx, event_rx) = tokio::sync::mpsc::unbounded_channel::<Event>();
|
||||
|
||||
let thread = std::thread::Builder::new()
|
||||
.name("pixelpass-pw-router".to_string())
|
||||
.spawn(move || {
|
||||
if let Err(e) = run_router(filter_name, sink_name, cmd_rx, event_tx) {
|
||||
tracing::warn!("audio routing: libpipewire thread exited with error: {e:#}");
|
||||
}
|
||||
})
|
||||
.context("failed to spawn libpipewire router thread")?;
|
||||
|
||||
Ok((
|
||||
Self {
|
||||
cmd_tx,
|
||||
thread: Some(thread),
|
||||
},
|
||||
event_rx,
|
||||
))
|
||||
}
|
||||
|
||||
fn shutdown(mut self) {
|
||||
// Best-effort: if the send fails the thread is already gone.
|
||||
let _ = self.cmd_tx.send(Cmd::Shutdown);
|
||||
if let Some(t) = self.thread.take()
|
||||
&& let Err(e) = t.join()
|
||||
{
|
||||
tracing::warn!("audio routing: pw thread join failed: {e:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Body of the libpipewire thread. Owns MainLoop, registry listener, and
|
||||
/// all PipeWire proxies for the duration of the routing session.
|
||||
fn run_router(
|
||||
filter_name: String,
|
||||
sink_name: String,
|
||||
cmd_rx: pipewire::channel::Receiver<Cmd>,
|
||||
event_tx: tokio::sync::mpsc::UnboundedSender<Event>,
|
||||
) -> Result<()> {
|
||||
use pipewire::{self as pw, types::ObjectType};
|
||||
|
||||
let main_loop =
|
||||
pw::main_loop::MainLoopRc::new(None).context("pw main loop construction failed")?;
|
||||
let context =
|
||||
pw::context::ContextRc::new(&main_loop, None).context("pw context construction failed")?;
|
||||
let core = context
|
||||
.connect_rc(None)
|
||||
.context("pw core connect failed (is the daemon running?)")?;
|
||||
let registry = core.get_registry_rc().context("pw get_registry failed")?;
|
||||
|
||||
let state = Rc::new(RefCell::new(RouterState {
|
||||
sink_serial: None,
|
||||
default_metadata: None,
|
||||
routed_node_ids: Vec::new(),
|
||||
pending: Vec::new(),
|
||||
}));
|
||||
|
||||
// Cmd handler: clear metadata for routed streams, then quit.
|
||||
let main_loop_for_cmd = main_loop.clone();
|
||||
let state_for_cmd = Rc::clone(&state);
|
||||
let _cmd_recv = cmd_rx.attach(main_loop.loop_(), move |cmd| match cmd {
|
||||
Cmd::Shutdown => {
|
||||
let s = state_for_cmd.borrow();
|
||||
if let Some(meta) = &s.default_metadata {
|
||||
for &nid in &s.routed_node_ids {
|
||||
meta.set_property(nid, "target.object", None, None);
|
||||
}
|
||||
if !s.routed_node_ids.is_empty() {
|
||||
tracing::info!(
|
||||
n = s.routed_node_ids.len(),
|
||||
"audio routing: cleared target.object on routed streams before quitting"
|
||||
);
|
||||
}
|
||||
}
|
||||
main_loop_for_cmd.quit();
|
||||
}
|
||||
});
|
||||
|
||||
let filter_lower = filter_name.to_ascii_lowercase();
|
||||
let sink_name_owned = sink_name.clone();
|
||||
let registry_weak = registry.downgrade();
|
||||
let state_for_reg = Rc::clone(&state);
|
||||
let event_tx_for_reg = event_tx.clone();
|
||||
let state_for_remove = Rc::clone(&state);
|
||||
let event_tx_for_remove = event_tx.clone();
|
||||
|
||||
let _reg_listener = registry
|
||||
.add_listener_local()
|
||||
.global(move |obj| {
|
||||
let Some(reg) = registry_weak.upgrade() else {
|
||||
return;
|
||||
};
|
||||
match obj.type_ {
|
||||
ObjectType::Node => {
|
||||
let Some(props) = obj.props.as_ref() else {
|
||||
return;
|
||||
};
|
||||
if props.get("node.name") == Some(sink_name_owned.as_str()) {
|
||||
if let Some(serial) = props
|
||||
.get("object.serial")
|
||||
.and_then(|s| s.parse::<u32>().ok())
|
||||
{
|
||||
state_for_reg.borrow_mut().sink_serial = Some(serial);
|
||||
tracing::info!(serial, "audio routing: pixelpass sink registered");
|
||||
try_flush(&state_for_reg, &event_tx_for_reg);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if props.get("media.class") != Some("Stream/Output/Audio") {
|
||||
return;
|
||||
}
|
||||
let Some(app) = props.get("application.name") else {
|
||||
return;
|
||||
};
|
||||
if !app.eq_ignore_ascii_case(&filter_lower) {
|
||||
return;
|
||||
}
|
||||
tracing::info!(
|
||||
node_id = obj.id,
|
||||
%app,
|
||||
"audio routing: matched stream, queued for route"
|
||||
);
|
||||
state_for_reg.borrow_mut().pending.push(obj.id);
|
||||
try_flush(&state_for_reg, &event_tx_for_reg);
|
||||
}
|
||||
ObjectType::Metadata => {
|
||||
let Some(props) = obj.props.as_ref() else {
|
||||
return;
|
||||
};
|
||||
if props.get("metadata.name") != Some("default") {
|
||||
return;
|
||||
}
|
||||
let metadata: pw::metadata::Metadata = match reg.bind(obj) {
|
||||
Ok(m) => m,
|
||||
Err(e) => {
|
||||
tracing::warn!("audio routing: bind default metadata failed: {e}");
|
||||
return;
|
||||
}
|
||||
};
|
||||
state_for_reg.borrow_mut().default_metadata = Some(metadata);
|
||||
tracing::info!("audio routing: default metadata bound");
|
||||
try_flush(&state_for_reg, &event_tx_for_reg);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
})
|
||||
.global_remove(move |id| {
|
||||
handle_global_remove(&state_for_remove, &event_tx_for_remove, id);
|
||||
})
|
||||
.register();
|
||||
|
||||
tracing::info!(filter = %filter_name, "audio routing: pw thread running");
|
||||
main_loop.run();
|
||||
tracing::info!("audio routing: pw thread exiting");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
struct RouterState {
|
||||
sink_serial: Option<u32>,
|
||||
default_metadata: Option<pipewire::metadata::Metadata>,
|
||||
routed_node_ids: Vec<u32>,
|
||||
pending: Vec<u32>,
|
||||
}
|
||||
|
||||
/// Drop the vanished node from `routed_node_ids` and `pending`. If it
|
||||
/// was the last routed stream, emit `LastRoutedStreamGone` so the
|
||||
/// tokio side restores the default-sink loopback.
|
||||
fn handle_global_remove(
|
||||
state: &Rc<RefCell<RouterState>>,
|
||||
event_tx: &tokio::sync::mpsc::UnboundedSender<Event>,
|
||||
id: u32,
|
||||
) {
|
||||
let mut s = state.borrow_mut();
|
||||
let was_routed = !s.routed_node_ids.is_empty();
|
||||
s.routed_node_ids.retain(|&x| x != id);
|
||||
s.pending.retain(|&x| x != id);
|
||||
if was_routed && s.routed_node_ids.is_empty() {
|
||||
tracing::info!(
|
||||
node_id = id,
|
||||
"audio routing: last routed stream disappeared"
|
||||
);
|
||||
let _ = event_tx.send(Event::LastRoutedStreamGone);
|
||||
}
|
||||
}
|
||||
|
||||
/// Drain pending streams to the sink, but only once both prerequisites
|
||||
/// (sink serial known + default metadata bound) are in place. Emits
|
||||
/// `FirstRoutedStream` when routed count crosses 0→N (so it fires
|
||||
/// each time the count comes back up from zero, not just the first
|
||||
/// time — pairs with `LastRoutedStreamGone` to oscillate the loopback).
|
||||
fn try_flush(
|
||||
state: &Rc<RefCell<RouterState>>,
|
||||
event_tx: &tokio::sync::mpsc::UnboundedSender<Event>,
|
||||
) {
|
||||
let mut s = state.borrow_mut();
|
||||
let Some(serial) = s.sink_serial else { return };
|
||||
if s.default_metadata.is_none() {
|
||||
return;
|
||||
}
|
||||
if s.pending.is_empty() {
|
||||
return;
|
||||
}
|
||||
let was_empty = s.routed_node_ids.is_empty();
|
||||
let serial_str = serial.to_string();
|
||||
let pending = std::mem::take(&mut s.pending);
|
||||
if let Some(meta) = &s.default_metadata {
|
||||
for nid in &pending {
|
||||
meta.set_property(*nid, "target.object", Some("Spa:Id"), Some(&serial_str));
|
||||
tracing::info!(
|
||||
node_id = *nid,
|
||||
sink_serial = serial,
|
||||
"audio routing: stream routed to pixelpass sink"
|
||||
);
|
||||
}
|
||||
}
|
||||
s.routed_node_ids.extend(pending);
|
||||
if was_empty && !s.routed_node_ids.is_empty() {
|
||||
let _ = event_tx.send(Event::FirstRoutedStream);
|
||||
}
|
||||
}
|
||||
+16
-31
@@ -1,40 +1,25 @@
|
||||
//! Capture dispatcher. Selects the per-display-server pipeline and returns its
|
||||
//! [`CaptureHandle`]. Each backend owns its own children and tears them down
|
||||
//! via its own Drop / shutdown.
|
||||
//! Capture dispatcher. Picks the per-display-server source backend and returns
|
||||
//! the shared [`pipeline::CaptureHandle`]. The handle itself, its teardown, and
|
||||
//! the whole encode/serve tail are display-agnostic and live in
|
||||
//! [`super::pipeline`]; the backends differ only in how they obtain a video
|
||||
//! source element.
|
||||
|
||||
use anyhow::{Result, bail};
|
||||
use anyhow::Result;
|
||||
|
||||
use crate::cli::HostOpts;
|
||||
use crate::common::display::DisplayServer;
|
||||
use crate::host::wayland;
|
||||
use crate::host::pipeline::CaptureHandle;
|
||||
use crate::host::quality::EffectiveQuality;
|
||||
use crate::host::{wayland, x11};
|
||||
|
||||
pub enum CaptureHandle {
|
||||
Wayland(wayland::CaptureHandle),
|
||||
}
|
||||
|
||||
impl CaptureHandle {
|
||||
pub fn local_port(&self) -> u16 {
|
||||
match self {
|
||||
CaptureHandle::Wayland(h) => h.local_port(),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn shutdown(self) {
|
||||
match self {
|
||||
CaptureHandle::Wayland(h) => h.shutdown().await,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn spawn(display: DisplayServer, opts: &HostOpts) -> Result<CaptureHandle> {
|
||||
pub async fn spawn(
|
||||
display: DisplayServer,
|
||||
opts: &HostOpts,
|
||||
quality: &EffectiveQuality,
|
||||
) -> Result<CaptureHandle> {
|
||||
match display {
|
||||
DisplayServer::Wayland => {
|
||||
let h = wayland::start(opts).await?;
|
||||
Ok(CaptureHandle::Wayland(h))
|
||||
}
|
||||
DisplayServer::X11 => {
|
||||
bail!("X11 capture pipeline not yet implemented (Phase 2 follow-up)");
|
||||
}
|
||||
DisplayServer::Wayland => wayland::start(opts, quality).await,
|
||||
DisplayServer::X11 => x11::start(opts, quality).await,
|
||||
DisplayServer::Unknown => unreachable!("caller guarantees display != Unknown"),
|
||||
}
|
||||
}
|
||||
|
||||
+473
-60
@@ -1,18 +1,56 @@
|
||||
pub mod audio;
|
||||
mod capture;
|
||||
mod pipeline;
|
||||
mod quality;
|
||||
mod serve;
|
||||
mod wayland;
|
||||
mod x11;
|
||||
|
||||
use anyhow::{Result, bail};
|
||||
use iroh::Endpoint;
|
||||
use iroh::endpoint::{Connection, presets};
|
||||
use iroh::endpoint::Connection;
|
||||
use iroh::{Endpoint, EndpointAddr};
|
||||
use iroh_tickets::endpoint::EndpointTicket;
|
||||
use std::collections::HashMap;
|
||||
use std::time::Duration;
|
||||
use tokio::sync::{mpsc, oneshot};
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
use crate::cli::HostOpts;
|
||||
use crate::common::{alpn::ALPN, deps, display::DisplayServer, signal};
|
||||
use crate::common::{
|
||||
bandwidth, config, config::BandwidthStatus, deps, display::DisplayServer, endpoint, output,
|
||||
signal, tunnel,
|
||||
};
|
||||
|
||||
use self::pipeline::CaptureHandle;
|
||||
use self::quality::EffectiveQuality;
|
||||
|
||||
/// Messages from per-viewer tasks (and the GUI command channel) to the
|
||||
/// capture supervisor.
|
||||
// The shared `Viewer` suffix is the point — these are all viewer lifecycle
|
||||
// messages — so keep the descriptive names.
|
||||
#[allow(clippy::enum_variant_names)]
|
||||
enum SupervisorMsg {
|
||||
/// A new viewer wants in. Supervisor replies with the local capture HTTP
|
||||
/// port to connect to, or an error string if the host is full or capture
|
||||
/// spawn failed. `cancel` is the viewer's own token — the supervisor keeps
|
||||
/// it so a later `KickViewer` can tear this viewer's stream down.
|
||||
AddViewer {
|
||||
id: String,
|
||||
cancel: CancellationToken,
|
||||
reply: oneshot::Sender<Result<u16, String>>,
|
||||
},
|
||||
/// A viewer's session ended. Supervisor decrements the count and tears
|
||||
/// down capture if it just hit zero.
|
||||
RemoveViewer { id: String },
|
||||
/// Host asked (via the GUI command channel) to disconnect a viewer by
|
||||
/// endpoint id. Cancels that viewer's token; the normal teardown path then
|
||||
/// emits the `ViewerLeft`.
|
||||
KickViewer { id: String },
|
||||
}
|
||||
|
||||
pub async fn run(opts: HostOpts) -> Result<()> {
|
||||
let display = DisplayServer::resolve(opts.display_server);
|
||||
deps::check_host_binaries(display)?;
|
||||
deps::check_host_binaries(display, &opts)?;
|
||||
|
||||
if display == DisplayServer::Unknown {
|
||||
bail!(
|
||||
@@ -21,108 +59,422 @@ pub async fn run(opts: HostOpts) -> Result<()> {
|
||||
);
|
||||
}
|
||||
|
||||
// Resolve quality first: Auto sizes its bandwidth budget against the viewer
|
||||
// cap the host will honor. To avoid a circular dependency (the auto-derived
|
||||
// cap itself depends on bitrate), Auto sizes against the user's explicit
|
||||
// --max-viewers when given, else a single viewer. The resulting effective
|
||||
// bitrate then feeds the cap resolution below.
|
||||
let sizing_viewers = opts.max_viewers.filter(|&n| n > 0).unwrap_or(1);
|
||||
let quality = quality::resolve(&opts, sizing_viewers);
|
||||
|
||||
let resolution = resolve_max_viewers(&opts, quality.bitrate);
|
||||
if resolution.value == 0 {
|
||||
bail!("--max-viewers must be at least 1");
|
||||
}
|
||||
|
||||
let cancel = signal::install_ctrl_c();
|
||||
|
||||
let endpoint = Endpoint::builder(presets::N0)
|
||||
.alpns(vec![ALPN.to_vec()])
|
||||
.bind()
|
||||
.await?;
|
||||
let endpoint = endpoint::bind(opts.relay.as_deref()).await?;
|
||||
|
||||
// Relay-only ticket: wait for the home relay to connect, then keep only
|
||||
// the endpoint id + relay URL and drop the direct IP candidates. The relay
|
||||
// coordinates hole-punching to a direct path right after connect, so this
|
||||
// doesn't change whether peers can reach each other — it just keeps the
|
||||
// ticket short (~140 vs ~320 chars) and stops it from leaking LAN /
|
||||
// Docker-bridge addresses to whoever receives the ticket. Awaiting online()
|
||||
// first guarantees the relay URL is actually present (addr() right after
|
||||
// bind can return before the relay handshake completes); the 15s cap means
|
||||
// a relay outage degrades to a possibly-incomplete ticket rather than a hang
|
||||
// (n0 DNS discovery still resolves the id in that case).
|
||||
if tokio::time::timeout(Duration::from_secs(15), endpoint.online())
|
||||
.await
|
||||
.is_err()
|
||||
{
|
||||
tracing::warn!("home relay not connected within 15s; ticket may be incomplete");
|
||||
}
|
||||
let addr = endpoint.addr();
|
||||
let ticket = EndpointTicket::new(addr);
|
||||
let clipboard_ok = opts.interactive && copy_to_clipboard(&ticket.to_string());
|
||||
print_host_banner(&ticket, display, &opts, clipboard_ok);
|
||||
let relay_only =
|
||||
EndpointAddr::new(addr.id).with_addrs(addr.addrs.iter().filter(|a| a.is_relay()).cloned());
|
||||
let ticket = EndpointTicket::new(relay_only);
|
||||
let ticket_str = ticket.to_string();
|
||||
let clipboard_ok = opts.interactive && copy_to_clipboard(&ticket_str);
|
||||
print_host_banner(&ticket, display, &opts, &quality, &resolution, clipboard_ok);
|
||||
|
||||
let result = accept_loop(&endpoint, display, &opts, cancel.clone()).await;
|
||||
output::emit(output::Event::Ticket { value: &ticket_str });
|
||||
let display_str = format!("{display:?}");
|
||||
let capture = capture_summary(&opts);
|
||||
let dims = quality.dimensions_summary();
|
||||
let cap_source = resolution.source.label();
|
||||
output::emit(output::Event::HostInfo {
|
||||
display_server: &display_str,
|
||||
capture: &capture,
|
||||
quality: &quality.label,
|
||||
dimensions: &dims,
|
||||
hw_encode: !opts.no_hwencode,
|
||||
max_viewers: resolution.value,
|
||||
max_viewers_source: &cap_source,
|
||||
});
|
||||
|
||||
let (sup_tx, sup_rx) = mpsc::channel::<SupervisorMsg>(16);
|
||||
let supervisor = tokio::spawn(supervise(
|
||||
opts.clone(),
|
||||
quality,
|
||||
display,
|
||||
resolution.value,
|
||||
sup_rx,
|
||||
));
|
||||
|
||||
// Command channel for the GUI front-end: read `kick <endpoint-id>` lines
|
||||
// off stdin. Only when machine-driven (`--output json`) — a human host has
|
||||
// nothing to type here, and we don't want to swallow terminal input. Runs
|
||||
// on a plain OS thread (not a tokio task) so a read parked on stdin can't
|
||||
// hold up runtime shutdown on Ctrl+C; the thread dies with the process.
|
||||
if output::json_enabled() {
|
||||
spawn_kick_listener(sup_tx.clone());
|
||||
}
|
||||
|
||||
accept_loop(&endpoint, sup_tx.clone(), cancel.clone()).await;
|
||||
|
||||
drop(sup_tx);
|
||||
let _ = supervisor.await;
|
||||
|
||||
endpoint.close().await;
|
||||
result
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn accept_loop(
|
||||
endpoint: &Endpoint,
|
||||
display: DisplayServer,
|
||||
opts: &HostOpts,
|
||||
sup_tx: mpsc::Sender<SupervisorMsg>,
|
||||
cancel: CancellationToken,
|
||||
) -> Result<()> {
|
||||
tokio::select! {
|
||||
_ = cancel.cancelled() => {
|
||||
tracing::info!("cancellation requested before any peer connected");
|
||||
Ok(())
|
||||
}
|
||||
accepted = endpoint.accept() => {
|
||||
let Some(incoming) = accepted else {
|
||||
bail!("endpoint stopped accepting connections");
|
||||
};
|
||||
let conn = incoming.await?;
|
||||
let remote = conn.remote_id();
|
||||
tracing::info!(%remote, "peer connected");
|
||||
eprintln!("\n[pixelpass] peer connected: {remote}\n");
|
||||
handle_peer(conn, display, opts, cancel).await
|
||||
) {
|
||||
loop {
|
||||
tokio::select! {
|
||||
_ = cancel.cancelled() => {
|
||||
tracing::info!("cancellation requested — closing accept loop");
|
||||
return;
|
||||
}
|
||||
accepted = endpoint.accept() => {
|
||||
let Some(incoming) = accepted else {
|
||||
tracing::info!("endpoint stopped accepting connections");
|
||||
return;
|
||||
};
|
||||
let conn = match incoming.await {
|
||||
Ok(c) => c,
|
||||
Err(e) => {
|
||||
tracing::warn!("incoming connection failed: {e:#}");
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let sup_tx = sup_tx.clone();
|
||||
let cancel = cancel.clone();
|
||||
tokio::spawn(handle_peer(conn, sup_tx, cancel));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn handle_peer(
|
||||
conn: Connection,
|
||||
display: DisplayServer,
|
||||
opts: &HostOpts,
|
||||
sup_tx: mpsc::Sender<SupervisorMsg>,
|
||||
cancel: CancellationToken,
|
||||
) -> Result<()> {
|
||||
let (quic_send, quic_recv) = conn.accept_bi().await?;
|
||||
) {
|
||||
let remote = conn.remote_id();
|
||||
let id = remote.to_string();
|
||||
// This viewer's own kill switch: the supervisor holds a clone so a `kick`
|
||||
// can cancel it, and the stream select! below watches it.
|
||||
let peer_cancel = CancellationToken::new();
|
||||
|
||||
let capture_handle = capture::spawn(display, opts).await?;
|
||||
let port = capture_handle.local_port();
|
||||
let tcp = wayland::connect_to_capture(port, std::time::Duration::from_secs(5)).await?;
|
||||
|
||||
let bridge = crate::common::tunnel::bridge(quic_send, quic_recv, tcp);
|
||||
|
||||
tokio::select! {
|
||||
res = bridge => {
|
||||
if let Err(e) = res {
|
||||
tracing::warn!("bridge ended with error: {e:#}");
|
||||
} else {
|
||||
tracing::info!("bridge closed cleanly");
|
||||
}
|
||||
let (reply_tx, reply_rx) = oneshot::channel();
|
||||
let add = SupervisorMsg::AddViewer {
|
||||
id: id.clone(),
|
||||
cancel: peer_cancel.clone(),
|
||||
reply: reply_tx,
|
||||
};
|
||||
if sup_tx.send(add).await.is_err() {
|
||||
tracing::warn!(%remote, "supervisor channel closed; dropping peer");
|
||||
return;
|
||||
}
|
||||
let port = match reply_rx.await {
|
||||
Ok(Ok(p)) => p,
|
||||
Ok(Err(reason)) => {
|
||||
tracing::warn!(%remote, %reason, "refusing viewer");
|
||||
eprintln!("[pixelpass] refusing viewer {remote}: {reason}");
|
||||
return;
|
||||
}
|
||||
Err(_) => {
|
||||
tracing::warn!(%remote, "supervisor reply dropped; dropping peer");
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
let (quic_send, quic_recv) = match conn.accept_bi().await {
|
||||
Ok(s) => s,
|
||||
Err(e) => {
|
||||
tracing::warn!(%remote, "accept_bi failed: {e:#}");
|
||||
let _ = sup_tx.send(SupervisorMsg::RemoveViewer { id }).await;
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
eprintln!("[pixelpass] viewer connected: {remote}");
|
||||
|
||||
let tcp = match serve::connect_to_capture(port, Duration::from_secs(5)).await {
|
||||
Ok(t) => t,
|
||||
Err(e) => {
|
||||
tracing::warn!(%remote, "connect_to_capture failed: {e:#}");
|
||||
let _ = sup_tx.send(SupervisorMsg::RemoveViewer { id }).await;
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
let bridge = tunnel::bridge(quic_send, quic_recv, tcp);
|
||||
tokio::select! {
|
||||
res = bridge => match res {
|
||||
Ok(()) => tracing::info!(%remote, "bridge closed cleanly"),
|
||||
Err(e) => tracing::info!(%remote, "bridge ended: {e:#}"),
|
||||
},
|
||||
_ = cancel.cancelled() => {
|
||||
tracing::info!("cancellation requested during stream");
|
||||
tracing::info!(%remote, "cancellation during stream");
|
||||
}
|
||||
_ = peer_cancel.cancelled() => {
|
||||
tracing::info!(%remote, "kicked by host");
|
||||
}
|
||||
}
|
||||
|
||||
capture_handle.shutdown().await;
|
||||
Ok(())
|
||||
eprintln!("[pixelpass] viewer disconnected: {remote}");
|
||||
let _ = sup_tx.send(SupervisorMsg::RemoveViewer { id }).await;
|
||||
}
|
||||
|
||||
/// Read `kick <endpoint-id>` lines off stdin and forward them to the
|
||||
/// supervisor. Runs on a detached OS thread (see the call site for why). Ends
|
||||
/// when stdin hits EOF (the GUI closed the pipe) or the supervisor is gone.
|
||||
fn spawn_kick_listener(sup_tx: mpsc::Sender<SupervisorMsg>) {
|
||||
use std::io::BufRead;
|
||||
std::thread::spawn(move || {
|
||||
let stdin = std::io::stdin();
|
||||
for line in stdin.lock().lines().map_while(Result::ok) {
|
||||
let Some(id) = line.trim().strip_prefix("kick ") else {
|
||||
continue;
|
||||
};
|
||||
let msg = SupervisorMsg::KickViewer {
|
||||
id: id.trim().to_string(),
|
||||
};
|
||||
// blocking_send is valid here: this is a plain thread, not inside
|
||||
// the tokio runtime. An Err means the supervisor closed — stop.
|
||||
if sup_tx.blocking_send(msg).is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Owns the single shared CaptureHandle and the active viewer count. Spawns
|
||||
/// capture lazily on the first AddViewer; tears it down when the count drops
|
||||
/// back to zero. Enforces the max-viewers cap by refusing AddViewer when
|
||||
/// the count is already at the cap.
|
||||
async fn supervise(
|
||||
opts: HostOpts,
|
||||
quality: EffectiveQuality,
|
||||
display: DisplayServer,
|
||||
max_viewers: u32,
|
||||
mut rx: mpsc::Receiver<SupervisorMsg>,
|
||||
) {
|
||||
let mut handle: Option<CaptureHandle> = None;
|
||||
// Active viewers, keyed by endpoint id, holding each one's kill switch.
|
||||
// The count is just `viewers.len()`. (A given endpoint connecting twice is
|
||||
// a non-case here: each viewer process uses a fresh ephemeral identity.)
|
||||
let mut viewers: HashMap<String, CancellationToken> = HashMap::new();
|
||||
|
||||
while let Some(msg) = rx.recv().await {
|
||||
match msg {
|
||||
SupervisorMsg::AddViewer { id, cancel, reply } => {
|
||||
let count = viewers.len() as u32;
|
||||
if count >= max_viewers {
|
||||
let reason =
|
||||
format!("host is full ({count} of {max_viewers} viewers connected)");
|
||||
output::emit(output::Event::ViewerRefused { reason: &reason });
|
||||
let _ = reply.send(Err(reason));
|
||||
continue;
|
||||
}
|
||||
|
||||
if handle.is_none() {
|
||||
tracing::info!("first viewer arriving — spawning capture");
|
||||
match capture::spawn(display, &opts, &quality).await {
|
||||
Ok(h) => {
|
||||
handle = Some(h);
|
||||
output::emit(output::Event::Capture {
|
||||
state: output::CaptureState::Started,
|
||||
});
|
||||
}
|
||||
Err(e) => {
|
||||
let _ = reply.send(Err(format!("capture spawn failed: {e:#}")));
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let port = handle.as_ref().expect("handle was just set").local_port();
|
||||
viewers.insert(id.clone(), cancel);
|
||||
let active = viewers.len() as u32;
|
||||
let _ = reply.send(Ok(port));
|
||||
output::emit(output::Event::ViewerJoined {
|
||||
id: &id,
|
||||
active,
|
||||
max: max_viewers,
|
||||
});
|
||||
tracing::info!(active, cap = max_viewers, "viewer joined");
|
||||
}
|
||||
SupervisorMsg::RemoveViewer { id } => {
|
||||
// A given viewer task only ever sends RemoveViewer once, but the
|
||||
// map remove is the source of truth either way.
|
||||
if viewers.remove(&id).is_none() {
|
||||
continue;
|
||||
}
|
||||
let active = viewers.len() as u32;
|
||||
output::emit(output::Event::ViewerLeft {
|
||||
id: &id,
|
||||
active,
|
||||
max: max_viewers,
|
||||
});
|
||||
tracing::info!(active, cap = max_viewers, "viewer left");
|
||||
if active == 0
|
||||
&& let Some(h) = handle.take()
|
||||
{
|
||||
tracing::info!("last viewer left — tearing down capture");
|
||||
h.shutdown().await;
|
||||
output::emit(output::Event::Capture {
|
||||
state: output::CaptureState::Stopped,
|
||||
});
|
||||
}
|
||||
}
|
||||
SupervisorMsg::KickViewer { id } => {
|
||||
match viewers.get(&id) {
|
||||
// Cancel the viewer's token; its handle_peer select! wakes,
|
||||
// sends RemoveViewer, and the leave is emitted there.
|
||||
Some(cancel) => {
|
||||
tracing::info!(%id, "kicking viewer");
|
||||
cancel.cancel();
|
||||
}
|
||||
None => tracing::debug!(%id, "kick for unknown/already-gone viewer"),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(h) = handle.take() {
|
||||
tracing::info!("host shutdown — tearing down capture");
|
||||
h.shutdown().await;
|
||||
output::emit(output::Event::Capture {
|
||||
state: output::CaptureState::Stopped,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
fn print_host_banner(
|
||||
ticket: &EndpointTicket,
|
||||
display: DisplayServer,
|
||||
opts: &HostOpts,
|
||||
quality: &EffectiveQuality,
|
||||
resolution: &MaxViewersResolution,
|
||||
clipboard_ok: bool,
|
||||
) {
|
||||
eprintln!();
|
||||
eprintln!("┌─ PixelPass · host ─────────────────────────────────────────");
|
||||
eprintln!("│ display server : {display:?}");
|
||||
eprintln!("│ capture : {}", capture_summary(opts));
|
||||
eprintln!("│ bitrate / fps : {} kbps @ {} fps", opts.bitrate, opts.framerate);
|
||||
eprintln!("│ hw encode : {}", if opts.no_hwencode { "off" } else { "auto (VAAPI if available)" });
|
||||
eprintln!(
|
||||
"│ quality : {} — {}",
|
||||
quality.label,
|
||||
quality.dimensions_summary()
|
||||
);
|
||||
eprintln!("│ ({})", quality.note);
|
||||
eprintln!(
|
||||
"│ hw encode : {}",
|
||||
if opts.no_hwencode {
|
||||
"off (software x264)"
|
||||
} else {
|
||||
"on (VAAPI H.264)"
|
||||
}
|
||||
);
|
||||
eprintln!(
|
||||
"│ max viewers : {} ({})",
|
||||
resolution.value,
|
||||
resolution.source.label()
|
||||
);
|
||||
eprintln!("│");
|
||||
if clipboard_ok {
|
||||
eprintln!("│ Your share code has been copied to your clipboard.");
|
||||
eprintln!("│ Send it to your viewer. (If clipboard didn't work, the");
|
||||
eprintln!("│ Send it to your viewer(s). (If clipboard didn't work, the");
|
||||
eprintln!("│ code is also shown below for manual copy.)");
|
||||
} else {
|
||||
eprintln!("│ Share this ticket with your viewer:");
|
||||
eprintln!("│ Share this ticket with your viewer(s):");
|
||||
}
|
||||
eprintln!("│");
|
||||
eprintln!("│ pixelpass {ticket}");
|
||||
eprintln!("│");
|
||||
eprintln!("│ Capture will not start until the viewer connects.");
|
||||
eprintln!("│ Press Ctrl+C to stop.");
|
||||
eprintln!("│ Capture starts when the first viewer connects, runs while");
|
||||
eprintln!("│ any viewer is connected, and tears down when the last one");
|
||||
eprintln!("│ leaves. Press Ctrl+C to stop the host entirely.");
|
||||
eprintln!("└────────────────────────────────────────────────────────────");
|
||||
eprintln!();
|
||||
}
|
||||
|
||||
/// How we arrived at the final viewer cap. Surfaced in the banner so the
|
||||
/// user can tell at a glance whether the number is what they specified,
|
||||
/// what their measured upstream supports, or just the fallback default.
|
||||
struct MaxViewersResolution {
|
||||
value: u32,
|
||||
source: MaxViewersSource,
|
||||
}
|
||||
|
||||
enum MaxViewersSource {
|
||||
/// User passed --max-viewers explicitly.
|
||||
UserFlag,
|
||||
/// Derived from the saved bandwidth measurement.
|
||||
BandwidthMeasurement { safe_mbps: f64 },
|
||||
/// No flag, no measurement — falling back.
|
||||
DefaultFallback,
|
||||
}
|
||||
|
||||
impl MaxViewersSource {
|
||||
fn label(&self) -> String {
|
||||
match self {
|
||||
MaxViewersSource::UserFlag => "user-specified".to_string(),
|
||||
MaxViewersSource::BandwidthMeasurement { safe_mbps } => {
|
||||
format!("auto: {safe_mbps:.1} Mbps measured upstream")
|
||||
}
|
||||
MaxViewersSource::DefaultFallback => {
|
||||
"default — run `pixelpass --reconfigure` for a connection-aware value".to_string()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn resolve_max_viewers(opts: &HostOpts, effective_bitrate: u32) -> MaxViewersResolution {
|
||||
if let Some(n) = opts.max_viewers {
|
||||
return MaxViewersResolution {
|
||||
value: n,
|
||||
source: MaxViewersSource::UserFlag,
|
||||
};
|
||||
}
|
||||
if let Ok(cfg) = config::load()
|
||||
&& cfg.bandwidth.status == BandwidthStatus::Measured
|
||||
&& let Some(upstream) = cfg.bandwidth.upstream_mbps
|
||||
{
|
||||
let n = bandwidth::recommended_max_viewers(upstream, effective_bitrate);
|
||||
return MaxViewersResolution {
|
||||
value: n,
|
||||
source: MaxViewersSource::BandwidthMeasurement {
|
||||
safe_mbps: upstream,
|
||||
},
|
||||
};
|
||||
}
|
||||
MaxViewersResolution {
|
||||
value: 2,
|
||||
source: MaxViewersSource::DefaultFallback,
|
||||
}
|
||||
}
|
||||
|
||||
fn copy_to_clipboard(text: &str) -> bool {
|
||||
match arboard::Clipboard::new().and_then(|mut cb| cb.set_text(text.to_owned())) {
|
||||
Ok(()) => true,
|
||||
@@ -136,12 +488,73 @@ fn copy_to_clipboard(text: &str) -> bool {
|
||||
fn capture_summary(opts: &HostOpts) -> String {
|
||||
let mut bits = vec![if opts.window { "window" } else { "fullscreen" }.to_string()];
|
||||
if let Some(app) = &opts.app {
|
||||
bits.push(format!("app-audio={app}"));
|
||||
if opts.strict_audio {
|
||||
bits.push(format!("app-audio={app} (strict)"));
|
||||
} else {
|
||||
bits.push(format!("app-audio={app}"));
|
||||
}
|
||||
} else {
|
||||
bits.push("system-audio".to_string());
|
||||
}
|
||||
if opts.mic {
|
||||
bits.push("mic".to_string());
|
||||
}
|
||||
bits.join(" + ")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::cli::Quality;
|
||||
|
||||
fn opts(app: Option<&str>, strict_audio: bool) -> HostOpts {
|
||||
HostOpts {
|
||||
window: false,
|
||||
app: app.map(str::to_string),
|
||||
strict_audio,
|
||||
display_server: None,
|
||||
quality: Quality::Auto,
|
||||
bitrate: None,
|
||||
framerate: None,
|
||||
max_height: None,
|
||||
no_hwencode: false,
|
||||
max_viewers: None,
|
||||
interactive: false,
|
||||
relay: None,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn capture_summary_reflects_audio_mode() {
|
||||
assert_eq!(
|
||||
capture_summary(&opts(None, false)),
|
||||
"fullscreen + system-audio"
|
||||
);
|
||||
assert_eq!(
|
||||
capture_summary(&opts(Some("Firefox"), false)),
|
||||
"fullscreen + app-audio=Firefox"
|
||||
);
|
||||
// strict only shows when an app is selected.
|
||||
assert_eq!(
|
||||
capture_summary(&opts(Some("Firefox"), true)),
|
||||
"fullscreen + app-audio=Firefox (strict)"
|
||||
);
|
||||
assert_eq!(
|
||||
capture_summary(&opts(None, true)),
|
||||
"fullscreen + system-audio"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn initial_app_audio_is_lost_only_in_strict_app_mode() {
|
||||
use crate::common::output::AppAudioState;
|
||||
use crate::host::audio::initial_app_audio_state;
|
||||
// Strict + app: announce silence up front (loopback suppressed).
|
||||
assert_eq!(
|
||||
initial_app_audio_state(&opts(Some("Firefox"), true)),
|
||||
Some(AppAudioState::Lost)
|
||||
);
|
||||
// Best-effort app (no strict): loopback covers the gap → no initial event.
|
||||
assert_eq!(initial_app_audio_state(&opts(Some("Firefox"), false)), None);
|
||||
// Whole-desktop (strict is ignored without --app): no per-app events.
|
||||
assert_eq!(initial_app_audio_state(&opts(None, true)), None);
|
||||
assert_eq!(initial_app_audio_state(&opts(None, false)), None);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,328 @@
|
||||
//! Display-server-agnostic capture pipeline. The video *source* element is the
|
||||
//! only part that differs between Wayland (`pipewiresrc`, after a portal
|
||||
//! handshake) and X11 (`ximagesrc`); everything downstream — the videorate cap,
|
||||
//! the encoder, `h264parse`, `mpegtsmux`, the whole audio branch, the gst spawn,
|
||||
//! the [`Serve`] fanout binding, and the [`CaptureHandle`] lifecycle — is shared
|
||||
//! and lives here. Backends call [`spawn`] with just their source-element args.
|
||||
|
||||
use anyhow::{Context, Result, bail};
|
||||
use nix::sys::signal::{Signal, kill};
|
||||
use nix::unistd::Pid;
|
||||
use std::process::Stdio;
|
||||
use std::time::Duration;
|
||||
use tokio::process::{Child, Command};
|
||||
use tokio::time::timeout;
|
||||
|
||||
use super::audio::Routing;
|
||||
use super::quality::EffectiveQuality;
|
||||
use super::serve::Serve;
|
||||
use crate::cli::HostOpts;
|
||||
|
||||
pub struct CaptureHandle {
|
||||
gst: Option<Child>,
|
||||
audio: Option<Routing>,
|
||||
serve: Option<Serve>,
|
||||
}
|
||||
|
||||
impl CaptureHandle {
|
||||
pub fn local_port(&self) -> u16 {
|
||||
self.serve
|
||||
.as_ref()
|
||||
.expect("serve is always Some until shutdown")
|
||||
.local_port()
|
||||
}
|
||||
|
||||
/// Graceful teardown: SIGTERM gst, give it ~1s to exit, then SIGKILL,
|
||||
/// unload audio routing (if any), then tear down the serve layer.
|
||||
/// The serve reader will see EOF on gst stdout and exit on its own;
|
||||
/// serve.shutdown() is the backstop.
|
||||
pub async fn shutdown(mut self) {
|
||||
if let Some(child) = self.gst.as_mut()
|
||||
&& let Some(pid) = child.id()
|
||||
{
|
||||
let _ = kill(Pid::from_raw(pid as i32), Signal::SIGTERM);
|
||||
}
|
||||
if let Some(child) = self.gst.as_mut() {
|
||||
let _ = timeout(Duration::from_millis(1000), child.wait()).await;
|
||||
let _ = child.start_kill();
|
||||
}
|
||||
if let Some(audio) = self.audio.take() {
|
||||
audio.shutdown();
|
||||
}
|
||||
if let Some(serve) = self.serve.take() {
|
||||
serve.shutdown().await;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for CaptureHandle {
|
||||
fn drop(&mut self) {
|
||||
if let Some(child) = self.gst.as_mut() {
|
||||
let _ = child.start_kill();
|
||||
}
|
||||
// Routing's and Serve's own Drop impls handle the rest.
|
||||
}
|
||||
}
|
||||
|
||||
/// Spawn the shared gst pipeline for a backend that supplies `source_args`
|
||||
/// (the video-source element + its properties, e.g. `["pipewiresrc", "fd=7",
|
||||
/// …]` or `["ximagesrc", "use-damage=false", …]`). `source_dims` is the source
|
||||
/// pixel size when the backend knows it (Wayland from the portal, X11 from
|
||||
/// root/window geometry); it lets a downscale preset compute an exact even
|
||||
/// target resolution and skip scaling when the source is already small enough.
|
||||
/// `after_spawn` runs once, immediately after the gst child is launched —
|
||||
/// Wayland uses it to `close` the pipewire fd it leaked into the child; X11
|
||||
/// passes a no-op.
|
||||
pub async fn spawn(
|
||||
opts: &HostOpts,
|
||||
quality: &EffectiveQuality,
|
||||
source_dims: Option<(u32, u32)>,
|
||||
source_args: Vec<String>,
|
||||
after_spawn: impl FnOnce(),
|
||||
) -> Result<CaptureHandle> {
|
||||
let (audio_routing, audio_device) = setup_audio(opts).await?;
|
||||
let args = build_args(&source_args, &audio_device, opts, quality, source_dims);
|
||||
|
||||
let mut gst_cmd = Command::new("gst-launch-1.0");
|
||||
gst_cmd
|
||||
.args(&args)
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::inherit());
|
||||
if std::env::var_os("PIXELPASS_GST_DEBUG").is_some() {
|
||||
gst_cmd.env("GST_DEBUG", "3");
|
||||
}
|
||||
let mut gst = gst_cmd.spawn().context("failed to spawn gst-launch-1.0")?;
|
||||
|
||||
// Backend-specific post-spawn cleanup (Wayland closes its leaked pw fd here,
|
||||
// once gst has inherited its own copy).
|
||||
after_spawn();
|
||||
|
||||
let gst_stdout = gst
|
||||
.stdout
|
||||
.take()
|
||||
.context("gst-launch-1.0 stdout pipe unavailable")?;
|
||||
|
||||
// Hand stdout to the serve layer, which binds the localhost HTTP listener
|
||||
// and runs the broadcast fanout. No demux/remux, no codec assumptions.
|
||||
let serve = Serve::bind(gst_stdout).await?;
|
||||
|
||||
Ok(CaptureHandle {
|
||||
gst: Some(gst),
|
||||
audio: audio_routing,
|
||||
serve: Some(serve),
|
||||
})
|
||||
}
|
||||
|
||||
/// Decide whether per-app audio routing is active and produce the `device=…`
|
||||
/// argument for `pulsesrc`. Routing activates when either `--app` is set
|
||||
/// (per-stream rerouting to a per-PID null-sink) or `PIXELPASS_AUDIO_VIA_NULL_SINK=1`
|
||||
/// is set (no app filter — captures everything via the null-sink, used for
|
||||
/// dogfooding the loopback path). Otherwise we capture the default sink's
|
||||
/// monitor (system audio out), not the default source (the mic).
|
||||
async fn setup_audio(opts: &HostOpts) -> Result<(Option<Routing>, String)> {
|
||||
let routing_requested =
|
||||
opts.app.is_some() || std::env::var_os("PIXELPASS_AUDIO_VIA_NULL_SINK").is_some();
|
||||
let audio_routing = if routing_requested {
|
||||
Some(
|
||||
Routing::start(opts)
|
||||
.await
|
||||
.context("audio routing setup failed")?,
|
||||
)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let audio_device = if let Some(r) = &audio_routing {
|
||||
format!("device={}.monitor", r.sink_name())
|
||||
} else {
|
||||
let default = default_audio_monitor().await?;
|
||||
format!("device={default}")
|
||||
};
|
||||
Ok((audio_routing, audio_device))
|
||||
}
|
||||
|
||||
/// Build the full gst-launch argument vector: MPEG-TS mux + fdsink, then the
|
||||
/// video branch (caller's `source` → videorate cap → optional downscale →
|
||||
/// encoder → h264parse → mux.), then the audio branch (pulsesrc → AAC → mux.).
|
||||
/// Bitrate, framerate, and the downscale height come from the resolved
|
||||
/// [`EffectiveQuality`]; the encoder and the `videoconvert` target format are
|
||||
/// selected by `opts.no_hwencode` (hardware VAAPI wants NV12, software x264
|
||||
/// wants I420).
|
||||
fn build_args(
|
||||
source: &[String],
|
||||
audio_device: &str,
|
||||
opts: &HostOpts,
|
||||
quality: &EffectiveQuality,
|
||||
source_dims: Option<(u32, u32)>,
|
||||
) -> Vec<String> {
|
||||
let key_interval = (quality.framerate * 2).to_string();
|
||||
let bitrate = quality.bitrate.to_string();
|
||||
let framerate_caps = format!("video/x-raw,framerate={}/1", quality.framerate);
|
||||
|
||||
let (raw_format, encoder_args): (&str, Vec<String>) = if opts.no_hwencode {
|
||||
(
|
||||
"video/x-raw,format=I420",
|
||||
vec![
|
||||
"x264enc".into(),
|
||||
"tune=zerolatency".into(),
|
||||
"speed-preset=ultrafast".into(),
|
||||
format!("bitrate={bitrate}"),
|
||||
format!("key-int-max={key_interval}"),
|
||||
],
|
||||
)
|
||||
} else {
|
||||
(
|
||||
"video/x-raw,format=NV12",
|
||||
vec![
|
||||
"vah264enc".into(),
|
||||
"rate-control=cbr".into(),
|
||||
format!("bitrate={bitrate}"),
|
||||
format!("key-int-max={key_interval}"),
|
||||
],
|
||||
)
|
||||
};
|
||||
|
||||
// muxer + sink
|
||||
let mut args: Vec<String> = vec![
|
||||
"mpegtsmux".into(),
|
||||
"name=mux".into(),
|
||||
"!".into(),
|
||||
"queue".into(),
|
||||
"!".into(),
|
||||
"fdsink".into(),
|
||||
"fd=1".into(),
|
||||
];
|
||||
|
||||
// Downscale step for the quality presets. `None` = encode at native size
|
||||
// (the "Source" preset, or a source already at/below the target height — we
|
||||
// never upscale). When the source dimensions are known we pin an exact even
|
||||
// WxH preserving the source aspect; H.264 4:2:0 needs even dims, so width is
|
||||
// rounded to even and height is forced even (preset heights already are; a
|
||||
// raw --max-height override is rounded down). When dims are unknown (a rare
|
||||
// X11 geometry-read failure) we fall back to height-only + square pixels +
|
||||
// an even-stepped width range and let videoscale negotiate.
|
||||
let scale_caps: Option<String> = match quality.max_height {
|
||||
None => {
|
||||
tracing::info!(preset = %quality.label, "encoding at native resolution (no downscale)");
|
||||
None
|
||||
}
|
||||
Some(max_h) => {
|
||||
let h = (max_h & !1).max(2);
|
||||
match source_dims {
|
||||
Some((sw, sh)) if sh > h => {
|
||||
let w = ((sw as u64 * h as u64 + sh as u64 / 2) / sh as u64) as u32;
|
||||
let w = (w & !1).max(2);
|
||||
tracing::info!(
|
||||
preset = %quality.label,
|
||||
from = %format!("{sw}x{sh}"),
|
||||
to = %format!("{w}x{h}"),
|
||||
"downscaling video"
|
||||
);
|
||||
Some(format!("{raw_format},width={w},height={h}"))
|
||||
}
|
||||
Some((sw, sh)) => {
|
||||
tracing::info!(
|
||||
preset = %quality.label,
|
||||
source = %format!("{sw}x{sh}"),
|
||||
max_height = h,
|
||||
"source already at/below preset height — encoding native (no upscale)"
|
||||
);
|
||||
None
|
||||
}
|
||||
None => {
|
||||
tracing::info!(
|
||||
preset = %quality.label,
|
||||
max_height = h,
|
||||
"downscaling to max height (source size unknown — width follows negotiation)"
|
||||
);
|
||||
Some(format!(
|
||||
"{raw_format},height={h},pixel-aspect-ratio=1/1,width=[2,8192,2]"
|
||||
))
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// video branch — videorate caps to the target fps so we don't ship at the
|
||||
// monitor's refresh rate (e.g. 180Hz) and pile up frames in the demuxer
|
||||
// queue faster than realtime. videoscale (when scaling) runs *after*
|
||||
// videoconvert so it operates on system-memory NV12/I420: scaling
|
||||
// pipewiresrc's raw output directly can hit a format/memory (e.g. DMABuf)
|
||||
// that software videoscale won't negotiate.
|
||||
args.extend(source.iter().cloned());
|
||||
args.extend([
|
||||
"!".into(),
|
||||
"videorate".into(),
|
||||
"!".into(),
|
||||
framerate_caps,
|
||||
"!".into(),
|
||||
"queue".into(),
|
||||
"!".into(),
|
||||
"videoconvert".into(),
|
||||
"!".into(),
|
||||
raw_format.into(),
|
||||
"!".into(),
|
||||
]);
|
||||
if let Some(caps) = scale_caps {
|
||||
args.extend(["videoscale".into(), "!".into(), caps, "!".into()]);
|
||||
}
|
||||
args.extend(encoder_args);
|
||||
args.extend([
|
||||
"!".into(),
|
||||
"h264parse".into(),
|
||||
"config-interval=-1".into(),
|
||||
"!".into(),
|
||||
"video/x-h264,stream-format=byte-stream,alignment=au".into(),
|
||||
"!".into(),
|
||||
"mux.".into(),
|
||||
]);
|
||||
|
||||
// audio branch — capture the default sink's MONITOR (system audio out),
|
||||
// not the default source (which is the mic).
|
||||
args.extend([
|
||||
"pulsesrc".into(),
|
||||
audio_device.to_string(),
|
||||
"do-timestamp=true".into(),
|
||||
"!".into(),
|
||||
"queue".into(),
|
||||
"!".into(),
|
||||
"audioconvert".into(),
|
||||
"!".into(),
|
||||
"audioresample".into(),
|
||||
"!".into(),
|
||||
"audio/x-raw,rate=48000,channels=2".into(),
|
||||
"!".into(),
|
||||
"avenc_aac".into(),
|
||||
"bitrate=128000".into(),
|
||||
"!".into(),
|
||||
"aacparse".into(),
|
||||
"!".into(),
|
||||
"mux.".into(),
|
||||
]);
|
||||
|
||||
args
|
||||
}
|
||||
|
||||
async fn default_audio_monitor() -> Result<String> {
|
||||
let output = Command::new("pactl")
|
||||
.arg("get-default-sink")
|
||||
.output()
|
||||
.await
|
||||
.context(
|
||||
"failed to run `pactl get-default-sink` (install pulseaudio-utils or pipewire-pulse)",
|
||||
)?;
|
||||
if !output.status.success() {
|
||||
bail!(
|
||||
"pactl get-default-sink failed: {}",
|
||||
String::from_utf8_lossy(&output.stderr).trim()
|
||||
);
|
||||
}
|
||||
let sink = String::from_utf8(output.stdout)
|
||||
.context("default sink name was not UTF-8")?
|
||||
.trim()
|
||||
.to_string();
|
||||
if sink.is_empty() {
|
||||
bail!("pactl get-default-sink returned no name (is a sound server running?)");
|
||||
}
|
||||
Ok(format!("{sink}.monitor"))
|
||||
}
|
||||
@@ -0,0 +1,283 @@
|
||||
//! Resolution / quality presets. A preset bundles `(max_height, bitrate, fps)`
|
||||
//! because resolution is a *quality-per-bitrate* knob, not a standalone one —
|
||||
//! the three are only useful together. Quality is **host-global**: one encode
|
||||
//! pipeline fans out to every viewer over the broadcast channel, so the sharer
|
||||
//! picks one quality for everyone (per-viewer quality would need per-viewer
|
||||
//! encodes, which kills the fanout).
|
||||
//!
|
||||
//! [`resolve`] turns the raw CLI/picker choice into a concrete
|
||||
//! [`EffectiveQuality`] the pipeline encodes at, applying — in order — the
|
||||
//! chosen preset (or an Auto derivation from the bandwidth pre-flight), then
|
||||
//! any explicit `--bitrate` / `--framerate` / `--max-height` field overrides.
|
||||
|
||||
use crate::cli::{HostOpts, Quality};
|
||||
use crate::common::{config, config::BandwidthStatus};
|
||||
|
||||
/// A fixed preset's concrete settings. `max_height = None` means encode at the
|
||||
/// native source resolution (no `videoscale` element is inserted at all).
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
struct Preset {
|
||||
max_height: Option<u32>,
|
||||
bitrate: u32, // kbps
|
||||
framerate: u32,
|
||||
}
|
||||
|
||||
impl Quality {
|
||||
/// The fixed tuple for a preset. `Auto` returns `None` — it has no fixed
|
||||
/// values and resolves to one of the others at runtime (see [`resolve_auto`]).
|
||||
fn preset(self) -> Option<Preset> {
|
||||
let p = match self {
|
||||
Quality::Source => Preset {
|
||||
max_height: None,
|
||||
bitrate: 6000,
|
||||
framerate: 30,
|
||||
},
|
||||
Quality::High => Preset {
|
||||
max_height: Some(1080),
|
||||
bitrate: 4000,
|
||||
framerate: 30,
|
||||
},
|
||||
Quality::Medium => Preset {
|
||||
max_height: Some(720),
|
||||
bitrate: 2500,
|
||||
framerate: 30,
|
||||
},
|
||||
Quality::Low => Preset {
|
||||
max_height: Some(480),
|
||||
bitrate: 1000,
|
||||
framerate: 30,
|
||||
},
|
||||
Quality::Auto => return None,
|
||||
};
|
||||
Some(p)
|
||||
}
|
||||
|
||||
fn name(self) -> &'static str {
|
||||
match self {
|
||||
Quality::Source => "Source",
|
||||
Quality::High => "High",
|
||||
Quality::Medium => "Medium",
|
||||
Quality::Low => "Low",
|
||||
Quality::Auto => "Auto",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Fixed presets in descending quality order — Auto walks this to find the
|
||||
/// best one whose per-viewer bitrate fits the measured upstream budget.
|
||||
const AUTO_LADDER: [Quality; 4] = [
|
||||
Quality::Source,
|
||||
Quality::High,
|
||||
Quality::Medium,
|
||||
Quality::Low,
|
||||
];
|
||||
|
||||
/// Auto's fallback when there is no usable bandwidth measurement.
|
||||
const AUTO_FALLBACK: Quality = Quality::Medium;
|
||||
|
||||
/// Fully-resolved quality: the concrete values the pipeline will encode at,
|
||||
/// plus human-readable strings for the host banner.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct EffectiveQuality {
|
||||
/// `None` = native resolution (omit `videoscale`); `Some(h)` = scale to height `h`.
|
||||
pub max_height: Option<u32>,
|
||||
pub bitrate: u32, // kbps
|
||||
pub framerate: u32,
|
||||
/// Short label, e.g. `"High"` or `"Auto → Medium"`.
|
||||
pub label: String,
|
||||
/// Provenance note for the banner, e.g. `"user-specified"` or
|
||||
/// `"auto: 8.8 Mbps safe ÷ 1 viewer"`.
|
||||
pub note: String,
|
||||
}
|
||||
|
||||
impl EffectiveQuality {
|
||||
/// `WxH-ish / bitrate / fps` summary for the banner. Width is unknown until
|
||||
/// capture (the source dictates it), so height is shown as `?xN` / `native`.
|
||||
pub fn dimensions_summary(&self) -> String {
|
||||
let res = match self.max_height {
|
||||
Some(h) => format!("≤{h}p"),
|
||||
None => "native".to_string(),
|
||||
};
|
||||
format!("{res} / {} kbps / {} fps", self.bitrate, self.framerate)
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolve the host's quality choice into concrete encode settings.
|
||||
///
|
||||
/// `sizing_viewers` is the viewer count Auto sizes its budget against (the
|
||||
/// resolved `--max-viewers` cap, so quality is chosen for the worst case —
|
||||
/// quality is baked in at capture-spawn and can't drop when viewer #2 joins).
|
||||
pub fn resolve(opts: &HostOpts, sizing_viewers: u32) -> EffectiveQuality {
|
||||
// 1. Base preset: a fixed tuple, or an Auto derivation.
|
||||
let (base, label, base_note) = match opts.quality {
|
||||
Quality::Auto => resolve_auto(measured_safe_mbps(), sizing_viewers),
|
||||
q => {
|
||||
let p = q.preset().expect("non-Auto presets always have a tuple");
|
||||
(p, q.name().to_string(), "user-specified".to_string())
|
||||
}
|
||||
};
|
||||
|
||||
let mut eff = EffectiveQuality {
|
||||
max_height: base.max_height,
|
||||
bitrate: base.bitrate,
|
||||
framerate: base.framerate,
|
||||
label,
|
||||
note: base_note,
|
||||
};
|
||||
|
||||
// 2. Per-field overrides win over the preset (precedence rule).
|
||||
let mut overridden = Vec::new();
|
||||
if let Some(b) = opts.bitrate {
|
||||
eff.bitrate = b;
|
||||
overridden.push("bitrate");
|
||||
}
|
||||
if let Some(f) = opts.framerate {
|
||||
eff.framerate = f;
|
||||
overridden.push("fps");
|
||||
}
|
||||
if let Some(h) = opts.max_height {
|
||||
eff.max_height = Some(h);
|
||||
overridden.push("max-height");
|
||||
}
|
||||
if !overridden.is_empty() {
|
||||
eff.note = format!("{}; override: {}", eff.note, overridden.join(", "));
|
||||
}
|
||||
|
||||
eff
|
||||
}
|
||||
|
||||
/// Auto: pick the highest preset whose per-viewer bitrate fits the measured
|
||||
/// safe upstream divided by the viewer count. Falls back to [`AUTO_FALLBACK`]
|
||||
/// when there's no usable measurement. Pure (no config I/O) so it's testable;
|
||||
/// [`resolve`] supplies the measurement via [`measured_safe_mbps`].
|
||||
fn resolve_auto(safe_mbps: Option<f64>, sizing_viewers: u32) -> (Preset, String, String) {
|
||||
match safe_mbps {
|
||||
Some(safe_mbps) => {
|
||||
let n = sizing_viewers.max(1);
|
||||
let budget_mbps = safe_mbps / n as f64;
|
||||
let chosen = AUTO_LADDER
|
||||
.iter()
|
||||
.copied()
|
||||
.find(|q| {
|
||||
let kbps = q.preset().expect("ladder is fixed presets").bitrate;
|
||||
(kbps as f64) / 1000.0 <= budget_mbps
|
||||
})
|
||||
.unwrap_or(Quality::Low);
|
||||
let preset = chosen.preset().expect("ladder is fixed presets");
|
||||
(
|
||||
preset,
|
||||
format!("Auto → {}", chosen.name()),
|
||||
format!(
|
||||
"auto: {safe_mbps:.1} Mbps safe ÷ {n} viewer(s) = {budget_mbps:.1} Mbps each"
|
||||
),
|
||||
)
|
||||
}
|
||||
None => {
|
||||
let preset = AUTO_FALLBACK.preset().expect("fallback is a fixed preset");
|
||||
(
|
||||
preset,
|
||||
format!("Auto → {}", AUTO_FALLBACK.name()),
|
||||
"auto fallback — no bandwidth measurement (run `pixelpass --reconfigure`)"
|
||||
.to_string(),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The saved safe-upstream figure, only when the pre-flight actually measured
|
||||
/// one. Skipped/failed/unmeasured all return `None` so Auto falls back.
|
||||
fn measured_safe_mbps() -> Option<f64> {
|
||||
let cfg = config::load().ok()?;
|
||||
if cfg.bandwidth.status == BandwidthStatus::Measured {
|
||||
cfg.bandwidth.upstream_mbps
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::cli::{DisplayServerArg, HostOpts};
|
||||
|
||||
/// A HostOpts with no overrides, parameterized by quality + max_viewers.
|
||||
fn opts(quality: Quality, max_viewers: Option<u32>) -> HostOpts {
|
||||
HostOpts {
|
||||
window: false,
|
||||
app: None,
|
||||
strict_audio: false,
|
||||
display_server: None::<DisplayServerArg>,
|
||||
quality,
|
||||
bitrate: None,
|
||||
framerate: None,
|
||||
max_height: None,
|
||||
no_hwencode: false,
|
||||
max_viewers,
|
||||
interactive: false,
|
||||
relay: None,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fixed_presets_pass_through_their_tuple() {
|
||||
let e = resolve(&opts(Quality::Medium, None), 1);
|
||||
assert_eq!(e.max_height, Some(720));
|
||||
assert_eq!(e.bitrate, 2500);
|
||||
assert_eq!(e.framerate, 30);
|
||||
assert_eq!(e.label, "Medium");
|
||||
assert_eq!(e.note, "user-specified");
|
||||
|
||||
// Source is the native (no-scale) preset.
|
||||
assert_eq!(resolve(&opts(Quality::Source, None), 1).max_height, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn auto_picks_highest_preset_that_fits_budget() {
|
||||
// Ample upstream, single viewer → Source fits (6 Mbps <= 8.78).
|
||||
let (p, label, _) = resolve_auto(Some(8.78), 1);
|
||||
assert_eq!(p.bitrate, 6000);
|
||||
assert_eq!(label, "Auto → Source");
|
||||
|
||||
// 10 Mbps split across 2 viewers = 5 each → Source(6) no, High(4) yes.
|
||||
let (p, label, _) = resolve_auto(Some(10.0), 2);
|
||||
assert_eq!(p.bitrate, 4000);
|
||||
assert_eq!(label, "Auto → High");
|
||||
|
||||
// Tight budget falls to the bottom of the ladder, never below Low.
|
||||
let (p, _, _) = resolve_auto(Some(0.3), 1);
|
||||
assert_eq!(p.bitrate, 1000); // Low
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn auto_without_measurement_falls_back_to_medium() {
|
||||
let (p, label, note) = resolve_auto(None, 1);
|
||||
assert_eq!(p.bitrate, 2500); // Medium
|
||||
assert_eq!(p.max_height, Some(720));
|
||||
assert_eq!(label, "Auto → Medium");
|
||||
assert!(note.contains("reconfigure"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_flags_override_preset_fields() {
|
||||
let mut o = opts(Quality::High, None);
|
||||
o.bitrate = Some(9000);
|
||||
o.framerate = Some(60);
|
||||
let e = resolve(&o, 1);
|
||||
assert_eq!(e.bitrate, 9000); // override wins
|
||||
assert_eq!(e.framerate, 60); // override wins
|
||||
assert_eq!(e.max_height, Some(1080)); // untouched preset field
|
||||
assert!(e.note.contains("override: bitrate, fps"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn max_height_override_is_rounded_even_and_applies_to_source() {
|
||||
// Odd override rounds down to even in the pipeline; here we just assert
|
||||
// the override replaces the (native) Source height with the raw value;
|
||||
// the even-rounding happens in pipeline::build_args.
|
||||
let mut o = opts(Quality::Source, None);
|
||||
o.max_height = Some(900);
|
||||
let e = resolve(&o, 1);
|
||||
assert_eq!(e.max_height, Some(900));
|
||||
assert!(e.note.contains("override: max-height"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,194 @@
|
||||
//! Display-server-agnostic serving layer: takes a capture child's stdout
|
||||
//! producing MPEG-TS bytes and fans them out to N concurrent HTTP viewers
|
||||
//! on a localhost port. One reader task pumps stdout chunks into a
|
||||
//! tokio::sync::broadcast channel; the accept loop spawns one drain task
|
||||
//! per accepted TCP connection. Slow consumers see Lagged and skip ahead;
|
||||
//! MPEG-TS resyncs at the next keyframe.
|
||||
//!
|
||||
//! Backends (host/wayland.rs, future host/x11.rs) build their own gst
|
||||
//! pipeline and hand the resulting ChildStdout to [`Serve::bind`].
|
||||
|
||||
use anyhow::{Context, Result, bail};
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
use tokio::net::{TcpListener, TcpStream};
|
||||
use tokio::process::ChildStdout;
|
||||
use tokio::sync::broadcast;
|
||||
use tokio::task::JoinHandle;
|
||||
use tokio::time::{Instant, sleep};
|
||||
|
||||
/// Broadcast-channel capacity in chunks. Each chunk is up to 64 KiB from
|
||||
/// the capture child's stdout, so 16 chunks ≈ 1 MiB ≈ ~2 s of buffered
|
||||
/// jitter at typical bitrates. A viewer that falls behind by more than
|
||||
/// this gets Lagged and skips ahead — MPEG-TS recovers at the next
|
||||
/// keyframe.
|
||||
const FANOUT_CAPACITY: usize = 16;
|
||||
|
||||
/// Size of each chunk read from the capture child's stdout.
|
||||
const READ_CHUNK: usize = 64 * 1024;
|
||||
|
||||
/// Owns the localhost HTTP listener and the two long-running tasks that
|
||||
/// pump bytes from a capture child to all connected viewers.
|
||||
pub struct Serve {
|
||||
port: u16,
|
||||
reader: Option<JoinHandle<()>>,
|
||||
server: Option<JoinHandle<()>>,
|
||||
}
|
||||
|
||||
impl Serve {
|
||||
/// Bind a localhost listener on a random port, set up the broadcast
|
||||
/// fanout, and spawn the reader + accept-loop tasks. The provided
|
||||
/// `stdout` is assumed to produce MPEG-TS bytes.
|
||||
pub async fn bind(stdout: ChildStdout) -> Result<Self> {
|
||||
let listener = TcpListener::bind("127.0.0.1:0")
|
||||
.await
|
||||
.context("could not bind local capture HTTP listener")?;
|
||||
let port = listener.local_addr()?.port();
|
||||
|
||||
let (tx, _) = broadcast::channel::<Arc<Vec<u8>>>(FANOUT_CAPACITY);
|
||||
let reader = tokio::spawn(pump_to_broadcast(stdout, tx.clone()));
|
||||
let server = tokio::spawn(run_accept_loop(listener, tx));
|
||||
|
||||
Ok(Self {
|
||||
port,
|
||||
reader: Some(reader),
|
||||
server: Some(server),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn local_port(&self) -> u16 {
|
||||
self.port
|
||||
}
|
||||
|
||||
/// Abort the reader and accept-loop tasks. Backends typically call this
|
||||
/// after killing their capture child so the reader sees stdout EOF and
|
||||
/// exits on its own; the abort is a backstop.
|
||||
pub async fn shutdown(mut self) {
|
||||
if let Some(task) = self.reader.take() {
|
||||
task.abort();
|
||||
}
|
||||
if let Some(task) = self.server.take() {
|
||||
task.abort();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Serve {
|
||||
fn drop(&mut self) {
|
||||
if let Some(task) = self.reader.as_ref() {
|
||||
task.abort();
|
||||
}
|
||||
if let Some(task) = self.server.as_ref() {
|
||||
task.abort();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Connect to the local capture HTTP listener, retrying until it's up or
|
||||
/// we time out. Returns the connected socket — the bridge layer pipes
|
||||
/// QUIC↔this socket once it's open.
|
||||
pub async fn connect_to_capture(port: u16, max_wait: Duration) -> Result<TcpStream> {
|
||||
let deadline = Instant::now() + max_wait;
|
||||
loop {
|
||||
match TcpStream::connect(("127.0.0.1", port)).await {
|
||||
Ok(stream) => return Ok(stream),
|
||||
Err(_) if Instant::now() < deadline => {
|
||||
sleep(Duration::from_millis(50)).await;
|
||||
}
|
||||
Err(e) => bail!("capture HTTP listener never came up on 127.0.0.1:{port}: {e}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Read the capture child's stdout in chunks and broadcast each to all
|
||||
/// current subscribers. `broadcast::send` returns Err when there are no
|
||||
/// receivers; we ignore it so the capture child isn't backpressured
|
||||
/// waiting for a viewer.
|
||||
async fn pump_to_broadcast(mut stdout: ChildStdout, tx: broadcast::Sender<Arc<Vec<u8>>>) {
|
||||
let mut buf = vec![0u8; READ_CHUNK];
|
||||
loop {
|
||||
match stdout.read(&mut buf).await {
|
||||
Ok(0) => {
|
||||
tracing::info!("capture stdout EOF — fanout reader exiting");
|
||||
return;
|
||||
}
|
||||
Ok(n) => {
|
||||
let chunk = Arc::new(buf[..n].to_vec());
|
||||
let _ = tx.send(chunk);
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!("capture stdout read error: {e}");
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn run_accept_loop(listener: TcpListener, tx: broadcast::Sender<Arc<Vec<u8>>>) {
|
||||
loop {
|
||||
let sock = match listener.accept().await {
|
||||
Ok((s, _)) => s,
|
||||
Err(e) => {
|
||||
// Most accept errors are transient (EMFILE from a brief FD spike,
|
||||
// EINTR, etc.). Bailing on the first one would kill the entire
|
||||
// viewer fanout for the rest of the session.
|
||||
tracing::warn!("capture HTTP accept failed (continuing): {e}");
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let rx = tx.subscribe();
|
||||
tokio::spawn(serve_one_viewer(sock, rx));
|
||||
}
|
||||
}
|
||||
|
||||
async fn serve_one_viewer(mut sock: TcpStream, mut rx: broadcast::Receiver<Arc<Vec<u8>>>) {
|
||||
if !drain_http_request(&mut sock).await {
|
||||
return;
|
||||
}
|
||||
|
||||
const RESPONSE: &[u8] = b"HTTP/1.1 200 OK\r\n\
|
||||
Content-Type: video/mp2t\r\n\
|
||||
Cache-Control: no-cache, no-store\r\n\
|
||||
Connection: close\r\n\
|
||||
\r\n";
|
||||
if sock.write_all(RESPONSE).await.is_err() {
|
||||
return;
|
||||
}
|
||||
|
||||
loop {
|
||||
match rx.recv().await {
|
||||
Ok(chunk) => {
|
||||
if sock.write_all(&chunk).await.is_err() {
|
||||
return;
|
||||
}
|
||||
}
|
||||
Err(broadcast::error::RecvError::Lagged(skipped)) => {
|
||||
tracing::warn!(
|
||||
skipped,
|
||||
"viewer fanout lagged — MPEG-TS will resync at next keyframe"
|
||||
);
|
||||
continue;
|
||||
}
|
||||
Err(broadcast::error::RecvError::Closed) => return,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn drain_http_request(sock: &mut TcpStream) -> bool {
|
||||
let mut buf = [0u8; 1024];
|
||||
let mut total = Vec::with_capacity(512);
|
||||
loop {
|
||||
match sock.read(&mut buf).await {
|
||||
Ok(0) => return false,
|
||||
Ok(n) => total.extend_from_slice(&buf[..n]),
|
||||
Err(_) => return false,
|
||||
}
|
||||
if total.windows(4).any(|w| w == b"\r\n\r\n") {
|
||||
return true;
|
||||
}
|
||||
if total.len() > 16 * 1024 {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
+38
-242
@@ -1,9 +1,9 @@
|
||||
//! Wayland capture: ashpd ScreenCast portal → PipeWire fd → gst-launch
|
||||
//! pipewiresrc → MPEG-TS on gst stdout → in-process HTTP server bound on a
|
||||
//! random localhost port. The host bridge TCP-connects to that server and
|
||||
//! pumps bytes to QUIC.
|
||||
//! Wayland capture: ashpd ScreenCast portal → PipeWire fd → `pipewiresrc`.
|
||||
//! This module owns only the portal handshake and the source-element args;
|
||||
//! the shared encode/mux tail, gst spawn, and serving live in
|
||||
//! [`super::pipeline`].
|
||||
|
||||
use anyhow::{Context, Result, bail};
|
||||
use anyhow::{Context, Result};
|
||||
use ashpd::{
|
||||
WindowIdentifier,
|
||||
desktop::{
|
||||
@@ -12,68 +12,24 @@ use ashpd::{
|
||||
},
|
||||
};
|
||||
use nix::fcntl::{FcntlArg, FdFlag, fcntl};
|
||||
use nix::sys::signal::{Signal, kill};
|
||||
use nix::unistd::{Pid, close};
|
||||
use std::os::fd::{AsFd, IntoRawFd, OwnedFd, RawFd};
|
||||
use std::process::Stdio;
|
||||
use std::time::Duration;
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
use tokio::net::{TcpListener, TcpStream};
|
||||
use tokio::process::{Child, ChildStdout, Command};
|
||||
use tokio::task::JoinHandle;
|
||||
use tokio::time::{Instant, sleep, timeout};
|
||||
use std::os::fd::{AsFd, AsRawFd, OwnedFd, RawFd};
|
||||
|
||||
use super::pipeline::{self, CaptureHandle};
|
||||
use super::quality::EffectiveQuality;
|
||||
use crate::cli::HostOpts;
|
||||
|
||||
pub struct CaptureHandle {
|
||||
port: u16,
|
||||
gst: Option<Child>,
|
||||
server: Option<JoinHandle<()>>,
|
||||
}
|
||||
|
||||
impl CaptureHandle {
|
||||
pub fn local_port(&self) -> u16 {
|
||||
self.port
|
||||
}
|
||||
|
||||
/// Graceful teardown: SIGTERM gst, give it ~1s to exit, then SIGKILL, then
|
||||
/// abort the HTTP server task. Call this before dropping; Drop only fires
|
||||
/// the kill backstop.
|
||||
pub async fn shutdown(mut self) {
|
||||
if let Some(child) = self.gst.as_mut()
|
||||
&& let Some(pid) = child.id()
|
||||
{
|
||||
let _ = kill(Pid::from_raw(pid as i32), Signal::SIGTERM);
|
||||
}
|
||||
if let Some(child) = self.gst.as_mut() {
|
||||
let _ = timeout(Duration::from_millis(1000), child.wait()).await;
|
||||
let _ = child.start_kill();
|
||||
}
|
||||
if let Some(task) = self.server.take() {
|
||||
task.abort();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for CaptureHandle {
|
||||
fn drop(&mut self) {
|
||||
if let Some(child) = self.gst.as_mut() {
|
||||
let _ = child.start_kill();
|
||||
}
|
||||
if let Some(task) = self.server.as_ref() {
|
||||
task.abort();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn start(opts: &HostOpts) -> Result<CaptureHandle> {
|
||||
pub async fn start(opts: &HostOpts, quality: &EffectiveQuality) -> Result<CaptureHandle> {
|
||||
// 1. Negotiate the screencast session with the portal.
|
||||
let proxy = Screencast::new()
|
||||
.await
|
||||
.context("could not reach the xdg-desktop-portal ScreenCast interface")?;
|
||||
let session = proxy.create_session().await?;
|
||||
|
||||
let source = if opts.window { SourceType::Window } else { SourceType::Monitor };
|
||||
let source = if opts.window {
|
||||
SourceType::Window
|
||||
} else {
|
||||
SourceType::Monitor
|
||||
};
|
||||
proxy
|
||||
.select_sources(
|
||||
&session,
|
||||
@@ -104,155 +60,33 @@ pub async fn start(opts: &HostOpts) -> Result<CaptureHandle> {
|
||||
let pw_fd: OwnedFd = proxy.open_pipe_wire_remote(&session).await?;
|
||||
tracing::info!(node_id, width = w, height = h, "portal handshake complete");
|
||||
// The fd is CLOEXEC by default; the gst child needs to inherit it across
|
||||
// exec. We then leak it via into_raw_fd so its lifetime spans the spawn,
|
||||
// and close the parent's copy once gst is running.
|
||||
// exec, so clear CLOEXEC. We keep the OwnedFd alive across the spawn (gst
|
||||
// inherits its own copy at exec) by moving it into the after_spawn hook,
|
||||
// which drops — and so closes — the parent's copy once gst is running. If
|
||||
// pipeline::spawn errors *before* calling the hook (e.g. audio setup or the
|
||||
// gst spawn fails), the unused closure is dropped, dropping the fd just the
|
||||
// same — so the portal fd never leaks on the error path.
|
||||
clear_cloexec(&pw_fd)?;
|
||||
let raw_fd: RawFd = pw_fd.into_raw_fd();
|
||||
let raw_fd: RawFd = pw_fd.as_raw_fd();
|
||||
|
||||
// 2. Bind the in-process HTTP listener on a random localhost port.
|
||||
let listener = TcpListener::bind("127.0.0.1:0")
|
||||
.await
|
||||
.context("could not bind local capture HTTP listener")?;
|
||||
let port = listener.local_addr()?.port();
|
||||
let source_args = vec![
|
||||
"pipewiresrc".to_string(),
|
||||
format!("fd={raw_fd}"),
|
||||
format!("path={node_id}"),
|
||||
"do-timestamp=true".to_string(),
|
||||
];
|
||||
|
||||
// 3. Spawn gst-launch with the full pipeline: video AND audio captured,
|
||||
// encoded, and muxed into MPEG-TS inside gst. Output goes to stdout,
|
||||
// which we pipe straight to our HTTP server task — no demux/remux,
|
||||
// no codec assumptions.
|
||||
let key_interval = (opts.framerate * 2).to_string();
|
||||
let bitrate = opts.bitrate.to_string();
|
||||
let audio_monitor = default_audio_monitor().await?;
|
||||
let audio_device = format!("device={audio_monitor}");
|
||||
let mut gst_cmd = Command::new("gst-launch-1.0");
|
||||
gst_cmd
|
||||
.args([
|
||||
// muxer + sink
|
||||
"mpegtsmux",
|
||||
"name=mux",
|
||||
"!",
|
||||
"queue",
|
||||
"!",
|
||||
"fdsink",
|
||||
"fd=1",
|
||||
// video branch — videorate caps to 30fps so we don't ship at the
|
||||
// monitor's refresh rate (e.g. 180Hz) and pile up frames in mpv's
|
||||
// demuxer queue faster than realtime.
|
||||
"pipewiresrc",
|
||||
&format!("fd={raw_fd}"),
|
||||
&format!("path={node_id}"),
|
||||
"do-timestamp=true",
|
||||
"!",
|
||||
"videorate",
|
||||
"!",
|
||||
&format!("video/x-raw,framerate={}/1", opts.framerate),
|
||||
"!",
|
||||
"queue",
|
||||
"!",
|
||||
"videoconvert",
|
||||
"!",
|
||||
"video/x-raw,format=NV12",
|
||||
"!",
|
||||
"vah264enc",
|
||||
"rate-control=cbr",
|
||||
&format!("bitrate={bitrate}"),
|
||||
&format!("key-int-max={key_interval}"),
|
||||
"!",
|
||||
"h264parse",
|
||||
"config-interval=-1",
|
||||
"!",
|
||||
"video/x-h264,stream-format=byte-stream,alignment=au",
|
||||
"!",
|
||||
"mux.",
|
||||
// audio branch — capture the default sink's MONITOR (system audio
|
||||
// out), not the default source (which is the mic).
|
||||
"pulsesrc",
|
||||
&audio_device,
|
||||
"do-timestamp=true",
|
||||
"!",
|
||||
"queue",
|
||||
"!",
|
||||
"audioconvert",
|
||||
"!",
|
||||
"audioresample",
|
||||
"!",
|
||||
"audio/x-raw,rate=48000,channels=2",
|
||||
"!",
|
||||
"avenc_aac",
|
||||
"bitrate=128000",
|
||||
"!",
|
||||
"aacparse",
|
||||
"!",
|
||||
"mux.",
|
||||
])
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::inherit());
|
||||
if std::env::var_os("PIXELPASS_GST_DEBUG").is_some() {
|
||||
gst_cmd.env("GST_DEBUG", "3");
|
||||
}
|
||||
let mut gst = gst_cmd.spawn().context("failed to spawn gst-launch-1.0")?;
|
||||
// Parent no longer needs the pipewire fd — gst inherited its own copy.
|
||||
let _ = close(raw_fd);
|
||||
|
||||
let gst_stdout = gst
|
||||
.stdout
|
||||
.take()
|
||||
.context("gst-launch-1.0 stdout pipe unavailable")?;
|
||||
|
||||
// 4. Spawn the HTTP server task. It owns the listener + gst stdout: it
|
||||
// accepts one client (the host's bridge socket via connect_to_capture),
|
||||
// drains the HTTP request, writes a fixed MPEG-TS response, then
|
||||
// copies gst stdout to the socket forever.
|
||||
let server = tokio::spawn(serve_capture(listener, gst_stdout));
|
||||
|
||||
Ok(CaptureHandle {
|
||||
port,
|
||||
gst: Some(gst),
|
||||
server: Some(server),
|
||||
})
|
||||
}
|
||||
|
||||
async fn serve_capture(listener: TcpListener, mut gst_stdout: ChildStdout) {
|
||||
let mut sock = match listener.accept().await {
|
||||
Ok((s, _)) => s,
|
||||
Err(e) => {
|
||||
tracing::warn!("capture HTTP accept failed: {e}");
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
if !drain_http_request(&mut sock).await {
|
||||
return;
|
||||
}
|
||||
|
||||
const RESPONSE: &[u8] = b"HTTP/1.1 200 OK\r\n\
|
||||
Content-Type: video/mp2t\r\n\
|
||||
Cache-Control: no-cache, no-store\r\n\
|
||||
Connection: close\r\n\
|
||||
\r\n";
|
||||
if sock.write_all(RESPONSE).await.is_err() {
|
||||
return;
|
||||
}
|
||||
|
||||
let _ = tokio::io::copy(&mut gst_stdout, &mut sock).await;
|
||||
}
|
||||
|
||||
async fn drain_http_request(sock: &mut TcpStream) -> bool {
|
||||
let mut buf = [0u8; 1024];
|
||||
let mut total = Vec::with_capacity(512);
|
||||
loop {
|
||||
match sock.read(&mut buf).await {
|
||||
Ok(0) => return false,
|
||||
Ok(n) => total.extend_from_slice(&buf[..n]),
|
||||
Err(_) => return false,
|
||||
}
|
||||
if total.windows(4).any(|w| w == b"\r\n\r\n") {
|
||||
return true;
|
||||
}
|
||||
if total.len() > 16 * 1024 {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
pipeline::spawn(
|
||||
opts,
|
||||
quality,
|
||||
Some((w as u32, h as u32)),
|
||||
source_args,
|
||||
move || {
|
||||
// Parent no longer needs the pipewire fd — gst inherited its own copy.
|
||||
drop(pw_fd);
|
||||
},
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
fn clear_cloexec(fd: &impl AsFd) -> Result<()> {
|
||||
@@ -262,41 +96,3 @@ fn clear_cloexec(fd: &impl AsFd) -> Result<()> {
|
||||
fcntl(fd.as_fd(), FcntlArg::F_SETFD(flags)).context("F_SETFD on pipewire fd")?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Connect to the in-process capture HTTP listener, retrying until it's up or
|
||||
/// we time out. Returns the connected socket — the listener accepts exactly
|
||||
/// one connection (the bridge socket), so this stream IS the bridge socket.
|
||||
pub async fn connect_to_capture(port: u16, max_wait: Duration) -> Result<TcpStream> {
|
||||
let deadline = Instant::now() + max_wait;
|
||||
loop {
|
||||
match TcpStream::connect(("127.0.0.1", port)).await {
|
||||
Ok(stream) => return Ok(stream),
|
||||
Err(_) if Instant::now() < deadline => {
|
||||
sleep(Duration::from_millis(50)).await;
|
||||
}
|
||||
Err(e) => bail!("capture HTTP listener never came up on 127.0.0.1:{port}: {e}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn default_audio_monitor() -> Result<String> {
|
||||
let output = Command::new("pactl")
|
||||
.arg("get-default-sink")
|
||||
.output()
|
||||
.await
|
||||
.context("failed to run `pactl get-default-sink` (install pulseaudio-utils or pipewire-pulse)")?;
|
||||
if !output.status.success() {
|
||||
bail!(
|
||||
"pactl get-default-sink failed: {}",
|
||||
String::from_utf8_lossy(&output.stderr).trim()
|
||||
);
|
||||
}
|
||||
let sink = String::from_utf8(output.stdout)
|
||||
.context("default sink name was not UTF-8")?
|
||||
.trim()
|
||||
.to_string();
|
||||
if sink.is_empty() {
|
||||
bail!("pactl get-default-sink returned no name (is a sound server running?)");
|
||||
}
|
||||
Ok(format!("{sink}.monitor"))
|
||||
}
|
||||
|
||||
+113
@@ -0,0 +1,113 @@
|
||||
//! X11 capture: `ximagesrc` → the shared encode/mux tail in [`super::pipeline`].
|
||||
//! Unlike Wayland there's no portal and no fd hand-off — `ximagesrc` opens its
|
||||
//! own X connection from `$DISPLAY`. The whole root window is captured by
|
||||
//! default; `--window` resolves a single window's XID via an `xwininfo`
|
||||
//! click-picker. The ticket is the access control, so capture starts silently
|
||||
//! when the first viewer connects (no host-side consent prompt).
|
||||
|
||||
use anyhow::{Context, Result, bail};
|
||||
use tokio::process::Command;
|
||||
use x11rb::connection::Connection;
|
||||
use x11rb::protocol::xproto::ConnectionExt;
|
||||
|
||||
use super::pipeline::{self, CaptureHandle};
|
||||
use super::quality::EffectiveQuality;
|
||||
use crate::cli::HostOpts;
|
||||
|
||||
pub async fn start(opts: &HostOpts, quality: &EffectiveQuality) -> Result<CaptureHandle> {
|
||||
let xid = if opts.window {
|
||||
Some(pick_window().await?)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
// Geometry mirrors Wayland's portal-handshake log line and feeds the
|
||||
// downscale presets (so they can compute an exact target size). A failure
|
||||
// here shouldn't abort capture — ximagesrc will surface a real error if the
|
||||
// X connection is genuinely unusable, and the scaler falls back to a
|
||||
// height-only negotiation when dims are unknown.
|
||||
let source_dims = match read_geometry(xid) {
|
||||
Ok((w, h)) => {
|
||||
tracing::info!(width = w, height = h, xid = ?xid, "X11 capture geometry");
|
||||
Some((w as u32, h as u32))
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!("could not read X11 geometry (capture will still try): {e:#}");
|
||||
None
|
||||
}
|
||||
};
|
||||
|
||||
// XDamage capture (`use-damage=true`) only re-grabs changed screen
|
||||
// regions instead of copying the whole root window every frame. On a busy
|
||||
// desktop that is the difference between a usable framerate and ~1 fps —
|
||||
// `use-damage=false` does a full XGetImage per frame, which collapses on
|
||||
// servers without working MIT-SHM (and pins the CPU everywhere else).
|
||||
// Kept as the default; `PIXELPASS_X11_NO_DAMAGE=1` restores full-frame
|
||||
// capture if a driver produces partial-update artifacts with damage on.
|
||||
let use_damage = if std::env::var_os("PIXELPASS_X11_NO_DAMAGE").is_some() {
|
||||
"use-damage=false"
|
||||
} else {
|
||||
"use-damage=true"
|
||||
};
|
||||
let mut source_args = vec![
|
||||
"ximagesrc".to_string(),
|
||||
// show-pointer matches Wayland's CursorMode::Embedded.
|
||||
use_damage.to_string(),
|
||||
"show-pointer=true".to_string(),
|
||||
];
|
||||
if let Some(xid) = xid {
|
||||
source_args.push(format!("xid={xid}"));
|
||||
}
|
||||
|
||||
// X11 has no leaked fd to clean up, so the post-spawn hook is a no-op.
|
||||
pipeline::spawn(opts, quality, source_dims, source_args, || {}).await
|
||||
}
|
||||
|
||||
/// Run `xwininfo` and let the user click the window they want to share, then
|
||||
/// parse the `Window id: 0x…` line out of its output. Returns the numeric XID.
|
||||
async fn pick_window() -> Result<u32> {
|
||||
eprintln!("[pixelpass] click the window you want to share…");
|
||||
let output = Command::new("xwininfo")
|
||||
.output()
|
||||
.await
|
||||
.context("failed to run `xwininfo` (install xorg-xwininfo)")?;
|
||||
if !output.status.success() {
|
||||
bail!(
|
||||
"xwininfo failed: {}",
|
||||
String::from_utf8_lossy(&output.stderr).trim()
|
||||
);
|
||||
}
|
||||
let text = String::from_utf8_lossy(&output.stdout);
|
||||
for line in text.lines() {
|
||||
// e.g. "xwininfo: Window id: 0x3a00007 \"xterm\""
|
||||
if let Some((_, rest)) = line.split_once("Window id: ") {
|
||||
let token = rest.split_whitespace().next().unwrap_or("");
|
||||
let hex = token.strip_prefix("0x").unwrap_or(token);
|
||||
if let Ok(xid) = u32::from_str_radix(hex, 16) {
|
||||
return Ok(xid);
|
||||
}
|
||||
}
|
||||
}
|
||||
bail!("could not parse a window id from xwininfo output");
|
||||
}
|
||||
|
||||
/// Read pixel dimensions: the selected window's geometry when `--window` was
|
||||
/// used, otherwise the root window of the screen named by `$DISPLAY`.
|
||||
fn read_geometry(xid: Option<u32>) -> Result<(u16, u16)> {
|
||||
let (conn, screen_num) =
|
||||
x11rb::connect(None).context("could not connect to the X server (is DISPLAY set?)")?;
|
||||
match xid {
|
||||
Some(id) => {
|
||||
let geo = conn
|
||||
.get_geometry(id)
|
||||
.context("GetGeometry request failed")?
|
||||
.reply()
|
||||
.context("GetGeometry reply failed")?;
|
||||
Ok((geo.width, geo.height))
|
||||
}
|
||||
None => {
|
||||
let screen = &conn.setup().roots[screen_num];
|
||||
Ok((screen.width_in_pixels, screen.height_in_pixels))
|
||||
}
|
||||
}
|
||||
}
|
||||
+276
-11
@@ -3,7 +3,8 @@ use dialoguer::{Input, Select, theme::ColorfulTheme};
|
||||
use iroh_tickets::endpoint::EndpointTicket;
|
||||
use std::str::FromStr;
|
||||
|
||||
use crate::cli::Cli;
|
||||
use crate::cli::{Cli, Quality};
|
||||
use crate::common::{bandwidth, config};
|
||||
use crate::{host, viewer};
|
||||
|
||||
pub async fn run(cli: Cli) -> Result<()> {
|
||||
@@ -12,7 +13,7 @@ pub async fn run(cli: Cli) -> Result<()> {
|
||||
let theme = ColorfulTheme::default();
|
||||
let choice = Select::with_theme(&theme)
|
||||
.with_prompt("What do you want to do?")
|
||||
.items(&[
|
||||
.items([
|
||||
"Host (share my screen)",
|
||||
"View (watch someone else's screen)",
|
||||
])
|
||||
@@ -20,7 +21,17 @@ pub async fn run(cli: Cli) -> Result<()> {
|
||||
.interact()?;
|
||||
|
||||
match choice {
|
||||
0 => host::run(cli.into_host_opts(true)).await,
|
||||
0 => {
|
||||
preflight_if_needed(&theme).await;
|
||||
let mut cli = cli;
|
||||
if cli.app.is_none() {
|
||||
cli.app = pick_app(&theme)?;
|
||||
}
|
||||
if cli.quality.is_none() {
|
||||
cli.quality = Some(pick_quality(&theme)?);
|
||||
}
|
||||
host::run(cli.into_host_opts(true)).await
|
||||
}
|
||||
_ => {
|
||||
let ticket = prompt_ticket(&theme)?;
|
||||
viewer::run(ticket, cli.into_viewer_opts(true)).await
|
||||
@@ -28,6 +39,215 @@ pub async fn run(cli: Cli) -> Result<()> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Picker for the per-app audio capture choice. Lists apps currently
|
||||
/// producing audio (deduped by `application.name`); user picks one or
|
||||
/// the "all system audio" default. Bypassed when `--app NAME` was given
|
||||
/// on the CLI.
|
||||
fn pick_app(theme: &ColorfulTheme) -> Result<Option<String>> {
|
||||
let apps = match host::audio::list_playing_apps() {
|
||||
Ok(a) => a,
|
||||
Err(e) => {
|
||||
tracing::warn!("could not enumerate playing apps: {e:#}");
|
||||
return Ok(None);
|
||||
}
|
||||
};
|
||||
|
||||
eprintln!();
|
||||
eprintln!("Audio capture");
|
||||
eprintln!("─────────────");
|
||||
if apps.is_empty() {
|
||||
eprintln!("No other apps are currently producing audio.");
|
||||
eprintln!("Start your game / music / call first if you want to pick it specifically.");
|
||||
}
|
||||
eprintln!();
|
||||
|
||||
let mut items = vec!["Capture all system audio (default)".to_string()];
|
||||
for app in &apps {
|
||||
items.push(if app.stream_count == 1 {
|
||||
app.name.clone()
|
||||
} else {
|
||||
format!("{} ({} streams)", app.name, app.stream_count)
|
||||
});
|
||||
}
|
||||
|
||||
let choice = Select::with_theme(theme)
|
||||
.with_prompt("What audio should the viewer hear?")
|
||||
.items(&items)
|
||||
.default(0)
|
||||
.interact()?;
|
||||
|
||||
if choice == 0 {
|
||||
Ok(None)
|
||||
} else {
|
||||
Ok(Some(apps[choice - 1].name.clone()))
|
||||
}
|
||||
}
|
||||
|
||||
/// Picker for the encode quality preset. Mirrors [`pick_app`]; bypassed when
|
||||
/// `--quality` was given on the CLI. Quality is host-global (the same stream
|
||||
/// fans out to every viewer), so this is the one choice that sets it for all.
|
||||
fn pick_quality(theme: &ColorfulTheme) -> Result<Quality> {
|
||||
eprintln!();
|
||||
eprintln!("Quality");
|
||||
eprintln!("───────");
|
||||
eprintln!("Lower presets trade resolution + bitrate for less upload usage.");
|
||||
eprintln!("The same quality is sent to every viewer.");
|
||||
eprintln!();
|
||||
|
||||
// Order mirrors the labels below; index maps back to a Quality.
|
||||
let choices = [
|
||||
Quality::Auto,
|
||||
Quality::Source,
|
||||
Quality::High,
|
||||
Quality::Medium,
|
||||
Quality::Low,
|
||||
];
|
||||
let items = [
|
||||
"Auto — pick from my measured upstream (recommended)",
|
||||
"Source — native resolution, 6000 kbps",
|
||||
"High — up to 1080p, 4000 kbps",
|
||||
"Medium — up to 720p, 2500 kbps",
|
||||
"Low — up to 480p, 1000 kbps",
|
||||
];
|
||||
|
||||
let choice = Select::with_theme(theme)
|
||||
.with_prompt("What quality should the viewer(s) get?")
|
||||
.items(items)
|
||||
.default(0)
|
||||
.interact()?;
|
||||
|
||||
Ok(choices[choice])
|
||||
}
|
||||
|
||||
/// `pixelpass --reconfigure` entry point: unconditionally re-run the
|
||||
/// bandwidth pre-flight test, save the result, and return. Used to
|
||||
/// refresh a stale measurement (e.g. user moved house, changed ISP).
|
||||
pub async fn run_reconfigure() -> Result<()> {
|
||||
eprintln!();
|
||||
eprintln!("Re-running bandwidth pre-flight test…");
|
||||
let mut cfg = config::load().unwrap_or_default();
|
||||
run_bandwidth_test(&mut cfg).await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// First-run pre-flight gate. Called once, when the user picks "Host" in
|
||||
/// the interactive menu. Behavior by saved status:
|
||||
/// - Unmeasured (first ever launch): explain + offer Run / Skip
|
||||
/// - Failed (previous attempt errored): offer Retry / give-up-and-skip
|
||||
/// - Measured or Skipped: silent — never re-prompts
|
||||
async fn preflight_if_needed(theme: &ColorfulTheme) {
|
||||
let mut cfg = config::load().unwrap_or_default();
|
||||
match cfg.bandwidth.status {
|
||||
config::BandwidthStatus::Measured | config::BandwidthStatus::Skipped => (),
|
||||
config::BandwidthStatus::Unmeasured => {
|
||||
eprintln!();
|
||||
eprintln!("First-time setup");
|
||||
eprintln!("────────────────");
|
||||
eprintln!("PixelPass can measure your upload speed to recommend a safe");
|
||||
eprintln!("default for how many viewers your connection can handle.");
|
||||
eprintln!("The test takes about 5 seconds and uploads ~5 MB to");
|
||||
eprintln!("Cloudflare's open speed-test endpoint.");
|
||||
eprintln!();
|
||||
eprintln!("If you skip, a conservative default (2 viewers) is used.");
|
||||
eprintln!("You can run the test later with `pixelpass --reconfigure`.");
|
||||
eprintln!();
|
||||
|
||||
let Ok(choice) = Select::with_theme(theme)
|
||||
.with_prompt("What would you like to do?")
|
||||
.items([
|
||||
"Run the bandwidth test (recommended)",
|
||||
"Skip — use the conservative default",
|
||||
])
|
||||
.default(0)
|
||||
.interact()
|
||||
else {
|
||||
return;
|
||||
};
|
||||
|
||||
if choice == 1 {
|
||||
cfg.bandwidth = config::BandwidthEntry {
|
||||
status: config::BandwidthStatus::Skipped,
|
||||
upstream_mbps: None,
|
||||
measured_at: None,
|
||||
};
|
||||
let _ = config::save(&cfg);
|
||||
eprintln!("Pre-flight skipped.");
|
||||
return;
|
||||
}
|
||||
run_bandwidth_test(&mut cfg).await;
|
||||
}
|
||||
config::BandwidthStatus::Failed => {
|
||||
eprintln!();
|
||||
let Ok(choice) = Select::with_theme(theme)
|
||||
.with_prompt("Last bandwidth test failed. Try again?")
|
||||
.items(["Yes — retry now", "No — use the conservative default"])
|
||||
.default(0)
|
||||
.interact()
|
||||
else {
|
||||
return;
|
||||
};
|
||||
|
||||
if choice == 1 {
|
||||
cfg.bandwidth = config::BandwidthEntry {
|
||||
status: config::BandwidthStatus::Skipped,
|
||||
upstream_mbps: None,
|
||||
measured_at: None,
|
||||
};
|
||||
let _ = config::save(&cfg);
|
||||
eprintln!("OK — using the conservative default.");
|
||||
return;
|
||||
}
|
||||
run_bandwidth_test(&mut cfg).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn run_bandwidth_test(cfg: &mut config::Config) {
|
||||
eprintln!();
|
||||
eprintln!("Measuring upstream…");
|
||||
|
||||
let result = tokio::task::spawn_blocking(bandwidth::measure_upstream_blocking).await;
|
||||
let measurement = match result {
|
||||
Ok(Ok(m)) => m,
|
||||
Ok(Err(e)) => {
|
||||
eprintln!("Test failed: {e:#}");
|
||||
eprintln!("Marking as failed — you'll be asked again on next launch.");
|
||||
cfg.bandwidth = config::BandwidthEntry {
|
||||
status: config::BandwidthStatus::Failed,
|
||||
upstream_mbps: None,
|
||||
measured_at: None,
|
||||
};
|
||||
let _ = config::save(cfg);
|
||||
return;
|
||||
}
|
||||
Err(join_err) => {
|
||||
eprintln!("Test task panicked: {join_err}");
|
||||
cfg.bandwidth = config::BandwidthEntry {
|
||||
status: config::BandwidthStatus::Failed,
|
||||
upstream_mbps: None,
|
||||
measured_at: None,
|
||||
};
|
||||
let _ = config::save(cfg);
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
eprintln!(
|
||||
"Measured {:.2} Mbps up (safe estimate {:.2} Mbps, took {:.1}s).",
|
||||
measurement.raw_mbps,
|
||||
measurement.safe_mbps,
|
||||
measurement.elapsed.as_secs_f64()
|
||||
);
|
||||
cfg.bandwidth = config::BandwidthEntry {
|
||||
status: config::BandwidthStatus::Measured,
|
||||
upstream_mbps: Some(measurement.safe_mbps),
|
||||
measured_at: Some(chrono::Utc::now()),
|
||||
};
|
||||
if let Err(e) = config::save(cfg) {
|
||||
eprintln!("Warning: failed to save result: {e:#}");
|
||||
}
|
||||
}
|
||||
|
||||
fn print_welcome() {
|
||||
eprintln!();
|
||||
eprintln!("Welcome to PixelPass.");
|
||||
@@ -59,29 +279,74 @@ impl Player {
|
||||
Player::Mpv => crate::common::process::spawn_detached(
|
||||
"mpv",
|
||||
&[
|
||||
// No `--untimed`: it ignores audio timestamps and drifts a
|
||||
// shared video out of sync. Pacing to audio keeps A/V synced.
|
||||
// Also leave hwdec at the `low-latency` default (software
|
||||
// decode): forcing `--hwdec=auto` froze some viewers on
|
||||
// frame 1 while audio kept playing.
|
||||
"--profile=low-latency",
|
||||
"--untimed",
|
||||
"--hwdec=auto",
|
||||
"--audio-buffer=0.2",
|
||||
"--demuxer-max-bytes=2M",
|
||||
"--demuxer-readahead-secs=0.5",
|
||||
url,
|
||||
],
|
||||
),
|
||||
Player::Vlc => crate::common::process::spawn_detached(
|
||||
"vlc",
|
||||
&["--network-caching=200", "--live-caching=200", url],
|
||||
),
|
||||
Player::Vlc => {
|
||||
warn_if_vlc_plugins_missing();
|
||||
crate::common::process::spawn_detached(
|
||||
"vlc",
|
||||
&["--network-caching=200", "--live-caching=200", url],
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// On Arch-family distros, the base `vlc` package omits two plugins
|
||||
// pixelpass needs: the MPEG-TS demuxer (`vlc-plugin-dvb`) and the
|
||||
// libavcodec-based H.264 decoder (`vlc-plugin-ffmpeg`). Missing either
|
||||
// produces a confusing error chain — warn at launch.
|
||||
fn warn_if_vlc_plugins_missing() {
|
||||
const REQUIRED: &[(&str, &str)] = &[
|
||||
(
|
||||
"/usr/lib/vlc/plugins/demux/libts_plugin.so",
|
||||
"vlc-plugin-dvb",
|
||||
),
|
||||
(
|
||||
"/usr/lib/vlc/plugins/codec/libavcodec_plugin.so",
|
||||
"vlc-plugin-ffmpeg",
|
||||
),
|
||||
];
|
||||
let missing: Vec<&(&str, &str)> = REQUIRED
|
||||
.iter()
|
||||
.filter(|(p, _)| !std::path::Path::new(p).exists())
|
||||
.collect();
|
||||
if missing.is_empty() {
|
||||
return;
|
||||
}
|
||||
eprintln!();
|
||||
eprintln!("Warning: VLC is missing plugins pixelpass needs:");
|
||||
for (path, pkg) in &missing {
|
||||
eprintln!(" - {path} (install `{pkg}`)");
|
||||
}
|
||||
eprintln!("On Arch / CachyOS / EndeavourOS: `sudo pacman -S {}`.", {
|
||||
let names: Vec<&str> = missing.iter().map(|(_, p)| *p).collect();
|
||||
names.join(" ")
|
||||
});
|
||||
eprintln!("mpv is unaffected.");
|
||||
eprintln!();
|
||||
}
|
||||
|
||||
pub fn prompt_player() -> Result<Player> {
|
||||
let theme = ColorfulTheme::default();
|
||||
let choice = Select::with_theme(&theme)
|
||||
.with_prompt("Connected. Pick a player to launch")
|
||||
.items(&["mpv", "VLC"])
|
||||
.items(["mpv", "VLC"])
|
||||
.default(0)
|
||||
.interact()?;
|
||||
Ok(if choice == 0 { Player::Mpv } else { Player::Vlc })
|
||||
Ok(if choice == 0 {
|
||||
Player::Mpv
|
||||
} else {
|
||||
Player::Vlc
|
||||
})
|
||||
}
|
||||
|
||||
+61
-2
@@ -1,5 +1,8 @@
|
||||
mod cli;
|
||||
mod common;
|
||||
mod doctor;
|
||||
#[cfg(feature = "gui")]
|
||||
mod gui;
|
||||
mod host;
|
||||
mod interactive;
|
||||
mod repair;
|
||||
@@ -16,10 +19,53 @@ async fn main() -> Result<()> {
|
||||
let cli = Cli::parse();
|
||||
init_tracing(cli.verbose);
|
||||
|
||||
if matches!(cli.output, Some(cli::OutputFormat::Json)) {
|
||||
common::output::set_json(true);
|
||||
}
|
||||
|
||||
if cli.gui {
|
||||
#[cfg(feature = "gui")]
|
||||
{
|
||||
return gui::run(cli.relay);
|
||||
}
|
||||
#[cfg(not(feature = "gui"))]
|
||||
{
|
||||
anyhow::bail!(
|
||||
"this binary was built without GUI support. Rebuild with \
|
||||
`cargo build --release --features gui` to use --gui."
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Diagnostics run before pipewire::init() (they don't need it) and work
|
||||
// regardless of the `gui` feature, so a headless tester can probe their box.
|
||||
if cli.doctor {
|
||||
let relay = common::endpoint::relay_override(cli.relay.as_deref());
|
||||
return doctor::run(relay).await;
|
||||
}
|
||||
|
||||
// libpipewire requires global init before any pw_* call. Idempotent;
|
||||
// safe to call even when the per-app audio thread never spawns.
|
||||
pipewire::init();
|
||||
|
||||
if cli.repair {
|
||||
return repair::run().await;
|
||||
}
|
||||
|
||||
if cli.reconfigure {
|
||||
return interactive::run_reconfigure().await;
|
||||
}
|
||||
|
||||
if cli.host {
|
||||
if cli.ticket.is_some() {
|
||||
anyhow::bail!(
|
||||
"--host and a ticket argument are mutually exclusive: --host shares your \
|
||||
screen, a ticket views someone else's."
|
||||
);
|
||||
}
|
||||
return host::run(cli.into_host_opts(false)).await;
|
||||
}
|
||||
|
||||
match cli.ticket.as_deref() {
|
||||
Some(s) => {
|
||||
let ticket: EndpointTicket = s.parse().map_err(|e| {
|
||||
@@ -35,7 +81,20 @@ async fn main() -> Result<()> {
|
||||
}
|
||||
|
||||
fn init_tracing(verbose: bool) {
|
||||
let default = if verbose { "pixelpass=trace,iroh=info" } else { "pixelpass=info,iroh=warn" };
|
||||
let default = if verbose {
|
||||
"pixelpass=trace,iroh=info"
|
||||
} else {
|
||||
"pixelpass=info,iroh=warn"
|
||||
};
|
||||
let filter = EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new(default));
|
||||
tracing_subscriber::fmt().with_env_filter(filter).with_target(false).init();
|
||||
// Tracing MUST write to stderr. `tracing_subscriber::fmt()` defaults its
|
||||
// writer to stdout, but with `--output json` stdout carries the JSON event
|
||||
// stream the `--gui` front-end parses (see `common::output`) — logging there
|
||||
// interleaves log lines into that stream (corrupting events and starving the
|
||||
// GUI's stderr-tail diagnostics). Pin it to stderr to honor that contract.
|
||||
tracing_subscriber::fmt()
|
||||
.with_writer(std::io::stderr)
|
||||
.with_env_filter(filter)
|
||||
.with_target(false)
|
||||
.init();
|
||||
}
|
||||
|
||||
+231
-7
@@ -1,12 +1,236 @@
|
||||
//! `--repair`: clean up any null sinks / loopbacks that a crashed pixelpass
|
||||
//! host left behind. Phase 2 will scan PipeWire for nodes tagged with the
|
||||
//! `pixelpass.session = <uuid>` property and destroy them.
|
||||
//! `--repair`: clean up null-sinks and loopbacks left behind by a crashed
|
||||
//! pixelpass host. Identifies orphans by the `pixelpass_capture_<pid>`
|
||||
//! name pattern + dead-PID check, then unloads paired loopbacks first
|
||||
//! (mirrors `Routing::shutdown`'s order so PipeWire doesn't leave zombie
|
||||
//! links). Live PIDs — including this process and any other running
|
||||
//! pixelpass — are left alone.
|
||||
|
||||
use anyhow::Result;
|
||||
use anyhow::{Context, Result, bail};
|
||||
use std::collections::HashSet;
|
||||
use std::path::Path;
|
||||
use std::process::Command;
|
||||
|
||||
const SINK_NAME_PREFIX: &str = "pixelpass_capture_";
|
||||
|
||||
pub async fn run() -> Result<()> {
|
||||
eprintln!("[pixelpass] --repair: PipeWire scan not yet implemented (Phase 2).");
|
||||
eprintln!(" Run `pactl list short sinks | grep pixelpass` to spot orphans,");
|
||||
eprintln!(" and `pactl unload-module <id>` to remove them manually.");
|
||||
let modules = list_modules().context("failed to list pactl modules")?;
|
||||
|
||||
let mut dead_sinks: Vec<OrphanSink> = Vec::new();
|
||||
let mut dead_pids: HashSet<u32> = HashSet::new();
|
||||
let mut live_skipped: u32 = 0;
|
||||
|
||||
for m in &modules {
|
||||
if m.name != "module-null-sink" {
|
||||
continue;
|
||||
}
|
||||
let Some(sink_name) = extract_kv(&m.args, "sink_name") else {
|
||||
continue;
|
||||
};
|
||||
let Some(pid_str) = sink_name.strip_prefix(SINK_NAME_PREFIX) else {
|
||||
continue;
|
||||
};
|
||||
let Ok(pid) = pid_str.parse::<u32>() else {
|
||||
continue;
|
||||
};
|
||||
|
||||
if is_pid_alive(pid) {
|
||||
live_skipped += 1;
|
||||
continue;
|
||||
}
|
||||
dead_pids.insert(pid);
|
||||
dead_sinks.push(OrphanSink {
|
||||
id: m.id,
|
||||
sink_name: sink_name.to_string(),
|
||||
pid,
|
||||
});
|
||||
}
|
||||
|
||||
let mut dead_loopbacks: Vec<u32> = Vec::new();
|
||||
for m in &modules {
|
||||
if m.name != "module-loopback" {
|
||||
continue;
|
||||
}
|
||||
// A pixelpass loopback references a capture sink either as its
|
||||
// destination (`sink=pixelpass_capture_<pid>` — the default→null
|
||||
// mirror) or as its source (`source=pixelpass_capture_<pid>.monitor`
|
||||
// — the local monitor that lets the sharer hear the app). Match both.
|
||||
let Some(pid) = loopback_capture_pid(&m.args) else {
|
||||
continue;
|
||||
};
|
||||
if dead_pids.contains(&pid) {
|
||||
dead_loopbacks.push(m.id);
|
||||
}
|
||||
}
|
||||
|
||||
if dead_sinks.is_empty() && dead_loopbacks.is_empty() {
|
||||
if live_skipped > 0 {
|
||||
println!(
|
||||
"[pixelpass] --repair: nothing to clean up ({live_skipped} live pixelpass host(s) left alone)."
|
||||
);
|
||||
} else {
|
||||
println!("[pixelpass] --repair: nothing to clean up.");
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let mut unloaded = 0u32;
|
||||
let mut failed = 0u32;
|
||||
|
||||
for id in &dead_loopbacks {
|
||||
match unload_module(*id) {
|
||||
Ok(()) => {
|
||||
println!("[pixelpass] --repair: unloaded loopback module #{id}");
|
||||
unloaded += 1;
|
||||
}
|
||||
Err(e) => {
|
||||
eprintln!("[pixelpass] --repair: failed to unload loopback #{id}: {e:#}");
|
||||
failed += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
for orphan in &dead_sinks {
|
||||
match unload_module(orphan.id) {
|
||||
Ok(()) => {
|
||||
println!(
|
||||
"[pixelpass] --repair: unloaded {} (orphaned from pid {})",
|
||||
orphan.sink_name, orphan.pid
|
||||
);
|
||||
unloaded += 1;
|
||||
}
|
||||
Err(e) => {
|
||||
eprintln!(
|
||||
"[pixelpass] --repair: failed to unload {} (#{}): {e:#}",
|
||||
orphan.sink_name, orphan.id
|
||||
);
|
||||
failed += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if live_skipped > 0 {
|
||||
println!("[pixelpass] --repair: left {live_skipped} live pixelpass host(s) alone.");
|
||||
}
|
||||
|
||||
if failed > 0 {
|
||||
bail!("--repair: {failed} module(s) failed to unload (see errors above)");
|
||||
}
|
||||
println!("[pixelpass] --repair: cleaned up {unloaded} module(s).");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
struct Module {
|
||||
id: u32,
|
||||
name: String,
|
||||
args: String,
|
||||
}
|
||||
|
||||
struct OrphanSink {
|
||||
id: u32,
|
||||
sink_name: String,
|
||||
pid: u32,
|
||||
}
|
||||
|
||||
fn list_modules() -> Result<Vec<Module>> {
|
||||
let output = Command::new("pactl")
|
||||
.args(["list", "short", "modules"])
|
||||
.output()
|
||||
.context("failed to run `pactl list short modules`")?;
|
||||
if !output.status.success() {
|
||||
bail!(
|
||||
"pactl list short modules failed: {}",
|
||||
String::from_utf8_lossy(&output.stderr).trim()
|
||||
);
|
||||
}
|
||||
let text = String::from_utf8(output.stdout).context("pactl returned non-UTF-8")?;
|
||||
let mut modules = Vec::new();
|
||||
// `pactl list short modules` is tab-separated, but some modules have
|
||||
// multi-line `{ ... }` argument blocks that wrap onto continuation
|
||||
// lines starting with whitespace. The wrap lines never parse as a
|
||||
// u32 ID, so the simple per-line + parse-id filter is robust.
|
||||
for line in text.lines() {
|
||||
let mut parts = line.splitn(4, '\t');
|
||||
let Some(id_str) = parts.next() else { continue };
|
||||
let Ok(id) = id_str.parse::<u32>() else {
|
||||
continue;
|
||||
};
|
||||
let Some(name) = parts.next() else { continue };
|
||||
let args = parts.next().unwrap_or("").to_string();
|
||||
modules.push(Module {
|
||||
id,
|
||||
name: name.to_string(),
|
||||
args,
|
||||
});
|
||||
}
|
||||
Ok(modules)
|
||||
}
|
||||
|
||||
/// The `pixelpass_capture_<pid>` PID a loopback references, whether the capture
|
||||
/// sink is its destination (`sink=pixelpass_capture_<pid>`) or its source
|
||||
/// (`source=pixelpass_capture_<pid>.monitor`). `None` for unrelated loopbacks.
|
||||
fn loopback_capture_pid(args: &str) -> Option<u32> {
|
||||
let from_sink = extract_kv(args, "sink").and_then(|v| v.strip_prefix(SINK_NAME_PREFIX));
|
||||
let from_source = extract_kv(args, "source")
|
||||
.and_then(|v| v.strip_prefix(SINK_NAME_PREFIX))
|
||||
.and_then(|rest| rest.strip_suffix(".monitor"));
|
||||
from_sink
|
||||
.or(from_source)
|
||||
.and_then(|pid| pid.parse::<u32>().ok())
|
||||
}
|
||||
|
||||
fn extract_kv<'a>(args: &'a str, key: &str) -> Option<&'a str> {
|
||||
for token in args.split_whitespace() {
|
||||
if let Some(rest) = token.strip_prefix(key)
|
||||
&& let Some(value) = rest.strip_prefix('=')
|
||||
{
|
||||
return Some(value);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn is_pid_alive(pid: u32) -> bool {
|
||||
Path::new(&format!("/proc/{pid}")).exists()
|
||||
}
|
||||
|
||||
fn unload_module(id: u32) -> Result<()> {
|
||||
let output = Command::new("pactl")
|
||||
.arg("unload-module")
|
||||
.arg(id.to_string())
|
||||
.output()
|
||||
.context("failed to run pactl unload-module")?;
|
||||
if !output.status.success() {
|
||||
bail!(
|
||||
"pactl unload-module #{id}: {}",
|
||||
String::from_utf8_lossy(&output.stderr).trim()
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn loopback_pid_matches_default_null_mirror_by_sink() {
|
||||
// The default→null loopback: capture sink is the destination.
|
||||
let args = "source=@DEFAULT_SINK@.monitor sink=pixelpass_capture_4242 latency_msec=20";
|
||||
assert_eq!(loopback_capture_pid(args), Some(4242));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn loopback_pid_matches_local_monitor_by_source() {
|
||||
// The local monitor: capture sink's monitor is the source, and the
|
||||
// destination is the real default sink (not a pixelpass name).
|
||||
let args = "source=pixelpass_capture_4242.monitor sink=@DEFAULT_SINK@ latency_msec=20";
|
||||
assert_eq!(loopback_capture_pid(args), Some(4242));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn loopback_pid_ignores_unrelated_loopback() {
|
||||
assert_eq!(
|
||||
loopback_capture_pid("source=alsa_output.pci.monitor sink=some_other_sink"),
|
||||
None
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
+79
-33
@@ -1,50 +1,96 @@
|
||||
use anyhow::{Context, Result};
|
||||
use iroh::Endpoint;
|
||||
use iroh::endpoint::presets;
|
||||
use anyhow::{Context, Result, bail};
|
||||
use iroh_tickets::endpoint::EndpointTicket;
|
||||
use std::time::Duration;
|
||||
use tokio::net::TcpListener;
|
||||
|
||||
use crate::cli::ViewerOpts;
|
||||
use crate::common::{alpn::ALPN, signal};
|
||||
use crate::common::{alpn::ALPN, endpoint, output, signal};
|
||||
|
||||
/// Cap on the initial QUIC connect. `endpoint.connect()` has no built-in
|
||||
/// deadline, so an offline host / stale code / unreachable relay otherwise
|
||||
/// hangs forever with no feedback (the silent "connecting…" failure mode).
|
||||
/// Matches the host's 15s `online()` cap.
|
||||
const CONNECT_TIMEOUT: Duration = Duration::from_secs(15);
|
||||
|
||||
pub async fn run(ticket: EndpointTicket, opts: ViewerOpts) -> Result<()> {
|
||||
let cancel = signal::install_ctrl_c();
|
||||
|
||||
let endpoint = Endpoint::builder(presets::N0)
|
||||
.alpns(vec![ALPN.to_vec()])
|
||||
.bind()
|
||||
.await?;
|
||||
let endpoint = endpoint::bind(opts.relay.as_deref()).await?;
|
||||
|
||||
let addr = ticket.endpoint_addr().clone();
|
||||
tracing::info!(remote = %addr.id, "connecting to host");
|
||||
let conn = endpoint.connect(addr, ALPN).await?;
|
||||
let (quic_send, quic_recv) = conn.open_bi().await?;
|
||||
|
||||
let listener = TcpListener::bind(("127.0.0.1", opts.port)).await?;
|
||||
let port = listener.local_addr()?.port();
|
||||
let url = format!("http://127.0.0.1:{port}");
|
||||
|
||||
if opts.interactive {
|
||||
let player = crate::interactive::prompt_player()?;
|
||||
player
|
||||
.spawn(&url)
|
||||
.with_context(|| "failed to launch player")?;
|
||||
print_viewer_banner_interactive();
|
||||
} else {
|
||||
print_viewer_banner(&url);
|
||||
}
|
||||
|
||||
let result = tokio::select! {
|
||||
accepted = listener.accept() => {
|
||||
let (tcp, peer) = accepted?;
|
||||
tracing::info!(%peer, "local viewer connected");
|
||||
crate::common::tunnel::bridge(quic_send, quic_recv, tcp).await
|
||||
}
|
||||
// Bound the connect attempt and let ctrl-c abort it, so the viewer fails
|
||||
// loud (and the GUI surfaces the error) instead of spinning indefinitely.
|
||||
let conn = tokio::select! {
|
||||
_ = cancel.cancelled() => {
|
||||
tracing::info!("ctrl-c received before local viewer connected");
|
||||
Ok(())
|
||||
tracing::info!("ctrl-c received before the connection was established");
|
||||
endpoint.close().await;
|
||||
return Ok(());
|
||||
}
|
||||
result = tokio::time::timeout(CONNECT_TIMEOUT, endpoint.connect(addr, ALPN)) => match result {
|
||||
Ok(Ok(conn)) => conn,
|
||||
Ok(Err(e)) => {
|
||||
endpoint.close().await;
|
||||
bail!("failed to connect to the host: {e:#}");
|
||||
}
|
||||
Err(_) => {
|
||||
endpoint.close().await;
|
||||
bail!(
|
||||
"couldn't reach the host within {}s — it may be offline, the share \
|
||||
code may be stale, or the relay may be unreachable. Check that the \
|
||||
host is running, then re-copy the code and try again.",
|
||||
CONNECT_TIMEOUT.as_secs()
|
||||
);
|
||||
}
|
||||
},
|
||||
};
|
||||
// Everything past the established connection runs in one block so any error
|
||||
// (open_bi, bind, local_addr, accept) is captured rather than `?`-propagated
|
||||
// straight out of the function — that would skip the close below and leak the
|
||||
// endpoint. The connect-phase arms above close explicitly for the same reason.
|
||||
let result = async {
|
||||
let (quic_send, quic_recv) = conn.open_bi().await?;
|
||||
|
||||
let listener = TcpListener::bind(("127.0.0.1", opts.port)).await?;
|
||||
let port = listener.local_addr()?.port();
|
||||
let url = format!("http://127.0.0.1:{port}");
|
||||
output::emit(output::Event::Connected { url: &url });
|
||||
|
||||
if opts.interactive {
|
||||
let player = crate::interactive::prompt_player()?;
|
||||
player
|
||||
.spawn(&url)
|
||||
.with_context(|| "failed to launch player")?;
|
||||
print_viewer_banner_interactive();
|
||||
} else {
|
||||
print_viewer_banner(&url);
|
||||
}
|
||||
|
||||
tokio::select! {
|
||||
accepted = listener.accept() => {
|
||||
let (tcp, peer) = accepted?;
|
||||
tracing::info!(%peer, "local viewer connected");
|
||||
// Race the bridge against ctrl-c so a disconnect lands promptly
|
||||
// mid-stream (mirrors the host's handle_peer). Without this, the
|
||||
// cancel token is set but nothing checks it once the player has
|
||||
// connected — ctrl-c is ignored until a second press, and a GUI
|
||||
// "Disconnect" only takes effect via the child's SIGKILL backstop.
|
||||
tokio::select! {
|
||||
res = crate::common::tunnel::bridge(quic_send, quic_recv, tcp) => res,
|
||||
_ = cancel.cancelled() => {
|
||||
tracing::info!("ctrl-c received during stream — disconnecting");
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
_ = cancel.cancelled() => {
|
||||
tracing::info!("ctrl-c received before local viewer connected");
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
.await;
|
||||
|
||||
endpoint.close().await;
|
||||
result
|
||||
@@ -56,7 +102,7 @@ fn print_viewer_banner(url: &str) {
|
||||
eprintln!("│ Connected to host. Open the stream in your player:");
|
||||
eprintln!("│");
|
||||
eprintln!(
|
||||
"│ mpv --profile=low-latency --untimed --hwdec=auto --audio-buffer=0.2 --demuxer-max-bytes=2M --demuxer-readahead-secs=0.5 {url}"
|
||||
"│ mpv --profile=low-latency --audio-buffer=0.2 --demuxer-max-bytes=2M --demuxer-readahead-secs=0.5 {url}"
|
||||
);
|
||||
eprintln!("│ vlc --network-caching=200 --live-caching=200 {url}");
|
||||
eprintln!("│");
|
||||
|
||||
Reference in New Issue
Block a user