Compare commits

..

1 Commits
1.1.8 ... 1.1.2

Author SHA1 Message Date
rustdesk
ad0a24ba23 source code 2021-03-27 09:41:55 +08:00
143 changed files with 7722 additions and 5050 deletions

1
.gitattributes vendored
View File

@@ -1 +0,0 @@
* text=auto

1
.github/FUNDING.yml vendored
View File

@@ -1,2 +1 @@
github: [rustdesk]
ko_fi: rustdesk

View File

@@ -1,32 +0,0 @@
---
name: Bug Report
about: Report a bug (English only, Please).
title: ""
labels: bug
assignees: ''
---
<!-- Hey there, thank you for creating an issue! -->
**Describe the bug you encountered:**
...
**What did you expect to happen instead?**
...
**How did you install `RustDesk`?**
<!-- GitHub release, build from source, Windows portable version, etc. -->
---
**RustDesk version and environment**
<!--
In order to reproduce your issue, please add some information about the environment
in which you're running RustDesk.
-->

View File

@@ -1,2 +0,0 @@
blank_issues_enabled: true

View File

@@ -1,10 +0,0 @@
---
name: Feature Request
about: Suggest an idea for this project ((English only, Please).
title: ''
labels: feature-request
assignees: ''
---

View File

@@ -1,10 +0,0 @@
---
name: Question
about: Ask a question about 'RustDesk' (English only, Please).
title: ''
labels: question
assignees: ''
---

View File

@@ -1,49 +0,0 @@
# Contributing to RustDesk
RustDesk welcomes contribution from everyone. Here are the guidelines if you are
thinking of helping us:
## Contributions
Contributions to RustDesk or its dependencies should be made in the form of GitHub
pull requests. Each pull request will be reviewed by a core contributor
(someone with permission to land patches) and either landed in the main tree or
given feedback for changes that would be required. All contributions should
follow this format, even those from core contributors.
Should you wish to work on an issue, please claim it first by commenting on
the GitHub issue that you want to work on it. This is to prevent duplicated
efforts from contributors on the same issue.
## Pull Request Checklist
- Branch from the master branch and, if needed, rebase to the current master
branch before submitting your pull request. If it doesn't merge cleanly with
master you may be asked to rebase your changes.
- Commits should be as small as possible, while ensuring that each commit is
correct independently (i.e., each commit should compile and pass tests).
- Commits should be accompanied by a Developer Certificate of Origin
(http://developercertificate.org) sign-off, which indicates that you (and
your employer if applicable) agree to be bound by the terms of the
[project license](LICENSE). In git, this is the `-s` option to `git commit`
- If your patch is not getting reviewed or you need a specific person to review
it, you can @-reply a reviewer asking for a review in the pull request or a
comment, or you can ask for a review via [email](mailto:info@rustdesk.com).
- Add tests relevant to the fixed bug or new feature.
For specific git instructions, see [GitHub workflow 101](https://github.com/servo/servo/wiki/Github-workflow).
## Conduct
We follow the [Rust Code of Conduct](https://www.rust-lang.org/policies/code-of-conduct).
## Communication
RustDesk contributors frequent the [Discord](https://discord.gg/nDceKgxnkV).

2214
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,23 +1,22 @@
[package]
name = "rustdesk"
version = "1.1.6"
version = "1.1.2"
authors = ["rustdesk <info@rustdesk.com>"]
edition = "2018"
build= "build.rs"
description = "A remote control software."
[lib]
crate-type = ["cdylib", "staticlib", "rlib"]
[features]
inline = []
cli = []
use_samplerate = ["samplerate"]
use_rubato = ["rubato"]
use_dasp = ["dasp"]
default = ["use_dasp"]
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
whoami = "1.1"
whoami = "0.9"
scrap = { path = "libs/scrap" }
hbb_common = { path = "libs/hbb_common" }
enigo = { path = "libs/enigo" }
@@ -29,31 +28,28 @@ lazy_static = "1.4"
sha2 = "0.9"
repng = "0.2"
libc = "0.2"
parity-tokio-ipc = { git = "https://github.com/open-trade/parity-tokio-ipc" }
flexi_logger = "0.17"
parity-tokio-ipc = { path = "libs/parity-tokio-ipc" }
flexi_logger = "0.16"
runas = "0.2"
magnum-opus = { git = "https://github.com/open-trade/magnum-opus" }
dasp = { version = "0.11", features = ["signal", "interpolate-linear", "interpolate"], optional = true }
rubato = { version = "0.8", optional = true }
samplerate = { version = "0.2", optional = true }
magnum-opus = { path = "libs/magnum-opus" }
dasp = { version = "0.11", features = ["signal", "interpolate-linear", "interpolate"] }
async-trait = "0.1"
crc32fast = "1.2"
uuid = { version = "0.8", features = ["v4"] }
copypasta = "0.7"
clap = "2.33"
rpassword = "5.0"
[target.'cfg(not(any(target_os = "android")))'.dependencies]
cpal = { git = "https://github.com/open-trade/cpal" }
cpal = { git = "https://github.com/rustaudio/cpal" }
[target.'cfg(not(any(target_os = "android", target_os = "ios")))'.dependencies]
machine-uid = "0.2"
mac_address = "1.1"
sciter-rs = { git = "https://github.com/open-trade/rust-sciter", branch = "dyn" }
ctrlc = "3.2"
arboard = "2.0"
sciter-rs = { git = "https://github.com/sciter-sdk/rust-sciter" }
[target.'cfg(target_os = "windows")'.dependencies]
#systray = { git = "https://github.com/open-trade/systray-rs" }
systray = { path = "libs/systray-rs" }
winapi = { version = "0.3", features = ["winuser"] }
winreg = "0.7"
windows-service = { git = 'https://github.com/mullvad/windows-service-rs.git' }
@@ -68,7 +64,8 @@ core-graphics = "0.22"
[target.'cfg(target_os = "linux")'.dependencies]
libpulse-simple-binding = "2.16"
libpulse-binding = "2.16"
rust-pulsectl = { git = "https://github.com/open-trade/pulsectl" }
rust-pulsectl = { path = "libs/pulsectl" }
ctrlc = "3.1"
[target.'cfg(not(any(target_os = "windows", target_os = "android", target_os = "ios")))'.dependencies]
psutil = "3.2"

View File

@@ -1,20 +0,0 @@
FROM debian
WORKDIR /
RUN apt update -y && apt install -y g++ gcc git curl wget nasm yasm libgtk-3-dev clang libxcb-randr0-dev libxdo-dev libxfixes-dev libxcb-shape0-dev libxcb-xfixes0-dev libasound2-dev libpulse-dev cmake unzip zip sudo
RUN git clone https://github.com/microsoft/vcpkg && cd vcpkg && git checkout 134505003bb46e20fbace51ccfb69243fbbc5f82
RUN /vcpkg/bootstrap-vcpkg.sh -disableMetrics
RUN /vcpkg/vcpkg --disable-metrics install libvpx libyuv opus
RUN groupadd -r user && useradd -r -g user user --home /home/user && mkdir -p /home/user && chown user /home/user
WORKDIR /home/user
RUN wget https://raw.githubusercontent.com/c-smile/sciter-sdk/master/bin.lnx/x64/libsciter-gtk.so
USER user
RUN curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs > rustup.sh
RUN chmod +x rustup.sh
RUN ./rustup.sh -y
USER root
COPY ./entrypoint /
ENTRYPOINT ["/entrypoint"]

View File

@@ -1,151 +0,0 @@
<p align="center">
<img src="logo-header.svg" alt="RustDesk - Your remote desktop"><br>
<a href="#kostenlose-öffentliche-server">Server</a> •
<a href="#die-groben-schritte-zum-kompilieren">Kompilieren</a> •
<a href="#auf-docker-kompilieren">Docker</a> •
<a href="#dateistruktur">Dateistruktur</a> •
<a href="#screenshots">Screenshots</a><br>
[<a href="README.md">English</a>] | [<a href="README-ZH.md">中文</a>] | [<a href="README-ES.md">Español</a>] | [<a href="README-FR.md">Français</a>] | [<a href="README-PL.md">Polski</a>] | [<a href="README-JP.md">日本語</a>] | [<a href="README-RU.md">Русский</a>] | [<a href="README-PT.md">Português</a>]<br>
<b>Wir brauchen deine Hilfe um diese README Datei zu verbessern und aktualisieren</b>
</p>
Rede mit uns: [Discord](https://discord.gg/nDceKgxnkV) | [Reddit](https://www.reddit.com/r/rustdesk)
[![ko-fi](https://ko-fi.com/img/githubbutton_sm.svg)](https://ko-fi.com/I2I04VU09)
Das hier ist ein Programm was man nutzen kann, um einen Computer fernzusteuern, es wurde in Rust geschrieben. Es funktioniert ohne Konfiguration oder ähnliches, man kann es einfach direkt nutzen. Es ist eine gute Alternative zu Programmen wie TeamViewer und AnyDesk! Du hast volle Kontrolle über deine Daten und brauchst dir daher auch keine Sorgen um die Sicherheit dieser Daten zu machen. Du kannst unseren rendezvous/relay Server nutzen, [einen eigenen Server eröffnen](https://rustdesk.com/blog/id-relay-set/) oder [einen neuen eigenen Server programmieren](https://github.com/rustdesk/rustdesk-server-demo).
RustDesk heißt jegliche Mitarbeit willkommen. Schau dir [`CONTRIBUTING.md`](CONTRIBUTING.md) an, wenn du Hilfe brauchst für den Start.
[**PROGRAMM DOWNLOAD**](https://github.com/rustdesk/rustdesk/releases)
## Kostenlose öffentliche Server
Hier sind die Server die du kostenlos nutzen kannst, es kann sein das sich diese Liste immer mal wieder ändert. Falls du nicht in der Nähe einer dieser Server bist, kann es sein, dass deine Verbindung langsam sein wird.
| Standort | Serverart | Spezifikationen | Kommentare |
| --------- | ------------- | ------------------ | ---------------------------------------- |
| Seoul | AWS lightsail | 1 VCPU / 0.5GB RAM | |
| Singapore | Vultr | 1 VCPU / 1GB RAM | |
| Dallas | Vultr | 1 VCPU / 1GB RAM | |
## Abhängigkeiten
Die Desktop Versionen nutzen [Sciter](https://sciter.com/) für die Oberfläche, bitte lade die dynamische Sciter Bibliothek selbst herunter.
[Windows](https://raw.githubusercontent.com/c-smile/sciter-sdk/master/bin.win/x64/sciter.dll) |
[Linux](https://raw.githubusercontent.com/c-smile/sciter-sdk/master/bin.lnx/x64/libsciter-gtk.so) |
[MacOS](https://raw.githubusercontent.com/c-smile/sciter-sdk/master/bin.osx/libsciter.dylib)
## Die groben Schritte zum Kompilieren
* Bereite deine Rust Entwicklungsumgebung und C++ Entwicklungsumgebung vor
* Installiere [vcpkg](https://github.com/microsoft/vcpkg) und füge die `VCPKG_ROOT` Systemumgebungsvariable hinzu
- Windows: `vcpkg install libvpx:x64-windows-static libyuv:x64-windows-static opus:x64-windows-static`
- Linux/MacOS: `vcpkg install libvpx libyuv opus`
* Nutze `cargo run`
## Kompilieren auf Linux
### Ubuntu 18 (Debian 10)
```sh
sudo apt install -y g++ gcc git curl wget nasm yasm libgtk-3-dev clang libxcb-randr0-dev libxdo-dev libxfixes-dev libxcb-shape0-dev libxcb-xfixes0-dev libasound2-dev libpulse-dev cmake
```
### Fedora 28 (CentOS 8)
```sh
sudo yum -y install gcc-c++ git curl wget nasm yasm gcc gtk3-devel clang libxcb-devel libxdo-devel libXfixes-devel pulseaudio-libs-devel cmake alsa-lib-devel
```
### Arch (Manjaro)
```sh
sudo pacman -Syu --needed unzip git cmake gcc curl wget yasm nasm zip make pkg-config clang gtk3 xdotool libxcb libxfixes alsa-lib pulseaudio
```
### vcpkg installieren
```sh
git clone https://github.com/microsoft/vcpkg
cd vcpkg
git checkout 134505003bb46e20fbace51ccfb69243fbbc5f82
cd ..
vcpkg/bootstrap-vcpkg.sh
export VCPKG_ROOT=$HOME/vcpkg
vcpkg/vcpkg install libvpx libyuv opus
```
### libvpx reparieren (Für Fedora)
```sh
cd vcpkg/buildtrees/libvpx/src
cd *
./configure
sed -i 's/CFLAGS+=-I/CFLAGS+=-fPIC -I/g' Makefile
sed -i 's/CXXFLAGS+=-I/CXXFLAGS+=-fPIC -I/g' Makefile
make
cp libvpx.a $HOME/vcpkg/installed/x64-linux/lib/
cd
```
### Kompilieren
```sh
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
source $HOME/.cargo/env
git clone https://github.com/rustdesk/rustdesk
cd rustdesk
mkdir -p target/debug
wget https://raw.githubusercontent.com/c-smile/sciter-sdk/master/bin.lnx/x64/libsciter-gtk.so
mv libsciter-gtk.so target/debug
cargo run
```
## Auf Docker Kompilieren
Beginne damit das Repository zu klonen und den Docker Container zu bauen:
```sh
git clone https://github.com/rustdesk/rustdesk
cd rustdesk
docker build -t "rustdesk-builder" .
```
Jedes Mal, wenn du das Programm Kompilieren musst, nutze diesen Befehl:
```sh
docker run --rm -it -v $PWD:/home/user/rustdesk -v rustdesk-git-cache:/home/user/.cargo/git -v rustdesk-registry-cache:/home/user/.cargo/registry -e PUID="$(id -u)" -e PGID="$(id -g)" rustdesk-builder
```
Bedenke, dass das erste Mal Kompilieren länger dauern kann, da die Abhängigkeiten erst kompiliert werden müssen bevor sie zwischengespeichert werden können. Darauf folgende Kompiliervorgänge werden schneller sein. Falls du zusätzliche oder andere Argumente für den Kompilierbefehl angeben musst, kannst du diese am Ende des Befehls an der `<OPTIONAL-ARGS>` Position machen. Wenn du zum Beispiel eine optimierte Releaseversion kompilieren willst, kannst du das tun indem du `--release` am Ende des Befehls anhängst. Das daraus entstehende Programm kannst du im “target” Ordner auf deinem System finden. Du kannst es mit folgenden Befehlen ausführen:
```sh
target/debug/rustdesk
```
Oder, wenn du eine Releaseversion benutzt:
```sh
target/release/rustdesk
```
Bitte gehe sicher, dass du diese Befehle vom Stammverzeichnis vom RustDesk Repository nutzt, sonst kann es passieren, dass das Programm die Ressourcen nicht finden kann. Bitte bedenke auch, dass Unterbefehle von Cargo, wie z.B. `install` oder `run` aktuell noch nicht unterstützt werden, da sie das Programm innerhalb des Containers starten oder installieren würden, anstatt auf deinem eigentlichen System.
### Ändere Wayland zu X11 (Xorg)
RustDesk unterstützt "Wayland" nicht. Siehe [hier](https://docs.fedoraproject.org/en-US/quick-docs/configuring-xorg-as-default-gnome-session/) um Xorg als Standard GNOME Session zu nutzen.
## Dateistruktur
- **[libs/hbb_common](https://github.com/rustdesk/rustdesk/tree/master/libs/hbb_common)**: Video Codec, Konfiguration, TCP/UDP Wrapper, Protokoll Puffer, fs Funktionen für Dateitransfer, und ein paar andere nützliche Funktionen
- **[libs/scrap](https://github.com/rustdesk/rustdesk/tree/master/libs/scrap)**: Bildschirmaufnahme
- **[libs/enigo](https://github.com/rustdesk/rustdesk/tree/master/libs/enigo)**: Plattformspezifische Maus und Tastatur Steuerung
- **[src/ui](https://github.com/rustdesk/rustdesk/tree/master/src/ui)**: GUI
- **[src/server](https://github.com/rustdesk/rustdesk/tree/master/src/server)**: Audio/Zwischenablage/Eingabe/Videodienste und Netzwerk Verbindungen
- **[src/client.rs](https://github.com/rustdesk/rustdesk/tree/master/src/client.rs)**: Starten einer Peer-Verbindung
- **[src/rendezvous_mediator.rs](https://github.com/rustdesk/rustdesk/tree/master/src/rendezvous_mediator.rs)**: Mit [rustdesk-server](https://github.com/rustdesk/rustdesk-server) kommunizieren, für Verbindung von außen warten, direkt (TCP hole punching) oder weitergeleitet
- **[src/platform](https://github.com/rustdesk/rustdesk/tree/master/src/platform)**: Plattformspezifischer Code
## Screenshots
![image](https://user-images.githubusercontent.com/71636191/113112362-ae4deb80-923b-11eb-957d-ff88daad4f06.png)
![image](https://user-images.githubusercontent.com/71636191/113112619-f705a480-923b-11eb-911d-97e984ef52b6.png)
![image](https://user-images.githubusercontent.com/71636191/113112857-3fbd5d80-923c-11eb-9836-768325faf906.png)
![image](https://user-images.githubusercontent.com/71636191/113112990-65e2fd80-923c-11eb-840e-349b4d6e340d.png)

View File

@@ -1,148 +0,0 @@
<p align="center">
<img src="logo-header.svg" alt="RustDesk - Your remote desktop"><br>
<a href="#servidores-gratis-de-uso-público">Servidores</a> •
<a href="#pasos-para-compilar-desde-el-inicio">Compilar</a> •
<a href="#como-compilar-con-docker">Docker</a> •
<a href="#estructura-de-archivos">Estructura</a> •
<a href="#captura-de-pantalla">Captura de pantalla</a><br>
[<a href="README.md">English</a>] | [<a href="README-ZH.md">中文</a>] | [<a href="README-DE.md">Deutsch</a>] | [<a href="README-FR.md">Français</a>] | [<a href="README-PL.md">Polski</a>] | [<a href="README-JP.md">日本語</a>] | [<a href="README-RU.md">Русский</a>] | [<a href="README-PT.md">Português</a>]<br>
<b>Necesitamos tu ayuda para traducir este README a tu idioma</b>
</p>
Chat with us: [Discord](https://discord.gg/nDceKgxnkV) | [Reddit](https://www.reddit.com/r/rustdesk)
[![ko-fi](https://ko-fi.com/img/githubbutton_sm.svg)](https://ko-fi.com/I2I04VU09)
Otro software de escritorio remoto, escrito en Rust. Funciona de forma inmediata, sin necesidad de configuración. Gran alternativa a TeamViewer o AnyDesk. Tienes el control total de sus datos, sin preocupaciones sobre la seguridad. Puedes utilizar nuestro servidor de rendezvous/relay, [set up your own](https://rustdesk.com/blog/id-relay-set/), o [escribir tu propio servidor rendezvous/relay](https://github.com/rustdesk/rustdesk-server-demo).
RustDesk agradece la contribución de todo el mundo. Ve [`CONTRIBUTING.md`](CONTRIBUTING.md) para ayuda inicial.
[**DESCARGA DE BINARIOS**](https://github.com/rustdesk/rustdesk/releases)
## Servidores gratis de uso público
A continuación se muestran los servidores que está utilizando de forma gratuita, puede cambiar en algún momento. Si no estás cerca de uno de ellos, tu red puede ser lenta.
- Seoul, AWS lightsail, 1 VCPU/0.5G RAM
- Singapore, Vultr, 1 VCPU/1G RAM
- Dallas, Vultr, 1 VCPU/1G RAM
## Dependencies
La versión Desktop usa [sciter](https://sciter.com/) para GUI, por favor bajate la librería sciter tu mismo..
[Windows](https://raw.githubusercontent.com/c-smile/sciter-sdk/master/bin.win/x64/sciter.dll) |
[Linux](https://raw.githubusercontent.com/c-smile/sciter-sdk/master/bin.lnx/x64/libsciter-gtk.so) |
[macOS](https://raw.githubusercontent.com/c-smile/sciter-sdk/master/bin.osx/libsciter.dylib)
## Pasos para compilar desde el inicio
* Prepara el entono de desarrollode Rust y el entorno de compilación de C++ y Rust.
* Instala [vcpkg](https://github.com/microsoft/vcpkg), y configura la variable de entono `VCPKG_ROOT` correctamente.
- Windows: vcpkg install libvpx:x64-windows-static libyuv:x64-windows-static opus:x64-windows-static
- Linux/Osx: vcpkg install libvpx libyuv opus
* run `cargo run`
## Como compilar en linux
### Ubuntu 18 (Debian 10)
```sh
sudo apt install -y g++ gcc git curl wget nasm yasm libgtk-3-dev clang libxcb-randr0-dev libxdo-dev libxfixes-dev libxcb-shape0-dev libxcb-xfixes0-dev libasound2-dev libpulse-dev cmake
```
### Fedora 28 (CentOS 8)
```sh
sudo yum -y install gcc-c++ git curl wget nasm yasm gcc gtk3-devel clang libxcb-devel libxdo-devel libXfixes-devel pulseaudio-libs-devel cmake alsa-lib-devel
```
### Arch (Manjaro)
```sh
sudo pacman -Syu --needed unzip git cmake gcc curl wget yasm nasm zip make pkg-config clang gtk3 xdotool libxcb libxfixes alsa-lib pulseaudio
```
### Install vcpkg
```sh
git clone https://github.com/microsoft/vcpkg
cd vcpkg
git checkout 134505003bb46e20fbace51ccfb69243fbbc5f82
cd ..
vcpkg/bootstrap-vcpkg.sh
export VCPKG_ROOT=$HOME/vcpkg
vcpkg/vcpkg install libvpx libyuv opus
```
### Soluciona libvpx (For Fedora)
```sh
cd vcpkg/buildtrees/libvpx/src
cd *
./configure
sed -i 's/CFLAGS+=-I/CFLAGS+=-fPIC -I/g' Makefile
sed -i 's/CXXFLAGS+=-I/CXXFLAGS+=-fPIC -I/g' Makefile
make
cp libvpx.a $HOME/vcpkg/installed/x64-linux/lib/
cd
```
### Compila
```sh
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
source $HOME/.cargo/env
git clone https://github.com/rustdesk/rustdesk
cd rustdesk
mkdir -p target/debug
wget https://raw.githubusercontent.com/c-smile/sciter-sdk/master/bin.lnx/x64/libsciter-gtk.so
mv libsciter-gtk.so target/debug
cargo run
```
## Como compilar con Docker
Empieza clonando el repositorio y compilando el contenedor de docker:
```sh
git clone https://github.com/rustdesk/rustdesk
cd rustdesk
docker build -t "rustdesk-builder" .
```
Entonces, cada vez que necesites compilar una modificación, ejecuta el siguiente comando:
```sh
docker run --rm -it -v $PWD:/home/user/rustdesk -v rustdesk-git-cache:/home/user/.cargo/git -v rustdesk-registry-cache:/home/user/.cargo/registry -e PUID="$(id -u)" -e PGID="$(id -g)" rustdesk-builder
```
Ten en cuenta que la primera compilación puede tardar más tiempo antes de que las dependencias se almacenen en la caché, las siguientes compilaciones serán más rápidas. Además, si necesitas especificar diferentes argumentos a la orden de compilación, puede hacerlo al final de la linea de comandos en el apartado`<OPTIONAL-ARGS>`. Por ejemplo, si desea compilar una versión optimizada para publicación, deberá ejecutar el comando anterior seguido de `---release`. El ejecutable resultante estará disponible en la carpeta de destino en su sistema, y puede ser ejecutado con:
```sh
target/debug/rustdesk
```
O si estas ejecutando una versión para su publicación:
```sh
target/release/rustdesk
```
Por favor, asegurate de que estás ejecutando estos comandos desde la raíz del repositorio de RustDesk, de lo contrario la aplicación puede ser incapaz de encontrar los recursos necesarios. También hay que tener en cuenta que otros subcomandos de carga como `install` o `run` no estan actualmente soportados via este metodo y podrían requerir ser instalados dentro del contenedor y no en el host.
### Cambia Wayland a X11 (Xorg)
RustDesk no soporta Wayland. Comprueba [aquí](https://docs.fedoraproject.org/en-US/quick-docs/configuring-xorg-as-default-gnome-session/) para configurar Xorg en la sesión por defecto de GNOME.
## Estructura de archivos
- **[libs/hbb_common](https://github.com/rustdesk/rustdesk/tree/master/libs/hbb_common)**: video codec, configuración, tcp/udp wrapper, protobuf, fs funciones para transferencia de ficheros, y alguna función de utilidad.
- **[libs/scrap](https://github.com/rustdesk/rustdesk/tree/master/libs/scrap)**: captura de pantalla
- **[libs/enigo](https://github.com/rustdesk/rustdesk/tree/master/libs/enigo)**: control específico por cada plataforma para el teclado/ratón
- **[src/ui](https://github.com/rustdesk/rustdesk/tree/master/src/ui)**: GUI
- **[src/server](https://github.com/rustdesk/rustdesk/tree/master/src/server)**: sonido/portapapeles/entrada/servicios de video, y conexiones de red
- **[src/client.rs](https://github.com/rustdesk/rustdesk/tree/master/src/client.rs)**: iniciar una conexión "peer to peer"
- **[src/rendezvous_mediator.rs](https://github.com/rustdesk/rustdesk/tree/master/src/rendezvous_mediator.rs)**: Comunicación con [rustdesk-server](https://github.com/rustdesk/rustdesk-server), esperar la conexión remota directa ("TCP hole punching") o conexión indirecta ("relayed")
- **[src/platform](https://github.com/rustdesk/rustdesk/tree/master/src/platform)**: código específico de cada plataforma
## Captura de pantalla
![image](https://user-images.githubusercontent.com/71636191/113112362-ae4deb80-923b-11eb-957d-ff88daad4f06.png)
![image](https://user-images.githubusercontent.com/71636191/113112619-f705a480-923b-11eb-911d-97e984ef52b6.png)
![image](https://user-images.githubusercontent.com/71636191/113112857-3fbd5d80-923c-11eb-9836-768325faf906.png)
![image](https://user-images.githubusercontent.com/71636191/113112990-65e2fd80-923c-11eb-840e-349b4d6e340d.png)

View File

@@ -1,148 +0,0 @@
<p align="center">
<img src="logo-header.svg" alt="RustDesk - Your remote desktop"><br>
<a href="#serveurs-publics-libres">Serveurs</a> -
<a href="#étapes-brutes-de-la-compilationbuild">Build</a> -
<a href="#comment-construire-avec-docker">Docker</a> -
<a href="#structure-du-projet">Structure</a> -
<a href="#images">Images</a><br>
[<a href="README.md">English</a>] | [<a href="README-ZH.md">中文</a>] | [<a href="README-DE.md">Deutsch</a>] | [<a href="README-ES.md">Española</a>] | [<a href="README-PL.md">Polski</a>] | [<a href="README-JP.md">日本語</a>] | [<a href="README-RU.md">Русский</a>] | [<a href="README-PT.md">Português</a>]<br>
<b>Nous avons besoin de votre aide pour traduire ce README dans votre langue maternelle</b>.
</p>
Chattez avec nous : [Discord](https://discord.gg/nDceKgxnkV) | [Reddit](https://www.reddit.com/r/rustdesk)
[![ko-fi](https://ko-fi.com/img/githubbutton_sm.svg)](https://ko-fi.com/I2I04VU09)
Encore un autre logiciel de bureau à distance, écrit en Rust. Fonctionne directement, aucune configuration n'est nécessaire. Une excellente alternative à TeamViewer et AnyDesk ! Vous avez le contrôle total de vos données, sans aucun souci de sécurité. Vous pouvez utiliser notre serveur de rendez-vous/relais, [configurer le vôtre](https://rustdesk.com/blog/id-relay-set/), ou [écrire votre propre serveur de rendez-vous/relais](https://github.com/rustdesk/rustdesk-server-demo).
RustDesk accueille les contributions de tout le monde. Voir [`CONTRIBUTING.md`](CONTRIBUTING.md) pour plus d'informations.
[**TÉLÉCHARGEMENT BINAIRE**](https://github.com/rustdesk/rustdesk/releases)
## Serveurs publics libres
Ci-dessous se trouvent les serveurs que vous utilisez gratuitement, cela peut changer au fil du temps. Si vous n'êtes pas proche de l'un d'entre eux, votre réseau peut être lent.
- Séoul, AWS lightsail, 1 VCPU/0.5G RAM
- Singapour, Vultr, 1 VCPU/1G RAM
- Dallas, Vultr, 1 VCPU/1G RAM
## Dépendances
Les versions de bureau utilisent [sciter](https://sciter.com/) pour l'interface graphique, veuillez télécharger la bibliothèque dynamique sciter vous-même.
[Windows](https://raw.githubusercontent.com/c-smile/sciter-sdk/master/bin.win/x64/sciter.dll) |
[Linux](https://raw.githubusercontent.com/c-smile/sciter-sdk/master/bin.lnx/x64/libsciter-gtk.so)
[macOS](https://raw.githubusercontent.com/c-smile/sciter-sdk/master/bin.osx/libsciter.dylib)
## Étapes brutes de la compilation/build
* Préparez votre environnement de développement Rust et votre environnement de compilation C++.
* Installez [vcpkg](https://github.com/microsoft/vcpkg), et définissez correctement la variable d'environnement `VCPKG_ROOT`.
- Windows : vcpkg install libvpx:x64-windows-static libyuv:x64-windows-static opus:x64-windows-static
- Linux/Osx : vcpkg install libvpx libyuv opus
* Exécuter `cargo run`
## Comment compiler/build sous Linux
### Ubuntu 18 (Debian 10)
```sh
sudo apt install -y g++ gcc git curl wget nasm yasm libgtk-3-dev clang libxcb-randr0-dev libxdo-dev libxfixes-dev libxcb-shape0-dev libxcb-xfixes0-dev libasound2-dev libpulse-dev cmake
```
### Fedora 28 (CentOS 8)
```sh
sudo yum -y install gcc-c++ git curl wget nasm yasm gcc gtk3-devel clang libxcb-devel libxdo-devel libXfixes-devel pulseaudio-libs-devel cmake alsa-lib-devel
```
### Arch (Manjaro)
```sh
sudo pacman -Syu --needed unzip git cmake gcc curl wget yasm nasm zip make pkg-config clang gtk3 xdotool libxcb libxfixes alsa-lib pulseaudio
```
### Installer vcpkg
```sh
git clone https://github.com/microsoft/vcpkg
cd vcpkg
git checkout 134505003bb46e20fbace51ccfb69243fbbc5f82
cd ..
vcpkg/bootstrap-vcpkg.sh
export VCPKG_ROOT=$HOME/vcpkg
vcpkg/vcpkg install libvpx libyuv opus
```
### Corriger libvpx (Pour Fedora)
```sh
cd vcpkg/buildtrees/libvpx/src
cd *
./configure
sed -i 's/CFLAGS+=-I/CFLAGS+=-fPIC -I/g' Makefile
sed -i 's/CXXFLAGS+=-I/CXXFLAGS+=-fPIC -I/g' Makefile
make
cp libvpx.a $HOME/vcpkg/installed/x64-linux/lib/
cd
```
### Construire
```sh
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
source $HOME/.cargo/env
git clone https://github.com/rustdesk/rustdesk
cd rustdesk
mkdir -p cible/debug
wget https://raw.githubusercontent.com/c-smile/sciter-sdk/master/bin.lnx/x64/libsciter-gtk.so
mv libsciter-gtk.so target/debug
Exécution du cargo
```
## Comment construire avec Docker
Commencez par cloner le dépôt et construire le conteneur Docker :
```sh
git clone https://github.com/rustdesk/rustdesk
cd rustdesk
docker build -t "rustdesk-builder" .
```
Ensuite, chaque fois que vous devez build le logiciel, exécutez la commande suivante :
```sh
docker run --rm -it -v $PWD:/home/user/rustdesk -v rustdesk-git-cache:/home/user/.cargo/git -v rustdesk-registry-cache:/home/user/.cargo/registry -e PUID="$(id -u)" -e PGID="$(id -g)" rustdesk-builder
```
Notez que le premier build peut prendre plus de temps avant que les dépendances ne soient mises en cache, les constructions suivantes seront plus rapides. De plus, si vous devez spécifier différents arguments à la commande de compilation, vous pouvez le faire à la fin de la commande dans la position `<OPTIONAL-ARGS>`. Par exemple, si vous voulez construire une version optimisée de la version release, vous devez exécuter la commande ci-dessus suivie de `---release`. L'exécutable résultant sera disponible dans le dossier cible sur votre système, et peut être lancé avec :
```sh
target/debug/rustdesk
```
Ou, si vous exécutez un exécutable provenant d'une release :
```sh
target/release/rustdesk
```
Veuillez vous assurer que vous exécutez ces commandes à partir de la racine du référentiel RustDesk, sinon l'application ne pourra pas trouver les ressources requises. Notez également que les autres sous-commandes de cargo telles que `install` ou `run` ne sont pas actuellement supportées par cette méthode car elles installeraient ou exécuteraient le programme à l'intérieur du conteneur au lieu de l'hôte.
### Changer Wayland en X11 (Xorg)
RustDesk ne supporte pas Wayland. Lisez [cela](https://docs.fedoraproject.org/en-US/quick-docs/configuring-xorg-as-default-gnome-session/) pour configurer Xorg comme la session GNOME par défaut.
## Structure du projet
- **[libs/hbb_common](https://github.com/rustdesk/rustdesk/tree/master/libs/hbb_common)** : codec vidéo, config, wrapper tcp/udp, protobuf, fonctions fs pour le transfert de fichiers, et quelques autres fonctions utilitaires.
- **[libs/scrap](https://github.com/rustdesk/rustdesk/tree/master/libs/scrap)** : capture d'écran
- **[libs/enigo](https://github.com/rustdesk/rustdesk/tree/master/libs/enigo)** : contrôle clavier/souris spécifique à la plate-forme
- **[src/ui](https://github.com/rustdesk/rustdesk/tree/master/src/ui)** : INTERFACE GRAPHIQUE
- **[src/server](https://github.com/rustdesk/rustdesk/tree/master/src/server)** : services audio/clipboard/input/vidéo, et connexions réseau
- **[src/client.rs](https://github.com/rustdesk/rustdesk/tree/master/src/client.rs)** : démarrer une connexion entre pairs
- **[src/rendezvous_mediator.rs](https://github.com/rustdesk/rustdesk/tree/master/src/rendezvous_mediator.rs)** : Communiquer avec [rustdesk-server](https://github.com/rustdesk/rustdesk-server), attendre une connexion distante directe (TCP hole punching) ou relayée.
- **[src/platform](https://github.com/rustdesk/rustdesk/tree/master/src/platform)** : code spécifique à la plateforme
## Images
![image](https://user-images.githubusercontent.com/71636191/113112362-ae4deb80-923b-11eb-957d-ff88daad4f06.png)
![image](https://user-images.githubusercontent.com/71636191/113112619-f705a480-923b-11eb-911d-97e984ef52b6.png)
![image](https://user-images.githubusercontent.com/71636191/113112857-3fbd5d80-923c-11eb-9836-768325faf906.png)
![image](https://user-images.githubusercontent.com/71636191/113112990-65e2fd80-923c-11eb-840e-349b4d6e340d.png)

View File

@@ -1,152 +0,0 @@
<p align="center">
<img src="logo-header.svg" alt="RustDesk - Your remote desktop"><br>
<a href="#darmowe-serwery-publiczne">Serwery</a> •
<a href="#podstawowe-kroki-do-kompilacji">Kompilacja</a> •
<a href="#jak-kompilować-za-pomocą-dockera">Docker</a> •
<a href="#struktura-plików">Struktura</a> •
<a href="#migawkisnapshoty">Snapshot</a><br>
[<a href="README.md">English</a>] | [<a href="README-ZH.md">中文</a>] | [<a href="README-DE.md">Deutsch</a>] | [<a href="README-ES.md">Española</a>] | [<a href="README-FR.md">Français</a>] | [<a href="README-JP.md">日本語</a>] | [<a href="README-RU.md">Русский</a>] | [<a href="README-PT.md">Português</a>]<br>
<b>Potrzebujemy twojej pomocy w tłumaczeniu README na twój ojczysty język</b>
</p>
Porozmawiaj z nami na: [Discord](https://discord.gg/nDceKgxnkV) | [Reddit](https://www.reddit.com/r/rustdesk)
[![ko-fi](https://ko-fi.com/img/githubbutton_sm.svg)](https://ko-fi.com/I2I04VU09)
Kolejny program do zdalnego pulpitu, napisany w Rust. Działa od samego początku, nie wymaga konfiguracji. Świetna alternatywa dla TeamViewera i AnyDesk! Masz pełną kontrolę nad swoimi danymi, bez obaw o bezpieczeństwo. Możesz skorzystać z naszego darmowego serwera publicznego , [skonfigurować własny](https://rustdesk.com/blog/id-relay-set/), lub [napisać własny serwer rendezvous/relay server](https://github.com/rustdesk/rustdesk-server-demo).
RustDesk zaprasza do współpracy każdego. Zobacz [`CONTRIBUTING.md`](CONTRIBUTING.md) pomoc w uruchomieniu programu.
[**POBIERZ KOMPILACJE**](https://github.com/rustdesk/rustdesk/releases)
## Darmowe Serwery Publiczne
Poniżej znajdują się serwery, z których można korzystać za darmo, może się to zmienić z upływem czasu. Jeśli nie znajdujesz się w pobliżu jednego z nich, Twoja prędkość połączenia może być niska.
| Lokalizacja | Dostawca | Specyfikacja |
| --------- | ------------- | ------------------ |
| Seul | AWS lightsail | 1 VCPU / 0.5GB RAM |
| Singapur | Vultr | 1 VCPU / 1GB RAM |
| Dallas | Vultr | 1 VCPU / 1GB RAM | |
## Zależności
Wersje desktopowe używają [sciter](https://sciter.com/) dla GUI, proszę pobrać bibliotekę dynamiczną sciter samodzielnie.
[Windows](https://raw.githubusercontent.com/c-smile/sciter-sdk/master/bin.win/x64/sciter.dll) |
[Linux](https://raw.githubusercontent.com/c-smile/sciter-sdk/master/bin.lnx/x64/libsciter-gtk.so) |
[MacOS](https://raw.githubusercontent.com/c-smile/sciter-sdk/master/bin.osx/libsciter.dylib)
## Podstawowe kroki do kompilacji.
* Przygotuj środowisko programistyczne Rust i środowisko programowania C++
* Zainstaluj [vcpkg](https://github.com/microsoft/vcpkg), i ustaw `VCPKG_ROOT` env zmienną prawidłowo
- Windows: vcpkg install libvpx:x64-windows-static libyuv:x64-windows-static opus:x64-windows-static
- Linux/MacOS: vcpkg install libvpx libyuv opus
* uruchom `cargo run`
## Jak Kompilować na Linuxie
### Ubuntu 18 (Debian 10)
```sh
sudo apt install -y g++ gcc git curl wget nasm yasm libgtk-3-dev clang libxcb-randr0-dev libxdo-dev libxfixes-dev libxcb-shape0-dev libxcb-xfixes0-dev libasound2-dev libpulse-dev cmake
```
### Fedora 28 (CentOS 8)
```sh
sudo yum -y install gcc-c++ git curl wget nasm yasm gcc gtk3-devel clang libxcb-devel libxdo-devel libXfixes-devel pulseaudio-libs-devel cmake alsa-lib-devel
```
### Arch (Manjaro)
```sh
sudo pacman -Syu --needed unzip git cmake gcc curl wget yasm nasm zip make pkg-config clang gtk3 xdotool libxcb libxfixes alsa-lib pulseaudio
```
### Zainstaluj vcpkg
```sh
git clone https://github.com/microsoft/vcpkg
cd vcpkg
git checkout 134505003bb46e20fbace51ccfb69243fbbc5f82
cd ..
vcpkg/bootstrap-vcpkg.sh
export VCPKG_ROOT=$HOME/vcpkg
vcpkg/vcpkg install libvpx libyuv opus
```
### Fix libvpx (For Fedora)
```sh
cd vcpkg/buildtrees/libvpx/src
cd *
./configure
sed -i 's/CFLAGS+=-I/CFLAGS+=-fPIC -I/g' Makefile
sed -i 's/CXXFLAGS+=-I/CXXFLAGS+=-fPIC -I/g' Makefile
make
cp libvpx.a $HOME/vcpkg/installed/x64-linux/lib/
cd
```
### Kompilacja
```sh
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
source $HOME/.cargo/env
git clone https://github.com/rustdesk/rustdesk
cd rustdesk
mkdir -p target/debug
wget https://raw.githubusercontent.com/c-smile/sciter-sdk/master/bin.lnx/x64/libsciter-gtk.so
mv libsciter-gtk.so target/debug
cargo run
```
## Jak kompilować za pomocą Dockera
Rozpocznij od sklonowania repozytorium i stworzenia kontenera docker:
```sh
git clone https://github.com/rustdesk/rustdesk
cd rustdesk
docker build -t "rustdesk-builder" .
```
Następnie, za każdym razem, gdy potrzebujesz skompilować aplikację, uruchom następujące polecenie:
```sh
docker run --rm -it -v $PWD:/home/user/rustdesk -v rustdesk-git-cache:/home/user/.cargo/git -v rustdesk-registry-cache:/home/user/.cargo/registry -e PUID="$(id -u)" -e PGID="$(id -g)" rustdesk-builder
```
Zauważ, że pierwsza kompilacja może potrwać dłużej zanim zależności zostaną zbuforowane, kolejne będą szybsze. Dodatkowo, jeśli potrzebujesz określić inne argumenty dla polecenia budowania, możesz to zrobić na końcu komendy w miejscu `<OPTIONAL-ARGS>`. Na przykład, jeśli chciałbyś zbudować zoptymalizowaną wersję wydania, uruchomiłbyś powyższą komendę a następnie `---release`. Powstały plik wykonywalny będzie dostępny w folderze docelowym w twoim systemie, i może być uruchomiony z:
```sh
target/debug/rustdesk
```
Lub, jeśli uruchamiasz plik wykonywalny wersji:
```sh
target/release/rustdesk
```
Upewnij się, że uruchamiasz te polecenia z katalogu głównego repozytorium RustDesk, w przeciwnym razie aplikacja może nie być w stanie znaleźć wymaganych zasobów. Należy również pamiętać, że inne podpolecenia ładowania, takie jak `install` lub `run` nie są obecnie obsługiwane za pomocą tej metody, ponieważ instalowałyby lub uruchamiały program wewnątrz kontenera zamiast na hoście.
### Zmień Wayland na X11 (Xorg)
RustDesk nie obsługuje Waylanda. Sprawdź [this](https://docs.fedoraproject.org/en-US/quick-docs/configuring-xorg-as-default-gnome-session/) by skonfigurować Xorg jako domyślną sesję GNOME.
## Struktura plików
- **[libs/hbb_common](https://github.com/rustdesk/rustdesk/tree/master/libs/hbb_common)**: kodek wideo, config, wrapper tcp/udp, protobuf, funkcje fs do transferu plików i kilka innych funkcji użytkowych
- **[libs/scrap](https://github.com/rustdesk/rustdesk/tree/master/libs/scrap)**: przechwytywanie ekranu
- **[libs/enigo](https://github.com/rustdesk/rustdesk/tree/master/libs/enigo)**: specyficzne dla danej platformy sterowanie klawiaturą/myszą
- **[src/ui](https://github.com/rustdesk/rustdesk/tree/master/src/ui)**: GUI
- **[src/server](https://github.com/rustdesk/rustdesk/tree/master/src/server)**: audio/schowek/wejście(input)/wideo oraz połączenia sieciowe
- **[src/client.rs](https://github.com/rustdesk/rustdesk/tree/master/src/client.rs)**: uruchamia połączenie peer
- **[src/rendezvous_mediator.rs](https://github.com/rustdesk/rustdesk/tree/master/src/rendezvous_mediator.rs)**: Komunikacja z [rustdesk-server](https://github.com/rustdesk/rustdesk-server), wait for remote direct (TCP hole punching) or relayed connection
- **[src/platform](https://github.com/rustdesk/rustdesk/tree/master/src/platform)**: specyficzny dla danej platformy kod
## Migawki(Snapshoty)
![image](https://user-images.githubusercontent.com/71636191/113112362-ae4deb80-923b-11eb-957d-ff88daad4f06.png)
![image](https://user-images.githubusercontent.com/71636191/113112619-f705a480-923b-11eb-911d-97e984ef52b6.png)
![image](https://user-images.githubusercontent.com/71636191/113112857-3fbd5d80-923c-11eb-9836-768325faf906.png)
![image](https://user-images.githubusercontent.com/71636191/113112990-65e2fd80-923c-11eb-840e-349b4d6e340d.png)

View File

@@ -1,154 +0,0 @@
<p align="center">
<img src="logo-header.svg" alt="RustDesk - Your remote desktop"><br>
<a href="#免费公共服务器">服务器</a> •
<a href="#基本构建步骤">编译</a> •
<a href="#使用Docker编译">Docker</a> •
<a href="#文件结构">结构</a> •
<a href="#截图">截图</a><br>
[<a href="README.md">English</a>] | [<a href="README-ES.md">Español</a>] | [<a href="README-FR.md">Français</a>] | [<a href="README-DE.md">Deutsch</a>] | [<a href="README-PL.md">Polski</a>] | [<a href="README-JP.md">日本語</a>] | [<a href="README-RU.md">Русский</a>] | [<a href="README-PT.md">Português</a>]<br>
</p>
Chat with us: [知乎](https://www.zhihu.com/people/rustdesk) | [Discord](https://discord.gg/nDceKgxnkV) | [Reddit](https://www.reddit.com/r/rustdesk)
[![ko-fi](https://ko-fi.com/img/githubbutton_sm.svg)](https://ko-fi.com/I2I04VU09)
远程桌面软件开箱即用无需任何配置替代TeamViewer和AnyDesk。您完全掌控数据不用担心安全问题。您可以使用我们的注册/中继服务器,
或者[自己设置](https://rustdesk.com/blog/id-relay-set/)
亦或者[开发您的版本](https://github.com/rustdesk/rustdesk-server-demo)。
欢迎大家贡献代码, 请看 [`CONTRIBUTING.md`](CONTRIBUTING.md).
[**可执行程序下载**](https://github.com/rustdesk/rustdesk/releases)
## 免费公共服务器
以下是您免费使用的服务器,它可能会随着时间的推移而变化。如果您不靠近其中之一,您的网络可能会很慢。
- 首尔, AWS lightsail, 1 VCPU/0.5G RAM
- 新加坡, Vultr, 1 VCPU/1G RAM
- 达拉斯, Vultr, 1 VCPU/1G RAM
## 依赖
桌面版本界面使用[sciter](https://sciter.com/), 请自行下载。
[Windows](https://raw.githubusercontent.com/c-smile/sciter-sdk/master/bin.win/x64/sciter.dll) |
[Linux](https://raw.githubusercontent.com/c-smile/sciter-sdk/master/bin.lnx/x64/libsciter-gtk.so) |
[macOS](https://raw.githubusercontent.com/c-smile/sciter-sdk/master/bin.osx/libsciter.dylib)
## 基本构建步骤
* 请准备好Rust开发环境和C++编译环境
* 安装[vcpkg](https://github.com/microsoft/vcpkg), 正确设置`VCPKG_ROOT`环境变量
- Windows: vcpkg install libvpx:x64-windows-static libyuv:x64-windows-static opus:x64-windows-static
- Linux/Osx: vcpkg install libvpx libyuv opus
* 运行 `cargo run`
## 在Linux上编译
### Ubuntu 18 (Debian 10)
```sh
sudo apt install -y g++ gcc git curl wget nasm yasm libgtk-3-dev clang libxcb-randr0-dev libxdo-dev libxfixes-dev libxcb-shape0-dev libxcb-xfixes0-dev libasound2-dev libpulse-dev cmake
```
### Fedora 28 (CentOS 8)
```sh
sudo yum -y install gcc-c++ git curl wget nasm yasm gcc gtk3-devel clang libxcb-devel libxdo-devel libXfixes-devel pulseaudio-libs-devel cmake alsa-lib-devel
```
### Arch (Manjaro)
```sh
sudo pacman -Syu --needed unzip git cmake gcc curl wget yasm nasm zip make pkg-config clang gtk3 xdotool libxcb libxfixes alsa-lib pulseaudio
```
### 安装vcpkg
```sh
git clone https://github.com/microsoft/vcpkg
cd vcpkg
git checkout 134505003bb46e20fbace51ccfb69243fbbc5f82
cd ..
vcpkg/bootstrap-vcpkg.sh
export VCPKG_ROOT=$HOME/vcpkg
vcpkg/vcpkg install libvpx libyuv opus
```
### 修复libvpx (仅仅针对Fedora)
```sh
cd vcpkg/buildtrees/libvpx/src
cd *
./configure
sed -i 's/CFLAGS+=-I/CFLAGS+=-fPIC -I/g' Makefile
sed -i 's/CXXFLAGS+=-I/CXXFLAGS+=-fPIC -I/g' Makefile
make
cp libvpx.a $HOME/vcpkg/installed/x64-linux/lib/
cd
```
### 构建
```sh
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
source $HOME/.cargo/env
git clone https://github.com/rustdesk/rustdesk
cd rustdesk
mkdir -p target/debug
wget https://raw.githubusercontent.com/c-smile/sciter-sdk/master/bin.lnx/x64/libsciter-gtk.so
mv libsciter-gtk.so target/debug
cargo run
```
## 使用Docker编译
首先克隆存储库并构建 docker 容器:
```sh
git clone https://github.com/rustdesk/rustdesk
cd rustdesk
docker build -t "rustdesk-builder" .
```
然后,每次需要构建应用程序时,运行以下命令:
```sh
docker run --rm -it -v $PWD:/home/user/rustdesk -v rustdesk-git-cache:/home/user/.cargo/git -v rustdesk-registry-cache:/home/user/.cargo/registry -e PUID="$(id -u)" -e PGID="$(id -g)" rustdesk-builder
```
请注意,第一次构建可能需要比较长的时间,因为需要缓存依赖项,后续构建会更快。此外,如果您需要为构建命令指定不同的参数,
您可以在命令末尾的 `<OPTIONAL-ARGS>` 位置执行此操作。例如,如果你想构建一个优化的发布版本,你可以在命令后跟 `---release`
将在target下产生可执行程序请通过以下方式运行调试版本
```sh
target/debug/rustdesk
```
或者运行发布版本:
```sh
target/release/rustdesk
```
请确保您从 RustDesk 存储库的根目录运行这些命令,否则应用程序可能无法找到所需的资源。另请注意,此方法当前不支持其他`Cargo`子命令,
例如 `install``run`,因为运行在容器里,而不是宿主机上。
### 把Wayland修改成X11 (Xorg)
RustDesk暂时不支持Wayland不过正在积极开发中.
请查看[this](https://docs.fedoraproject.org/en-US/quick-docs/configuring-xorg-as-default-gnome-session/)配置X11.
## 文件结构
- **[libs/hbb_common](https://github.com/rustdesk/rustdesk/tree/master/libs/hbb_common)**: 视频编解码, 配置, tcp/udp封装, protobuf, 文件传输相关文件系统操作函数, 以及一些其他实用函数
- **[libs/scrap](https://github.com/rustdesk/rustdesk/tree/master/libs/scrap)**: 截屏
- **[libs/enigo](https://github.com/rustdesk/rustdesk/tree/master/libs/enigo)**: 平台相关的鼠标键盘输入
- **[src/ui](https://github.com/rustdesk/rustdesk/tree/master/src/ui)**: GUI
- **[src/server](https://github.com/rustdesk/rustdesk/tree/master/src/server)**: 被控端服务audio/clipboard/input/video服务, 已经连接实现
- **[src/client.rs](https://github.com/rustdesk/rustdesk/tree/master/src/client.rs)**: 控制端
- **[src/rendezvous_mediator.rs](https://github.com/rustdesk/rustdesk/tree/master/src/rendezvous_mediator.rs)**: 与[rustdesk-server](https://github.com/rustdesk/rustdesk-server)保持UDP通讯, 等待远程连接(通过打洞直连或者中继)
- **[src/platform](https://github.com/rustdesk/rustdesk/tree/master/src/platform)**: 平台服务相关代码
## 截图
![image](https://user-images.githubusercontent.com/71636191/113112362-ae4deb80-923b-11eb-957d-ff88daad4f06.png)
![image](https://user-images.githubusercontent.com/71636191/113112619-f705a480-923b-11eb-911d-97e984ef52b6.png)
![image](https://user-images.githubusercontent.com/71636191/113112857-3fbd5d80-923c-11eb-9836-768325faf906.png)
![image](https://user-images.githubusercontent.com/71636191/113112990-65e2fd80-923c-11eb-840e-349b4d6e340d.png)

138
README.md
View File

@@ -1,134 +1,27 @@
<p align="center">
<img src="logo-header.svg" alt="RustDesk - Your remote desktop"><br>
<a href="#free-public-servers">Servers</a> •
<a href="#raw-steps-to-build">Build</a> •
<a href="#how-to-build-with-docker">Docker</a> •
<a href="#file-structure">Structure</a> •
<a href="#snapshot">Snapshot</a><br>
[<a href="README-ZH.md">中文</a>] | [<a href="README-ES.md">Español</a>] | [<a href="README-FR.md">Français</a>] | [<a href="README-DE.md">Deutsch</a>] | [<a href="README-PL.md">Polski</a>] | [<a href="README-JP.md">日本語</a>] | [<a href="README-RU.md">Русский</a>] | [<a href="README-PT.md">Português</a>]<br>
<b>We need your help to translate this README to your native language</b>
</p>
### RustDesk | Your Remote Desktop Software
Chat with us: [Discord](https://discord.gg/nDceKgxnkV) | [Reddit](https://www.reddit.com/r/rustdesk)
[![ko-fi](https://ko-fi.com/img/githubbutton_sm.svg)](https://ko-fi.com/I2I04VU09)
Yet another remote desktop software, written in Rust. Works out of the box, no configuration required. Great alternative to TeamViewer and AnyDesk! You have full control of your data, with no concerns about security. You can use our rendezvous/relay server, [set up your own](https://rustdesk.com/blog/id-relay-set/), or [write your own rendezvous/relay server](https://github.com/rustdesk/rustdesk-server-demo).
RustDesk welcomes contribution from everyone. See [`CONTRIBUTING.md`](CONTRIBUTING.md) for help getting started.
The best open source remote desktop software written with Rust.
[**BINARY DOWNLOAD**](https://github.com/rustdesk/rustdesk/releases)
## Free Public Servers
Below are the servers you are using for free, it may change along the time. If you are not close to one of these, your network may be slow.
| Location | Vendor | Specification |
| --------- | ------------- | ------------------ |
| Seoul | AWS lightsail | 1 VCPU / 0.5GB RAM |
| Singapore | Vultr | 1 VCPU / 1GB RAM |
| Dallas | Vultr | 1 VCPU / 1GB RAM | |
## Dependencies
## Dependence
Desktop versions use [sciter](https://sciter.com/) for GUI, please download sciter dynamic library yourself.
[Windows](https://raw.githubusercontent.com/c-smile/sciter-sdk/master/bin.win/x64/sciter.dll) |
[Linux](https://raw.githubusercontent.com/c-smile/sciter-sdk/master/bin.lnx/x64/libsciter-gtk.so) |
[MacOS](https://raw.githubusercontent.com/c-smile/sciter-sdk/master/bin.osx/libsciter.dylib)
[Windows](https://github.com/c-smile/sciter-sdk/blob/dc65744b66389cd5a0ff6bdb7c63a8b7b05a708b/bin.win/x64/sciter.dll)
[Linux](https://github.com/c-smile/sciter-sdk/raw/dc65744b66389cd5a0ff6bdb7c63a8b7b05a708b/bin.lnx/x64/libsciter-gtk.so)
[Osx](https://github.com/c-smile/sciter-sdk/raw/dc65744b66389cd5a0ff6bdb7c63a8b7b05a708b/bin.osx/sciter-osx-64.dylib)
## How To Build
## Raw steps to build
* Prepare your Rust development env and C++ build env
* Install [vcpkg](https://github.com/microsoft/vcpkg), and set `VCPKG_ROOT` env variable correctly
* Install [vcpkg](https://github.com/microsoft/vcpkg), and set VCPKG_ROOT env variable correctly
- Windows: vcpkg install libvpx:x64-windows-static libyuv:x64-windows-static opus:x64-windows-static
- Linux/MacOS: vcpkg install libvpx libyuv opus
- Linux/Osx: vcpkg install libvpx libyuv opus
* run `cargo run`
## How to build on Linux
### Ubuntu 18 (Debian 10)
```sh
sudo apt install -y g++ gcc git curl wget nasm yasm libgtk-3-dev clang libxcb-randr0-dev libxdo-dev libxfixes-dev libxcb-shape0-dev libxcb-xfixes0-dev libasound2-dev libpulse-dev cmake
```
### Fedora 28 (CentOS 8)
```sh
sudo yum -y install gcc-c++ git curl wget nasm yasm gcc gtk3-devel clang libxcb-devel libxdo-devel libXfixes-devel pulseaudio-libs-devel cmake alsa-lib-devel
```
### Arch (Manjaro)
```sh
sudo pacman -Syu --needed unzip git cmake gcc curl wget yasm nasm zip make pkg-config clang gtk3 xdotool libxcb libxfixes alsa-lib pulseaudio
```
### Install vcpkg
```sh
git clone https://github.com/microsoft/vcpkg
cd vcpkg
git checkout 134505003bb46e20fbace51ccfb69243fbbc5f82
cd ..
vcpkg/bootstrap-vcpkg.sh
export VCPKG_ROOT=$HOME/vcpkg
vcpkg/vcpkg install libvpx libyuv opus
```
### Fix libvpx (For Fedora)
```sh
cd vcpkg/buildtrees/libvpx/src
cd *
./configure
sed -i 's/CFLAGS+=-I/CFLAGS+=-fPIC -I/g' Makefile
sed -i 's/CXXFLAGS+=-I/CXXFLAGS+=-fPIC -I/g' Makefile
make
cp libvpx.a $HOME/vcpkg/installed/x64-linux/lib/
cd
```
### Build
```sh
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
source $HOME/.cargo/env
git clone https://github.com/rustdesk/rustdesk
cd rustdesk
mkdir -p target/debug
wget https://raw.githubusercontent.com/c-smile/sciter-sdk/master/bin.lnx/x64/libsciter-gtk.so
mv libsciter-gtk.so target/debug
cargo run
```
## How to build with Docker
Begin by cloning the repository and building the docker container:
```sh
git clone https://github.com/rustdesk/rustdesk
cd rustdesk
docker build -t "rustdesk-builder" .
```
Then, each time you need to build the application, run the following command:
```sh
docker run --rm -it -v $PWD:/home/user/rustdesk -v rustdesk-git-cache:/home/user/.cargo/git -v rustdesk-registry-cache:/home/user/.cargo/registry -e PUID="$(id -u)" -e PGID="$(id -g)" rustdesk-builder
```
Note that the first build may take longer before dependencies are cached, subsequent builds will be faster. Additionally, if you need to specify different arguments to the build command, you may do so at the end of the command in the `<OPTIONAL-ARGS>` position. For instance, if you wanted to build an optimized release version, you would run the command above followed by `---release`. The resulting executable will be available in the target folder on your system, and can be run with:
```sh
target/debug/rustdesk
```
Or, if you're running a release executable:
```sh
target/release/rustdesk
```
Please ensure that you are running these commands from the root of the RustDesk repository, otherwise the application may be unable to find the required resources. Also note that other cargo subcommands such as `install` or `run` are not currently supported via this method as they would install or run the program inside the container instead of the host.
### Change Wayland to X11 (Xorg)
RustDesk does not support Wayland. Check [this](https://docs.fedoraproject.org/en-US/quick-docs/configuring-xorg-as-default-gnome-session/) to configuring Xorg as the default GNOME session.
* cargo run
## File Structure
@@ -140,12 +33,3 @@ RustDesk does not support Wayland. Check [this](https://docs.fedoraproject.org/e
- **[src/client.rs](https://github.com/rustdesk/rustdesk/tree/master/src/client.rs)**: start a peer connection
- **[src/rendezvous_mediator.rs](https://github.com/rustdesk/rustdesk/tree/master/src/rendezvous_mediator.rs)**: Communicate with [rustdesk-server](https://github.com/rustdesk/rustdesk-server), wait for remote direct (TCP hole punching) or relayed connection
- **[src/platform](https://github.com/rustdesk/rustdesk/tree/master/src/platform)**: platform specific code
## Snapshot
![image](https://user-images.githubusercontent.com/71636191/113112362-ae4deb80-923b-11eb-957d-ff88daad4f06.png)
![image](https://user-images.githubusercontent.com/71636191/113112619-f705a480-923b-11eb-911d-97e984ef52b6.png)
![image](https://user-images.githubusercontent.com/71636191/113112857-3fbd5d80-923c-11eb-9836-768325faf906.png)
![image](https://user-images.githubusercontent.com/71636191/113112990-65e2fd80-923c-11eb-840e-349b4d6e340d.png)

View File

@@ -1,13 +0,0 @@
# Security Policy
## Supported Versions
| Version | Supported |
| ------- | ------------------ |
| 1.1.x | :white_check_mark: |
| 1.x | :white_check_mark: |
| Below 1.0 | :x: |
## Reporting a Vulnerability
Here we should write what to do in case of a security vulnerability

View File

@@ -1,7 +1,7 @@
#[cfg(windows)]
fn build_windows() {
cc::Build::new().file("src/windows.cc").compile("windows");
println!("cargo:rustc-link-lib=WtsApi32");
cc::Build::new().file("windows.cc").compile("windows");
// println!("cargo:rustc-link-lib=WtsApi32");
println!("cargo:rerun-if-changed=build.rs");
println!("cargo:rerun-if-changed=windows.cc");
}

View File

@@ -1,42 +0,0 @@
#!/bin/sh
if [ "$(id -u)" != "${PUID:-1000}" ] || [ "$(id -g)" != "${PGID:-1000}" ]; then
usermod -o -u "${PUID:-1000}" user
groupmod -o -g "${PGID:-1000}" user
chown -R user /home/user
sudo -u user /entrypoint $@
exit 0
fi
cd $HOME/rustdesk
. $HOME/.cargo/env
argv=$@
while test $# -gt 0; do
case "$1" in
--release)
mkdir -p target/release
test -f target/release/libsciter-gtk.so || cp $HOME/libsciter-gtk.so target/release/
release=1
shift
;;
--target)
shift
if test $# -gt 0; then
rustup target add $1
shift
fi
;;
*)
shift
;;
esac
done
if [ -z $release ]; then
mkdir -p target/debug
test -f target/debug/libsciter-gtk.so || cp $HOME/libsciter-gtk.so target/debug/
fi
VCPKG_ROOT=/vcpkg cargo build $argv

View File

@@ -299,7 +299,7 @@ pub enum Key {
/// meta key (also known as "windows", "super", and "command")
Meta,
/// option key on macOS (alt key on Linux and Windows)
Option, // deprecated, use Alt instead
Option,
/// page down key
PageDown,
/// page up key
@@ -347,6 +347,8 @@ pub enum Key {
///
Clear,
///
Menu,
///
Pause,
///
Kana,
@@ -407,12 +409,6 @@ pub enum Key {
///
NumpadEnter,
///
RightShift,
///
RightControl,
///
RightAlt,
///
/// Function, /// mac
/// keyboard layout dependent key
Layout(char),
@@ -489,7 +485,7 @@ impl Enigo {
/// ```
pub fn new() -> Self {
#[cfg(any(target_os = "android", target_os = "ios"))]
return Enigo {};
return Enigo{};
#[cfg(not(any(target_os = "android", target_os = "ios")))]
Self::default()
}

View File

@@ -238,6 +238,7 @@ fn keysequence<'a>(key: Key) -> Cow<'a, str> {
Key::Decimal => "U2E", //"KP_Decimal",
Key::Cancel => "Cancel",
Key::Clear => "Clear",
Key::Menu => "Menu",
Key::Pause => "Pause",
Key::Kana => "Kana",
Key::Hangul => "Hangul",
@@ -259,17 +260,14 @@ fn keysequence<'a>(key: Key) -> Cow<'a, str> {
Key::Mute => "",
Key::Scroll => "Scroll_Lock",
Key::NumLock => "Num_Lock",
Key::RWin => "Super_R",
Key::Apps => "Menu",
Key::RWin => "",
Key::Apps => "",
Key::Multiply => "KP_Multiply",
Key::Add => "KP_Add",
Key::Subtract => "KP_Subtract",
Key::Divide => "KP_Divide",
Key::Equals => "KP_Equal",
Key::NumpadEnter => "KP_Enter",
Key::RightShift => "Shift_R",
Key::RightControl => "Control_R",
Key::RightAlt => "Alt_R",
Key::Command | Key::Super | Key::Windows | Key::Meta => "Super",

View File

@@ -70,51 +70,3 @@ pub const kVK_ANSI_KeypadDivide: u16 = 0x4B;
pub const kVK_ANSI_KeypadEnter: u16 = 0x4C;
pub const kVK_ANSI_KeypadMinus: u16 = 0x4E;
pub const kVK_ANSI_KeypadEquals: u16 = 0x51;
pub const kVK_RIGHT_COMMAND: u16 = 0x36;
pub const kVK_ANSI_A : u16 = 0x00;
pub const kVK_ANSI_S : u16 = 0x01;
pub const kVK_ANSI_D : u16 = 0x02;
pub const kVK_ANSI_F : u16 = 0x03;
pub const kVK_ANSI_H : u16 = 0x04;
pub const kVK_ANSI_G : u16 = 0x05;
pub const kVK_ANSI_Z : u16 = 0x06;
pub const kVK_ANSI_X : u16 = 0x07;
pub const kVK_ANSI_C : u16 = 0x08;
pub const kVK_ANSI_V : u16 = 0x09;
pub const kVK_ANSI_B : u16 = 0x0B;
pub const kVK_ANSI_Q : u16 = 0x0C;
pub const kVK_ANSI_W : u16 = 0x0D;
pub const kVK_ANSI_E : u16 = 0x0E;
pub const kVK_ANSI_R : u16 = 0x0F;
pub const kVK_ANSI_Y : u16 = 0x10;
pub const kVK_ANSI_T : u16 = 0x11;
pub const kVK_ANSI_1 : u16 = 0x12;
pub const kVK_ANSI_2 : u16 = 0x13;
pub const kVK_ANSI_3 : u16 = 0x14;
pub const kVK_ANSI_4 : u16 = 0x15;
pub const kVK_ANSI_6 : u16 = 0x16;
pub const kVK_ANSI_5 : u16 = 0x17;
pub const kVK_ANSI_Equal : u16 = 0x18;
pub const kVK_ANSI_9 : u16 = 0x19;
pub const kVK_ANSI_7 : u16 = 0x1A;
pub const kVK_ANSI_Minus : u16 = 0x1B;
pub const kVK_ANSI_8 : u16 = 0x1C;
pub const kVK_ANSI_0 : u16 = 0x1D;
pub const kVK_ANSI_RightBracket : u16 = 0x1E;
pub const kVK_ANSI_O : u16 = 0x1F;
pub const kVK_ANSI_U : u16 = 0x20;
pub const kVK_ANSI_LeftBracket : u16 = 0x21;
pub const kVK_ANSI_I : u16 = 0x22;
pub const kVK_ANSI_P : u16 = 0x23;
pub const kVK_ANSI_L : u16 = 0x25;
pub const kVK_ANSI_J : u16 = 0x26;
pub const kVK_ANSI_Quote : u16 = 0x27;
pub const kVK_ANSI_K : u16 = 0x28;
pub const kVK_ANSI_Semicolon : u16 = 0x29;
pub const kVK_ANSI_Backslash : u16 = 0x2A;
pub const kVK_ANSI_Comma : u16 = 0x2B;
pub const kVK_ANSI_Slash : u16 = 0x2C;
pub const kVK_ANSI_N : u16 = 0x2D;
pub const kVK_ANSI_M : u16 = 0x2E;
pub const kVK_ANSI_Period : u16 = 0x2F;
pub const kVK_ANSI_Grave : u16 = 0x32;

View File

@@ -9,6 +9,12 @@ use self::core_graphics::event_source::*;
use crate::macos::keycodes::*;
use crate::{Key, KeyboardControllable, MouseButton, MouseControllable};
use objc::runtime::Class;
use std::ffi::CStr;
use std::os::raw::*;
// required for pressedMouseButtons on NSEvent
#[link(name = "AppKit", kind = "framework")]
extern "C" {}
struct MyCGEvent;
@@ -28,6 +34,8 @@ extern "C" {
fn CGEventSourceKeyState(stateID: i32, key: u16) -> bool;
}
pub type CFDataRef = *const c_void;
#[repr(C)]
#[derive(Clone, Copy)]
struct NSPoint {
@@ -35,6 +43,160 @@ struct NSPoint {
y: f64,
}
#[repr(C)]
pub struct __TISInputSource;
pub type TISInputSourceRef = *const __TISInputSource;
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct __CFString([u8; 0]);
pub type CFStringRef = *const __CFString;
pub type Boolean = c_uchar;
pub type UInt8 = c_uchar;
pub type SInt32 = c_int;
pub type UInt16 = c_ushort;
pub type UInt32 = c_uint;
pub type UniChar = UInt16;
pub type UniCharCount = c_ulong;
pub type OptionBits = UInt32;
pub type OSStatus = SInt32;
pub type CFStringEncoding = UInt32;
#[allow(non_upper_case_globals)]
pub const kUCKeyActionDisplay: _bindgen_ty_702 = _bindgen_ty_702::kUCKeyActionDisplay;
#[allow(non_camel_case_types)]
#[repr(u32)]
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub enum _bindgen_ty_702 {
// kUCKeyActionDown = 0,
// kUCKeyActionUp = 1,
// kUCKeyActionAutoKey = 2,
kUCKeyActionDisplay = 3,
}
#[allow(non_snake_case)]
#[repr(C)]
#[derive(Debug, Clone, Copy)]
pub struct UCKeyboardTypeHeader {
pub keyboardTypeFirst: UInt32,
pub keyboardTypeLast: UInt32,
pub keyModifiersToTableNumOffset: UInt32,
pub keyToCharTableIndexOffset: UInt32,
pub keyStateRecordsIndexOffset: UInt32,
pub keyStateTerminatorsOffset: UInt32,
pub keySequenceDataIndexOffset: UInt32,
}
#[allow(non_snake_case)]
#[repr(C)]
#[derive(Debug, Clone, Copy)]
pub struct UCKeyboardLayout {
pub keyLayoutHeaderFormat: UInt16,
pub keyLayoutDataVersion: UInt16,
pub keyLayoutFeatureInfoOffset: UInt32,
pub keyboardTypeCount: UInt32,
pub keyboardTypeList: [UCKeyboardTypeHeader; 1usize],
}
#[allow(non_upper_case_globals)]
pub const kUCKeyTranslateNoDeadKeysBit: _bindgen_ty_703 =
_bindgen_ty_703::kUCKeyTranslateNoDeadKeysBit;
#[allow(non_camel_case_types)]
#[repr(u32)]
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub enum _bindgen_ty_703 {
kUCKeyTranslateNoDeadKeysBit = 0,
}
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct __CFAllocator([u8; 0]);
pub type CFAllocatorRef = *const __CFAllocator;
// #[repr(u32)]
// #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
// pub enum _bindgen_ty_15 {
// kCFStringEncodingMacRoman = 0,
// kCFStringEncodingWindowsLatin1 = 1280,
// kCFStringEncodingISOLatin1 = 513,
// kCFStringEncodingNextStepLatin = 2817,
// kCFStringEncodingASCII = 1536,
// kCFStringEncodingUnicode = 256,
// kCFStringEncodingUTF8 = 134217984,
// kCFStringEncodingNonLossyASCII = 3071,
// kCFStringEncodingUTF16BE = 268435712,
// kCFStringEncodingUTF16LE = 335544576,
// kCFStringEncodingUTF32 = 201326848,
// kCFStringEncodingUTF32BE = 402653440,
// kCFStringEncodingUTF32LE = 469762304,
// }
#[allow(non_upper_case_globals)]
pub const kCFStringEncodingUTF8: u32 = 134_217_984;
#[allow(improper_ctypes)]
#[link(name = "Carbon", kind = "framework")]
extern "C" {
fn TISCopyCurrentKeyboardInputSource() -> TISInputSourceRef;
// extern void *
// TISGetInputSourceProperty(
// TISInputSourceRef inputSource,
// CFStringRef propertyKey)
#[allow(non_upper_case_globals)]
#[link_name = "kTISPropertyUnicodeKeyLayoutData"]
pub static kTISPropertyUnicodeKeyLayoutData: CFStringRef;
#[allow(non_snake_case)]
pub fn TISGetInputSourceProperty(
inputSource: TISInputSourceRef,
propertyKey: CFStringRef,
) -> *mut c_void;
#[allow(non_snake_case)]
pub fn CFDataGetBytePtr(theData: CFDataRef) -> *const UInt8;
#[allow(non_snake_case)]
pub fn UCKeyTranslate(
keyLayoutPtr: *const UInt8, //*const UCKeyboardLayout,
virtualKeyCode: UInt16,
keyAction: UInt16,
modifierKeyState: UInt32,
keyboardType: UInt32,
keyTranslateOptions: OptionBits,
deadKeyState: *mut UInt32,
maxStringLength: UniCharCount,
actualStringLength: *mut UniCharCount,
unicodeString: *mut UniChar,
) -> OSStatus;
pub fn LMGetKbdType() -> UInt8;
#[allow(non_snake_case)]
pub fn CFStringCreateWithCharacters(
alloc: CFAllocatorRef,
chars: *const UniChar,
numChars: CFIndex,
) -> CFStringRef;
#[allow(non_upper_case_globals)]
#[link_name = "kCFAllocatorDefault"]
pub static kCFAllocatorDefault: CFAllocatorRef;
#[allow(non_snake_case)]
pub fn CFStringGetCString(
theString: CFStringRef,
buffer: *mut c_char,
bufferSize: CFIndex,
encoding: CFStringEncoding,
) -> Boolean;
}
// not present in servo/core-graphics
#[allow(dead_code)]
#[derive(Debug)]
@@ -47,6 +209,7 @@ enum ScrollUnit {
/// The main struct for handling the event emitting
pub struct Enigo {
event_source: Option<CGEventSource>,
keycode_to_string_map: std::collections::HashMap<String, CGKeyCode>,
double_click_interval: u32,
last_click_time: Option<std::time::Instant>,
multiple_click: i64,
@@ -98,6 +261,7 @@ impl Default for Enigo {
} else {
None
},
keycode_to_string_map: Default::default(),
double_click_interval,
multiple_click: 1,
last_click_time: None,
@@ -419,71 +583,97 @@ impl Enigo {
Key::Subtract => kVK_ANSI_KeypadMinus,
Key::Equals => kVK_ANSI_KeypadEquals,
Key::NumLock => kVK_ANSI_KeypadClear,
Key::RWin => kVK_RIGHT_COMMAND,
Key::RightShift => kVK_RightShift,
Key::RightControl => kVK_RightControl,
Key::RightAlt => kVK_RightOption,
Key::Raw(raw_keycode) => raw_keycode,
Key::Layout(c) => self.map_key_board(c),
Key::Layout(c) => self.get_layoutdependent_keycode(c.to_string()),
Key::Super | Key::Command | Key::Windows | Key::Meta => kVK_Command,
_ => 0,
}
}
#[inline]
fn map_key_board(&self, ch: char) -> CGKeyCode {
match ch {
'a' => kVK_ANSI_A,
'b' => kVK_ANSI_B,
'c' => kVK_ANSI_C,
'd' => kVK_ANSI_D,
'e' => kVK_ANSI_E,
'f' => kVK_ANSI_F,
'g' => kVK_ANSI_G,
'h' => kVK_ANSI_H,
'i' => kVK_ANSI_I,
'j' => kVK_ANSI_J,
'k' => kVK_ANSI_K,
'l' => kVK_ANSI_L,
'm' => kVK_ANSI_M,
'n' => kVK_ANSI_N,
'o' => kVK_ANSI_O,
'p' => kVK_ANSI_P,
'q' => kVK_ANSI_Q,
'r' => kVK_ANSI_R,
's' => kVK_ANSI_S,
't' => kVK_ANSI_T,
'u' => kVK_ANSI_U,
'v' => kVK_ANSI_V,
'w' => kVK_ANSI_W,
'x' => kVK_ANSI_X,
'y' => kVK_ANSI_Y,
'z' => kVK_ANSI_Z,
'0' => kVK_ANSI_0,
'1' => kVK_ANSI_1,
'2' => kVK_ANSI_2,
'3' => kVK_ANSI_3,
'4' => kVK_ANSI_4,
'5' => kVK_ANSI_5,
'6' => kVK_ANSI_6,
'7' => kVK_ANSI_7,
'8' => kVK_ANSI_8,
'9' => kVK_ANSI_9,
'-' => kVK_ANSI_Minus,
'=' => kVK_ANSI_Equal,
'[' => kVK_ANSI_LeftBracket,
']' => kVK_ANSI_RightBracket,
'\\' => kVK_ANSI_Backslash,
';' => kVK_ANSI_Semicolon,
'\'' => kVK_ANSI_Quote,
',' => kVK_ANSI_Comma,
'.' => kVK_ANSI_Period,
'/' => kVK_ANSI_Slash,
'`' => kVK_ANSI_Grave,
_ => 0,
fn get_layoutdependent_keycode(&mut self, string: String) -> CGKeyCode {
if self.keycode_to_string_map.is_empty() {
self.init_map();
}
*self.keycode_to_string_map.get(&string).unwrap_or(&0)
}
fn init_map(&mut self) {
self.keycode_to_string_map.insert("".to_owned(), 0);
// loop through every keycode (0 - 127)
for keycode in 0..128 {
// no modifier
if let Some(key_string) = self.keycode_to_string(keycode, 0x100) {
self.keycode_to_string_map.insert(key_string, keycode);
}
// shift modifier
if let Some(key_string) = self.keycode_to_string(keycode, 0x20102) {
self.keycode_to_string_map.insert(key_string, keycode);
}
// alt modifier
// if let Some(string) = self.keycode_to_string(keycode, 0x80120) {
// println!("{:?}", string);
// }
// alt + shift modifier
// if let Some(string) = self.keycode_to_string(keycode, 0xa0122) {
// println!("{:?}", string);
// }
}
}
fn keycode_to_string(&self, keycode: u16, modifier: u32) -> Option<String> {
let cf_string = self.create_string_for_key(keycode, modifier);
unsafe {
if !cf_string.is_null() {
let mut buf: [i8; 255] = [0; 255];
let success = CFStringGetCString(
cf_string,
buf.as_mut_ptr(),
buf.len() as _,
kCFStringEncodingUTF8,
);
if success != 0 {
let name: &CStr = CStr::from_ptr(buf.as_ptr());
if let Ok(name) = name.to_str() {
return Some(name.to_owned());
}
}
}
}
None
}
fn create_string_for_key(&self, keycode: u16, modifier: u32) -> CFStringRef {
let current_keyboard = unsafe { TISCopyCurrentKeyboardInputSource() };
let layout_data = unsafe {
TISGetInputSourceProperty(current_keyboard, kTISPropertyUnicodeKeyLayoutData)
};
let keyboard_layout = unsafe { CFDataGetBytePtr(layout_data) };
let mut keys_down: UInt32 = 0;
// let mut chars: *mut c_void;//[UniChar; 4];
let mut chars: u16 = 0;
let mut real_length: UniCharCount = 0;
unsafe {
UCKeyTranslate(
keyboard_layout,
keycode,
kUCKeyActionDisplay as u16,
modifier,
LMGetKbdType() as u32,
kUCKeyTranslateNoDeadKeysBit as u32,
&mut keys_down,
8, // sizeof(chars) / sizeof(chars[0]),
&mut real_length,
&mut chars,
);
}
unsafe { CFStringCreateWithCharacters(kCFAllocatorDefault, &chars, 1) }
}
}

View File

@@ -1,7 +1,4 @@
// https://msdn.microsoft.com/en-us/library/windows/desktop/dd375731
//
// JP/KR mapping https://github.com/TigerVNC/tigervnc/blob/1a008c1380305648ab50f1d99e73439747e9d61d/vncviewer/win32.c#L267
// altgr handle: https://github.com/TigerVNC/tigervnc/blob/dccb95f345f7a9c5aa785a19d1bfa3fdecd8f8e0/vncviewer/Viewport.cxx#L1066
pub const EVK_RETURN: u16 = 0x0D;
pub const EVK_TAB: u16 = 0x09;
@@ -10,14 +7,9 @@ pub const EVK_BACK: u16 = 0x08;
pub const EVK_ESCAPE: u16 = 0x1b;
pub const EVK_LWIN: u16 = 0x5b;
pub const EVK_SHIFT: u16 = 0x10;
//pub const EVK_LSHIFT: u16 = 0xa0;
pub const EVK_RSHIFT: u16 = 0xa1;
//pub const EVK_LMENU: u16 = 0xa4;
pub const EVK_RMENU: u16 = 0xa5;
pub const EVK_CAPITAL: u16 = 0x14;
pub const EVK_MENU: u16 = 0x12;
pub const EVK_LCONTROL: u16 = 0xa2;
pub const EVK_RCONTROL: u16 = 0xa3;
pub const EVK_HOME: u16 = 0x24;
pub const EVK_PRIOR: u16 = 0x21;
pub const EVK_NEXT: u16 = 0x22;

View File

@@ -176,13 +176,13 @@ impl KeyboardControllable for Enigo {
}
fn key_click(&mut self, key: Key) {
let vk = self.key_to_keycode(key);
keybd_event(0, vk, 0);
keybd_event(KEYEVENTF_KEYUP, vk, 0);
let scancode = self.key_to_scancode(key);
keybd_event(KEYEVENTF_SCANCODE, 0, scancode);
keybd_event(KEYEVENTF_KEYUP | KEYEVENTF_SCANCODE, 0, scancode);
}
fn key_down(&mut self, key: Key) -> crate::ResultType {
let res = keybd_event(0, self.key_to_keycode(key), 0);
let res = keybd_event(KEYEVENTF_SCANCODE, 0, self.key_to_scancode(key));
if res == 0 {
let err = get_error();
if !err.is_empty() {
@@ -193,7 +193,11 @@ impl KeyboardControllable for Enigo {
}
fn key_up(&mut self, key: Key) {
keybd_event(KEYEVENTF_KEYUP, self.key_to_keycode(key), 0);
keybd_event(
KEYEVENTF_KEYUP | KEYEVENTF_SCANCODE,
0,
self.key_to_scancode(key),
);
}
fn get_key_state(&mut self, key: Key) -> bool {
@@ -303,6 +307,7 @@ impl Enigo {
Key::Numpad9 => EVK_NUMPAD9,
Key::Cancel => EVK_CANCEL,
Key::Clear => EVK_CLEAR,
Key::Menu => EVK_MENU,
Key::Pause => EVK_PAUSE,
Key::Kana => EVK_KANA,
Key::Hangul => EVK_HANGUL,
@@ -333,9 +338,6 @@ impl Enigo {
Key::Divide => EVK_DIVIDE,
Key::NumpadEnter => EVK_RETURN,
Key::Equals => '=' as _,
Key::RightShift => EVK_RSHIFT,
Key::RightControl => EVK_RCONTROL,
Key::RightAlt => EVK_RMENU,
Key::Raw(raw_keycode) => raw_keycode,
Key::Layout(c) => self.get_layoutdependent_keycode(c.to_string()),
@@ -343,6 +345,11 @@ impl Enigo {
}
}
fn key_to_scancode(&self, key: Key) -> u16 {
let keycode = self.key_to_keycode(key);
unsafe { MapVirtualKeyW(keycode as u32, 0) as u16 }
}
fn get_layoutdependent_keycode(&self, string: String) -> u16 {
// get the first char from the string ignore the rest
// ensure its not a multybyte char

View File

@@ -1,26 +1,26 @@
[package]
name = "hbb_common"
version = "0.1.0"
authors = ["rustdesk<info@rustdesk.com>"]
authors = ["open-trade <info@opentradesolutions.com>"]
edition = "2018"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
protobuf = { version = "3.0.0-pre", git = "https://github.com/stepancheg/rust-protobuf" }
tokio = { version = "1.10", features = ["full"] }
tokio-util = { version = "0.6", features = ["full"] }
tokio = { version = "0.2", features = ["full"] }
tokio-util = { version = "0.3", features = ["full"] }
futures = "0.3"
bytes = "1.0"
bytes = "0.5"
log = "0.4"
env_logger = "0.9"
env_logger = "0.8"
socket2 = { version = "0.3", features = ["reuseport"] }
zstd = "0.9"
zstd = "0.5"
quinn = {version = "0.6", optional = true }
anyhow = "1.0"
futures-util = "0.3"
directories-next = "2.0"
rand = "0.8"
rand = "0.7"
serde_derive = "1.0"
serde = "1.0"
lazy_static = "1.4"

View File

@@ -129,7 +129,7 @@ enum ControlKey {
Numpad9 = 42;
Cancel = 43;
Clear = 44;
Menu = 45; // deprecated, use Alt instead
Menu = 45;
Pause = 46;
Kana = 47;
Hangul = 48;
@@ -157,9 +157,6 @@ enum ControlKey {
Divide = 70;
Equals = 71;
NumpadEnter = 72;
RShift= 73;
RControl = 74;
RAlt = 75;
CtrlAltDel = 100;
LockScreen = 101;
}

View File

@@ -6,19 +6,11 @@ message RegisterPeer {
int32 serial = 2;
}
enum ConnType {
DEFAULT_CONN = 0;
FILE_TRANSFER = 1;
PORT_FORWARD = 2;
RDP = 3;
}
message RegisterPeerResponse { bool request_pk = 2; }
message PunchHoleRequest {
string id = 1;
NatType nat_type = 2;
ConnType conn_type = 4;
}
message PunchHole {
@@ -60,11 +52,6 @@ message RegisterPkResponse {
enum Result {
OK = 1;
UUID_MISMATCH = 2;
ID_EXISTS = 3;
TOO_FREQUENT = 4;
INVALID_ID_FORMAT = 5;
NOT_SUPPORT = 6;
SERVER_ERROR = 7;
}
Result result = 1;
}
@@ -75,8 +62,6 @@ message PunchHoleResponse {
enum Failure {
ID_NOT_EXIST = 1;
OFFLINE = 2;
LICENCE_MISMATCH = 3;
LICENCE_OVERUSE = 4;
}
Failure failure = 3;
string relay_server = 4;
@@ -84,7 +69,6 @@ message PunchHoleResponse {
NatType nat_type = 5;
bool is_local = 6;
}
string other_failure = 7;
}
message ConfigUpdate {
@@ -98,7 +82,6 @@ message RequestRelay {
bytes socket_addr = 3;
string relay_server = 4;
bool secure = 5;
ConnType conn_type = 7;
}
message RelayResponse {
@@ -109,7 +92,6 @@ message RelayResponse {
string id = 4;
bytes pk = 5;
}
string refuse_reason = 6;
}
message SoftwareUpdate { string url = 1; }
@@ -127,7 +109,6 @@ message LocalAddr {
bytes socket_addr = 1;
bytes local_addr = 2;
string relay_server = 3;
string id = 4;
}
message RendezvousMessage {

View File

@@ -17,7 +17,7 @@ pub const BIND_INTERFACE: &str = "0.0.0.0";
pub const RENDEZVOUS_TIMEOUT: u64 = 12_000;
pub const CONNECT_TIMEOUT: u64 = 18_000;
pub const COMPRESS_LEVEL: i32 = 3;
const SERIAL: i32 = 1;
const SERIAL: i32 = 0;
// 128x128
#[cfg(target_os = "macos")] // 128x128 on 160x160 canvas, then shrink to 128, mac looks better with padding
pub const ICON: &str = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAIAAAACACAMAAAD04JH5AAAAyVBMVEUAAAAAcf8Acf8Acf8Acv8Acf8Acf8Acf8Acf8AcP8Acf8Ab/8AcP8Acf////8AaP/z+f/o8v/k7v/5/v/T5f8AYP/u9v/X6f+hx/+Kuv95pP8Aef/B1/+TwP9xoP8BdP/g6P+Irv9ZmP8Bgf/E3f98q/9sn/+01f+Es/9nm/9Jif8hhv8off/M4P+syP+avP86iP/c7f+xy/9yqf9Om/9hk/9Rjv+60P99tv9fpf88lv8yjf8Tgf8deP+kvP8BiP8NeP8hkP80gP8oj2VLAAAADXRSTlMA7o7qLvnaxZ1FOxYPjH9HWgAABHJJREFUeNrtm+tW4jAQgBfwuu7MtIUWsOUiCCioIIgLiqvr+z/UHq/LJKVkmwTcc/r9E2nzlU4mSTP9lpGRkZGR8VX5cZjfL+yCEXYL+/nDH//U/Pd8DgyTy39Xbv7oIAcWyB0cqbW/sweW2NtRaj8H1sgpGOwUIAH7Bkd7YJW9dXFwAJY5WNP/cmCZQnJvzIN18on5LwfWySXlxEPYAIcad8D6PdiHDbCfIFCADVBIENiFDbCbIACKPPXrZ+cP8E6/0znvP4EymgIEravIRcTxu8HxNSJ60a8W0AYECKrlAN+YwAthCd9wm1Ug6wKzIn5SgRduXfwkqDasCjx0XFzi9PV6zwNcIuhcWBOg+ikySq8C9UD4dEKWBCoOcspvAuLHTo9sCDQiFPHotRM48j8G5gVur1FdAN2uaYEuiz7xFsgEJ2RUoMUakXuBTHHoGxQYOBhHjeUBAefEnMAowFhaLBOKuOemBBbxLRQrH2PBCgMvNCPQGMeevTb9zLrPxz2Mo+QbEaijzPUcOOHMQZkKGRAIPem39+bypREMPTkQW/oCfk866zAkiIFG4yIKRE/aAnfiSd0WrORY6pFdXQEqi9mvAQm0RIOSnoCcZ8vJoz3diCnjRk+g8VP4/fuQDJ2Lxr6WwG0gXs9aTpDzW0vgDBlVUpixR8gYk44AD8FrUKHr8JQJGgIDnoDqoALxmWPQSi9AVVzm8gKUuEPGr/QCvptwJkbSYT/TC4S8C96DGjTj86aHtAI0x2WaBIq0eSYYpRa4EsdWVVwWu9O0Aj6f6dyBMnwEraeOgSYu0wZlauzA47QCbT7DgAQSE+hZWoEBF/BBmWOewNMK3BsSqKUW4MGcWqCSVmDkbvkXGKQOwg6PAUO9oL3xXhA20yaiCjuwYygRVQlUOTWTCf2SuNJTxeFjgaHByGuAIvd8ItdPLTDhS7IuqEE1YSKVOgbayLhSFQhMzYh8hwfBs1r7c505YVIQYEdNoKwxK06MJiyrpUFHiF0NAfCQUVHoiRclIXJIR6C2fqG37pBHvcWpgwzvAtYwkR5UGV2e42UISdBJETl3mg8ouo54Rcnti1/vaT+iuUQBt500Cgo4U10BeHSkk57FB0JjWkKRMWgLUA0lLodtImAQdaMiiri3+gIAPZQoutHNsgKF1aaDMhMyIdBf8Th+Bh8MTjGWCpl5Wv43tDmnF+IUVMrcZgRoiAxhtrloYizNkZaAnF5leglbNhj0wYCAbCDvGb0mP4nib7O7ZlcYQ2m1gPtIZgVgGNNMeaVAaWR+57TrqgtUnm3sHQ+kYeE6fufUubG1ez50FXbPnWgBlgSABmN3TTcsRl2yWkHRrwbiunvk/W2+Mg1hPZplPDeXRbZzStFH15s1QIVd3UImP5z/bHpeeQLvRJ7XLFUffQIlCvqlXETQbgN9/rlYABGosv+Vi9m2Xs639YLGrZd0br+odetlvdsvbN56abfd4vbCzv9Q3v/ygoOV21A4OPpfXvH4Ai+5ZGRkZGRkbJA/t/I0QMzoMiEAAAAASUVORK5CYII=
@@ -48,7 +48,6 @@ const CHARS: &'static [char] = &[
];
pub const RENDEZVOUS_SERVERS: &'static [&'static str] = &[
"rs-ny.rustdesk.com",
"rs-sg.rustdesk.com",
"rs-cn.rustdesk.com",
];
@@ -149,17 +148,6 @@ fn patch(path: PathBuf) -> PathBuf {
.into();
#[cfg(target_os = "macos")]
return _tmp.replace("Application Support", "Preferences").into();
#[cfg(target_os = "linux")]
{
if _tmp == "/root" {
if let Ok(output) = std::process::Command::new("whoami").output() {
let user = String::from_utf8_lossy(&output.stdout).to_string().trim().to_owned();
if user != "root" {
return format!("/home/{}", user).into();
}
}
}
}
}
path
}
@@ -272,7 +260,6 @@ impl Config {
}
pub fn log_path() -> PathBuf {
#[allow(unreachable_code)]
#[cfg(target_os = "macos")]
{
if let Some(path) = dirs_next::home_dir().as_mut() {
@@ -282,10 +269,11 @@ impl Config {
}
#[cfg(target_os = "linux")]
{
let mut path = Self::get_home();
path.push(format!(".local/share/logs/{}", APP_NAME));
std::fs::create_dir_all(&path).ok();
return path;
if let Some(path) = dirs_next::home_dir().as_mut() {
path.push(format!(".local/share/logs/{}", APP_NAME));
std::fs::create_dir_all(&path).ok();
return path.clone();
}
}
if let Some(path) = Self::path("").parent() {
let mut path: PathBuf = path.into();
@@ -549,7 +537,7 @@ impl Config {
// to-do: how about if one ip register a lot of ids?
let id = Self::get_id();
let mut rng = rand::thread_rng();
let new_id = rng.gen_range(1_000_000_000..2_000_000_000).to_string();
let new_id = rng.gen_range(1_000_000_000, 2_000_000_000).to_string();
Config::set_id(&new_id);
log::info!("id updated from {} to {}", id, new_id);
}
@@ -648,7 +636,7 @@ impl PeerConfig {
Config::path(path).with_extension("toml")
}
pub fn peers() -> Vec<(String, SystemTime, PeerConfig)> {
pub fn peers() -> Vec<(String, SystemTime, PeerInfoSerde)> {
if let Ok(peers) = Config::path(PEERS).read_dir() {
if let Ok(peers) = peers
.map(|res| res.map(|e| e.path()))
@@ -669,13 +657,13 @@ impl PeerConfig {
.map(|p| p.to_str().unwrap_or(""))
.unwrap_or("")
.to_owned();
let c = PeerConfig::load(&id);
if c.info.platform.is_empty() {
let info = PeerConfig::load(&id).info;
if info.platform.is_empty() {
fs::remove_file(&p).ok();
}
(id, t, c)
(id, t, info)
})
.filter(|p| !p.2.info.platform.is_empty())
.filter(|p| !p.2.platform.is_empty())
.collect();
peers.sort_unstable_by(|a, b| b.1.cmp(&a.1));
return peers;

View File

@@ -7,7 +7,7 @@ use crate::{
};
#[cfg(windows)]
use std::os::windows::prelude::*;
use tokio::{fs::File, io::*};
use tokio::{fs::File, prelude::*};
pub fn read_dir(path: &PathBuf, include_hidden: bool) -> ResultType<FileDirectory> {
let mut dir = FileDirectory {

View File

@@ -6,6 +6,7 @@ pub mod rendezvous_proto;
pub use bytes;
pub use futures;
pub use protobuf;
use socket2::{Domain, Socket, Type};
use std::{
fs::File,
io::{self, BufRead},
@@ -35,7 +36,7 @@ pub type Stream = tcp::FramedStream;
#[inline]
pub async fn sleep(sec: f32) {
tokio::time::sleep(time::Duration::from_secs_f32(sec)).await;
tokio::time::delay_for(time::Duration::from_secs_f32(sec)).await;
}
#[macro_export]
@@ -60,6 +61,30 @@ pub fn timeout<T: std::future::Future>(ms: u64, future: T) -> tokio::time::Timeo
tokio::time::timeout(std::time::Duration::from_millis(ms), future)
}
fn new_socket(addr: SocketAddr, tcp: bool, reuse: bool) -> Result<Socket, std::io::Error> {
let stype = {
if tcp {
Type::stream()
} else {
Type::dgram()
}
};
let socket = match addr {
SocketAddr::V4(..) => Socket::new(Domain::ipv4(), stype, None),
SocketAddr::V6(..) => Socket::new(Domain::ipv6(), stype, None),
}?;
if reuse {
// windows has no reuse_port, but it's reuse_address
// almost equals to unix's reuse_port + reuse_address,
// though may introduce nondeterministic bahavior
#[cfg(unix)]
socket.set_reuse_port(true)?;
socket.set_reuse_address(true)?;
}
socket.bind(&addr.into())?;
Ok(socket)
}
pub type ResultType<F, E = anyhow::Error> = anyhow::Result<F, E>;
/// Certain router and firewalls scan the packet and if they
@@ -75,10 +100,10 @@ impl AddrMangle {
.duration_since(UNIX_EPOCH)
.unwrap()
.as_micros() as u32) as u128;
let ip = u32::from_le_bytes(addr_v4.ip().octets()) as u128;
let ip = u32::from_ne_bytes(addr_v4.ip().octets()) as u128;
let port = addr.port() as u128;
let v = ((ip + tm) << 49) | (tm << 17) | (port + (tm & 0xFFFF));
let bytes = v.to_le_bytes();
let bytes = v.to_ne_bytes();
let mut n_padding = 0;
for i in bytes.iter().rev() {
if i == &0u8 {
@@ -98,9 +123,9 @@ impl AddrMangle {
pub fn decode(bytes: &[u8]) -> SocketAddr {
let mut padded = [0u8; 16];
padded[..bytes.len()].copy_from_slice(&bytes);
let number = u128::from_le_bytes(padded);
let number = u128::from_ne_bytes(padded);
let tm = (number >> 17) & (u32::max_value() as u128);
let ip = (((number >> 49) - tm) as u32).to_le_bytes();
let ip = (((number >> 49) - tm) as u32).to_ne_bytes();
let port = (number & 0xFFFFFF) - (tm & 0xFFFF);
SocketAddr::V4(SocketAddrV4::new(
Ipv4Addr::new(ip[0], ip[1], ip[2], ip[3]),

View File

@@ -1,13 +1,16 @@
use crate::{bail, bytes_codec::BytesCodec, ResultType};
use bytes::{BufMut, Bytes, BytesMut};
use futures::{SinkExt, StreamExt};
use futures::SinkExt;
use protobuf::Message;
use sodiumoxide::crypto::secretbox::{self, Key, Nonce};
use std::{
io::{Error, ErrorKind},
ops::{Deref, DerefMut},
};
use tokio::net::{lookup_host, TcpListener, TcpSocket, TcpStream, ToSocketAddrs};
use tokio::{
net::{TcpListener, TcpStream, ToSocketAddrs},
stream::StreamExt,
};
use tokio_util::codec::Framed;
pub struct FramedStream(Framed<TcpStream, BytesCodec>, Option<(Key, u64, u64)>);
@@ -26,37 +29,25 @@ impl DerefMut for FramedStream {
}
}
fn new_socket(addr: std::net::SocketAddr, reuse: bool) -> Result<TcpSocket, std::io::Error> {
let socket = match addr {
std::net::SocketAddr::V4(..) => TcpSocket::new_v4()?,
std::net::SocketAddr::V6(..) => TcpSocket::new_v6()?,
};
if reuse {
// windows has no reuse_port, but it's reuse_address
// almost equals to unix's reuse_port + reuse_address,
// though may introduce nondeterministic bahavior
#[cfg(unix)]
socket.set_reuseport(true)?;
socket.set_reuseaddr(true)?;
}
socket.bind(addr)?;
Ok(socket)
}
impl FramedStream {
pub async fn new<T: ToSocketAddrs, T2: ToSocketAddrs>(
remote_addr: T,
local_addr: T2,
ms_timeout: u64,
) -> ResultType<Self> {
for local_addr in lookup_host(&local_addr).await? {
for remote_addr in lookup_host(&remote_addr).await? {
let stream = super::timeout(
for local_addr in local_addr.to_socket_addrs().await? {
for remote_addr in remote_addr.to_socket_addrs().await? {
if let Ok(stream) = super::timeout(
ms_timeout,
new_socket(local_addr, true)?.connect(remote_addr),
TcpStream::connect_std(
super::new_socket(local_addr, true, true)?.into_tcp_stream(),
&remote_addr,
),
)
.await??;
return Ok(Self(Framed::new(stream, BytesCodec::new()), None));
.await?
{
return Ok(Self(Framed::new(stream, BytesCodec::new()), None));
}
}
}
bail!("could not resolve to any address");
@@ -133,21 +124,22 @@ impl FramedStream {
fn get_nonce(seqnum: u64) -> Nonce {
let mut nonce = Nonce([0u8; secretbox::NONCEBYTES]);
nonce.0[..std::mem::size_of_val(&seqnum)].copy_from_slice(&seqnum.to_le_bytes());
nonce.0[..std::mem::size_of_val(&seqnum)].copy_from_slice(&seqnum.to_ne_bytes());
nonce
}
}
const DEFAULT_BACKLOG: u32 = 128;
const DEFAULT_BACKLOG: i32 = 128;
#[allow(clippy::never_loop)]
pub async fn new_listener<T: ToSocketAddrs>(addr: T, reuse: bool) -> ResultType<TcpListener> {
if !reuse {
Ok(TcpListener::bind(addr).await?)
} else {
for addr in lookup_host(&addr).await? {
let socket = new_socket(addr, true)?;
return Ok(socket.listen(DEFAULT_BACKLOG)?);
for addr in addr.to_socket_addrs().await? {
let socket = super::new_socket(addr, true, true)?;
socket.listen(DEFAULT_BACKLOG)?;
return Ok(TcpListener::from_std(socket.into_tcp_listener())?);
}
bail!("could not resolve to any address");
}

View File

@@ -1,14 +1,13 @@
use crate::{bail, ResultType};
use bytes::BytesMut;
use futures::{SinkExt, StreamExt};
use futures::SinkExt;
use protobuf::Message;
use socket2::{Domain, Socket, Type};
use std::{
io::Error,
net::SocketAddr,
ops::{Deref, DerefMut},
};
use tokio::{net::ToSocketAddrs, net::UdpSocket};
use tokio::{net::ToSocketAddrs, net::UdpSocket, stream::StreamExt};
use tokio_util::{codec::BytesCodec, udp::UdpFramed};
pub struct FramedSocket(UdpFramed<BytesCodec>);
@@ -21,23 +20,6 @@ impl Deref for FramedSocket {
}
}
fn new_socket(addr: SocketAddr, reuse: bool) -> Result<Socket, std::io::Error> {
let socket = match addr {
SocketAddr::V4(..) => Socket::new(Domain::ipv4(), Type::dgram(), None),
SocketAddr::V6(..) => Socket::new(Domain::ipv6(), Type::dgram(), None),
}?;
if reuse {
// windows has no reuse_port, but it's reuse_address
// almost equals to unix's reuse_port + reuse_address,
// though may introduce nondeterministic bahavior
#[cfg(unix)]
socket.set_reuse_port(true)?;
socket.set_reuse_address(true)?;
}
socket.bind(&addr.into())?;
Ok(socket)
}
impl DerefMut for FramedSocket {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
@@ -51,10 +33,10 @@ impl FramedSocket {
}
#[allow(clippy::never_loop)]
pub async fn new_reuse<T: std::net::ToSocketAddrs>(addr: T) -> ResultType<Self> {
for addr in addr.to_socket_addrs()? {
pub async fn new_reuse<T: ToSocketAddrs>(addr: T) -> ResultType<Self> {
for addr in addr.to_socket_addrs().await? {
return Ok(Self(UdpFramed::new(
UdpSocket::from_std(new_socket(addr, true)?.into_udp_socket())?,
UdpSocket::from_std(super::new_socket(addr, false, true)?.into_udp_socket())?,
BytesCodec::new(),
)));
}

2
libs/magnum-opus/.gitignore vendored Normal file
View File

@@ -0,0 +1,2 @@
target
Cargo.lock

View File

@@ -0,0 +1,18 @@
[package]
name = "magnum-opus"
version = "0.3.4"
authors = ["Tad Hardesty <tad@platymuus.com>", "Sergey Duck <sergeypechnikov326@gmail.com>"]
edition = "2018"
description = "Safe Rust bindings for libopus"
readme = "README.md"
license = "MIT/Apache-2.0"
keywords = ["opus", "codec", "voice", "sound", "audio"]
categories = ["api-bindings", "encoding", "compression",
"multimedia::audio", "multimedia::encoding"]
repository = "https://github.com/DuckerMan/magnum-opus"
documentation = "https://docs.rs/magnum-opus"
[build-dependencies]
target_build_utils = "0.3"
bindgen = "0.53"

View File

@@ -0,0 +1,201 @@
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 [yyyy] [name of copyright owner]
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.

View File

@@ -0,0 +1,19 @@
Copyright (c) 2016 Tad Hardesty
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.

View File

@@ -0,0 +1,22 @@
# magnum-opus [![](https://meritbadge.herokuapp.com/magnum-opus)](https://crates.io/crates/magnum-opus) [![](https://img.shields.io/badge/docs-online-2020ff.svg)](https://docs.rs/magnum-opus)
### This is the fork of @SpaceManiac repo, which now is abandoned
Safe Rust bindings for libopus. The rustdoc (available through `cargo doc`)
includes brief descriptions for methods, and detailed API information can be
found at the [libopus documentation](https://opus-codec.org/docs/opus_api-1.1.2/).
## License
Licensed under either of
* Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0)
* MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT)
at your option.
### Contribution
Unless you explicitly state otherwise, any contribution intentionally submitted
for inclusion in the work by you, as defined in the Apache-2.0 license, shall be
dual licensed as above, without any additional terms or conditions.

89
libs/magnum-opus/build.rs Normal file
View File

@@ -0,0 +1,89 @@
use std::{
env,
path::{Path, PathBuf},
};
fn find_package(name: &str) -> Vec<PathBuf> {
let vcpkg_root = std::env::var("VCPKG_ROOT").unwrap();
let mut path: PathBuf = vcpkg_root.into();
let target_os = std::env::var("CARGO_CFG_TARGET_OS").unwrap();
let mut target_arch = std::env::var("CARGO_CFG_TARGET_ARCH").unwrap();
if target_arch == "x86_64" {
target_arch = "x64".to_owned();
} else if target_arch == "aarch64" {
target_arch = "arm64".to_owned();
} else {
target_arch = "arm".to_owned();
}
let target = if target_os == "macos" {
"x64-osx".to_owned()
} else if target_os == "windows" {
"x64-windows-static".to_owned()
} else if target_os == "android" {
format!("{}-android-static", target_arch)
} else {
"x64-linux".to_owned()
};
println!("cargo:info={}", target);
path.push("installed");
path.push(target);
println!(
"{}",
format!("cargo:rustc-link-lib={}", name.trim_start_matches("lib"))
);
println!(
"{}",
format!(
"cargo:rustc-link-search={}",
path.join("lib").to_str().unwrap()
)
);
let include = path.join("include");
println!("{}", format!("cargo:include={}", include.to_str().unwrap()));
vec![include]
}
fn generate_bindings(ffi_header: &Path, include_paths: &[PathBuf], ffi_rs: &Path) {
#[derive(Debug)]
struct ParseCallbacks;
impl bindgen::callbacks::ParseCallbacks for ParseCallbacks {
fn int_macro(&self, name: &str, _value: i64) -> Option<bindgen::callbacks::IntKind> {
if name.starts_with("OPUS") {
Some(bindgen::callbacks::IntKind::Int)
} else {
None
}
}
}
let mut b = bindgen::Builder::default()
.header(ffi_header.to_str().unwrap())
.parse_callbacks(Box::new(ParseCallbacks))
.generate_comments(false);
for dir in include_paths {
b = b.clang_arg(format!("-I{}", dir.display()));
}
b.generate().unwrap().write_to_file(ffi_rs).unwrap();
}
fn gen_opus() {
let includes = find_package("opus");
let src_dir = env::var_os("CARGO_MANIFEST_DIR").unwrap();
let src_dir = Path::new(&src_dir);
let out_dir = env::var_os("OUT_DIR").unwrap();
let out_dir = Path::new(&out_dir);
let ffi_header = src_dir.join("opus_ffi.h");
println!("rerun-if-changed={}", ffi_header.display());
for dir in &includes {
println!("rerun-if-changed={}", dir.display());
}
let ffi_rs = out_dir.join("opus_ffi.rs");
generate_bindings(&ffi_header, &includes, &ffi_rs);
}
fn main() {
gen_opus()
}

View File

@@ -0,0 +1 @@
#include <opus/opus_multistream.h>

843
libs/magnum-opus/src/lib.rs Normal file
View File

@@ -0,0 +1,843 @@
// Copyright 2016 Tad Hardesty
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! High-level bindings for libopus.
//!
//! Only brief descriptions are included here. For detailed information, consult
//! the [libopus documentation](https://opus-codec.org/docs/opus_api-1.1.2/).
#![warn(missing_docs)]
mod opus_ffi;
use opus_ffi as ffi;
use std::ffi::CStr;
use std::marker::PhantomData;
use std::os::raw::c_int;
// ============================================================================
// Constants
// Generic CTLs
const OPUS_RESET_STATE: c_int = 4028; // void
const OPUS_GET_FINAL_RANGE: c_int = 4031; // out *u32
const OPUS_GET_BANDWIDTH: c_int = 4009; // out *i32
const OPUS_GET_SAMPLE_RATE: c_int = 4029; // out *i32
// Encoder CTLs
const OPUS_SET_BITRATE: c_int = 4002; // in i32
const OPUS_GET_BITRATE: c_int = 4003; // out *i32
const OPUS_SET_VBR: c_int = 4006; // in i32
const OPUS_GET_VBR: c_int = 4007; // out *i32
const OPUS_SET_VBR_CONSTRAINT: c_int = 4020; // in i32
const OPUS_GET_VBR_CONSTRAINT: c_int = 4021; // out *i32
const OPUS_SET_INBAND_FEC: c_int = 4012; // in i32
const OPUS_GET_INBAND_FEC: c_int = 4013; // out *i32
const OPUS_SET_PACKET_LOSS_PERC: c_int = 4014; // in i32
const OPUS_GET_PACKET_LOSS_PERC: c_int = 4015; // out *i32
const OPUS_GET_LOOKAHEAD: c_int = 4027; // out *i32
// Decoder CTLs
const OPUS_SET_GAIN: c_int = 4034; // in i32
const OPUS_GET_GAIN: c_int = 4045; // out *i32
const OPUS_GET_LAST_PACKET_DURATION: c_int = 4039; // out *i32
const OPUS_GET_PITCH: c_int = 4033; // out *i32
// Bitrate
const OPUS_AUTO: c_int = -1000;
const OPUS_BITRATE_MAX: c_int = -1;
/// The possible applications for the codec.
#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)]
pub enum Application {
/// Best for most VoIP/videoconference applications where listening quality
/// and intelligibility matter most.
Voip = 2048,
/// Best for broadcast/high-fidelity application where the decoded audio
/// should be as close as possible to the input.
Audio = 2049,
/// Only use when lowest-achievable latency is what matters most.
LowDelay = 2051,
}
/// The available channel setings.
#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)]
pub enum Channels {
/// One channel.
Mono = 1,
/// Two channels, left and right.
Stereo = 2,
}
/// The available bandwidth level settings.
#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)]
pub enum Bandwidth {
/// Auto/default setting.
Auto = -1000,
/// 4kHz bandpass.
Narrowband = 1101,
/// 6kHz bandpass.
Mediumband = 1102,
/// 8kHz bandpass.
Wideband = 1103,
/// 12kHz bandpass.
Superwideband = 1104,
/// 20kHz bandpass.
Fullband = 1105,
}
impl Bandwidth {
fn from_int(value: i32) -> Option<Bandwidth> {
Some(match value {
-1000 => Bandwidth::Auto,
1101 => Bandwidth::Narrowband,
1102 => Bandwidth::Mediumband,
1103 => Bandwidth::Wideband,
1104 => Bandwidth::Superwideband,
1105 => Bandwidth::Fullband,
_ => return None,
})
}
fn decode(value: i32, what: &'static str) -> Result<Bandwidth> {
match Bandwidth::from_int(value) {
Some(bandwidth) => Ok(bandwidth),
None => Err(Error::bad_arg(what)),
}
}
}
/// Possible error codes.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
pub enum ErrorCode {
/// One or more invalid/out of range arguments.
BadArg = -1,
/// Not enough bytes allocated in the buffer.
BufferTooSmall = -2,
/// An internal error was detected.
InternalError = -3,
/// The compressed data passed is corrupted.
InvalidPacket = -4,
/// Invalid/unsupported request number.
Unimplemented = -5,
/// An encoder or decoder structure is invalid or already freed.
InvalidState = -6,
/// Memory allocation has failed.
AllocFail = -7,
/// An unknown failure.
Unknown = -8,
}
impl ErrorCode {
fn from_int(value: c_int) -> ErrorCode {
use ErrorCode::*;
match value {
ffi::OPUS_BAD_ARG => BadArg,
ffi::OPUS_BUFFER_TOO_SMALL => BufferTooSmall,
ffi::OPUS_INTERNAL_ERROR => InternalError,
ffi::OPUS_INVALID_PACKET => InvalidPacket,
ffi::OPUS_UNIMPLEMENTED => Unimplemented,
ffi::OPUS_INVALID_STATE => InvalidState,
ffi::OPUS_ALLOC_FAIL => AllocFail,
_ => Unknown,
}
}
/// Get a human-readable error string for this error code.
pub fn description(self) -> &'static str {
// should always be ASCII and non-null for any input
unsafe { CStr::from_ptr(ffi::opus_strerror(self as c_int)) }.to_str().unwrap()
}
}
/// Possible bitrates.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
pub enum Bitrate {
/// Explicit bitrate choice (in bits/second).
Bits(i32),
/// Maximum bitrate allowed (up to maximum number of bytes for the packet).
Max,
/// Default bitrate decided by the encoder (not recommended).
Auto,
}
/// Get the libopus version string.
///
/// Applications may look for the substring "-fixed" in the version string to
/// determine whether they have a fixed-point or floating-point build at
/// runtime.
pub fn version() -> &'static str {
// verison string should always be ASCII
unsafe { CStr::from_ptr(ffi::opus_get_version_string()) }.to_str().unwrap()
}
macro_rules! ffi {
($f:ident $(, $rest:expr)*) => {
match unsafe { ffi::$f($($rest),*) } {
code if code < 0 => return Err(Error::from_code(stringify!($f), code)),
code => code,
}
}
}
macro_rules! ctl {
($f:ident, $this:ident, $ctl:ident, $($rest:expr),*) => {
match unsafe { ffi::$f($this.ptr, $ctl, $($rest),*) } {
code if code < 0 => return Err(Error::from_code(
concat!(stringify!($f), "(", stringify!($ctl), ")"),
code,
)),
_ => (),
}
}
}
// ============================================================================
// Encoder
macro_rules! enc_ctl {
($this:ident, $ctl:ident $(, $rest:expr)*) => {
ctl!(opus_encoder_ctl, $this, $ctl, $($rest),*)
}
}
/// An Opus encoder with associated state.
#[derive(Debug)]
pub struct Encoder {
ptr: *mut ffi::OpusEncoder,
channels: Channels,
}
impl Encoder {
/// Create and initialize an encoder.
pub fn new(sample_rate: u32, channels: Channels, mode: Application) -> Result<Encoder> {
let mut error = 0;
let ptr = unsafe { ffi::opus_encoder_create(
sample_rate as i32,
channels as c_int,
mode as c_int,
&mut error) };
if error != ffi::OPUS_OK || ptr.is_null() {
Err(Error::from_code("opus_encoder_create", error))
} else {
Ok(Encoder { ptr: ptr, channels: channels })
}
}
/// Encode an Opus frame.
pub fn encode(&mut self, input: &[i16], output: &mut [u8]) -> Result<usize> {
let len = ffi!(opus_encode, self.ptr,
input.as_ptr(), len(input) / self.channels as c_int,
output.as_mut_ptr(), len(output));
Ok(len as usize)
}
/// Encode an Opus frame from floating point input.
pub fn encode_float(&mut self, input: &[f32], output: &mut [u8]) -> Result<usize> {
let len = ffi!(opus_encode_float, self.ptr,
input.as_ptr(), len(input) / self.channels as c_int,
output.as_mut_ptr(), len(output));
Ok(len as usize)
}
/// Encode an Opus frame to a new buffer.
pub fn encode_vec(&mut self, input: &[i16], max_size: usize) -> Result<Vec<u8>> {
let mut output: Vec<u8> = vec![0; max_size];
let result = self.encode(input, output.as_mut_slice())?;
output.truncate(result);
Ok(output)
}
/// Encode an Opus frame from floating point input to a new buffer.
pub fn encode_vec_float(&mut self, input: &[f32], max_size: usize) -> Result<Vec<u8>> {
let mut output: Vec<u8> = vec![0; max_size];
let result = self.encode_float(input, output.as_mut_slice())?;
output.truncate(result);
Ok(output)
}
// ------------
// Generic CTLs
/// Reset the codec state to be equivalent to a freshly initialized state.
pub fn reset_state(&mut self) -> Result<()> {
enc_ctl!(self, OPUS_RESET_STATE);
Ok(())
}
/// Get the final range of the codec's entropy coder.
pub fn get_final_range(&mut self) -> Result<u32> {
let mut value: u32 = 0;
enc_ctl!(self, OPUS_GET_FINAL_RANGE, &mut value);
Ok(value)
}
/// Get the encoder's configured bandpass.
pub fn get_bandwidth(&mut self) -> Result<Bandwidth> {
let mut value: i32 = 0;
enc_ctl!(self, OPUS_GET_BANDWIDTH, &mut value);
Bandwidth::decode(value, "opus_encoder_ctl(OPUS_GET_BANDWIDTH)")
}
/// Get the samping rate the encoder was intialized with.
pub fn get_sample_rate(&mut self) -> Result<u32> {
let mut value: i32 = 0;
enc_ctl!(self, OPUS_GET_SAMPLE_RATE, &mut value);
Ok(value as u32)
}
// ------------
// Encoder CTLs
/// Set the encoder's bitrate.
pub fn set_bitrate(&mut self, value: Bitrate) -> Result<()> {
let value: i32 = match value {
Bitrate::Auto => OPUS_AUTO,
Bitrate::Max => OPUS_BITRATE_MAX,
Bitrate::Bits(b) => b,
};
enc_ctl!(self, OPUS_SET_BITRATE, value);
Ok(())
}
/// Get the encoder's bitrate.
pub fn get_bitrate(&mut self) -> Result<Bitrate> {
let mut value: i32 = 0;
enc_ctl!(self, OPUS_GET_BITRATE, &mut value);
Ok(match value {
OPUS_AUTO => Bitrate::Auto,
OPUS_BITRATE_MAX => Bitrate::Max,
_ => Bitrate::Bits(value),
})
}
/// Enable or disable variable bitrate.
pub fn set_vbr(&mut self, vbr: bool) -> Result<()> {
let value: i32 = if vbr { 1 } else { 0 };
enc_ctl!(self, OPUS_SET_VBR, value);
Ok(())
}
/// Determine if variable bitrate is enabled.
pub fn get_vbr(&mut self) -> Result<bool> {
let mut value: i32 = 0;
enc_ctl!(self, OPUS_GET_VBR, &mut value);
Ok(value != 0)
}
/// Enable or disable constrained VBR.
pub fn set_vbr_constraint(&mut self, vbr: bool) -> Result<()> {
let value: i32 = if vbr { 1 } else { 0 };
enc_ctl!(self, OPUS_SET_VBR_CONSTRAINT, value);
Ok(())
}
/// Determine if constrained VBR is enabled.
pub fn get_vbr_constraint(&mut self) -> Result<bool> {
let mut value: i32 = 0;
enc_ctl!(self, OPUS_GET_VBR_CONSTRAINT, &mut value);
Ok(value != 0)
}
/// Configures the encoder's use of inband forward error correction (FEC).
pub fn set_inband_fec(&mut self, value: bool) -> Result<()> {
let value: i32 = if value { 1 } else { 0 };
enc_ctl!(self, OPUS_SET_INBAND_FEC, value);
Ok(())
}
/// Gets encoder's configured use of inband forward error correction.
pub fn get_inband_fec(&mut self) -> Result<bool> {
let mut value: i32 = 0;
enc_ctl!(self, OPUS_GET_INBAND_FEC, &mut value);
Ok(value != 0)
}
/// Sets the encoder's expected packet loss percentage.
pub fn set_packet_loss_perc(&mut self, value: i32) -> Result<()> {
enc_ctl!(self, OPUS_SET_PACKET_LOSS_PERC, value);
Ok(())
}
/// Gets the encoder's expected packet loss percentage.
pub fn get_packet_loss_perc(&mut self) -> Result<i32> {
let mut value: i32 = 0;
enc_ctl!(self, OPUS_GET_PACKET_LOSS_PERC, &mut value);
Ok(value)
}
/// Gets the total samples of delay added by the entire codec.
pub fn get_lookahead(&mut self) -> Result<i32> {
let mut value: i32 = 0;
enc_ctl!(self, OPUS_GET_LOOKAHEAD, &mut value);
Ok(value)
}
// TODO: Encoder-specific CTLs
}
impl Drop for Encoder {
fn drop(&mut self) {
unsafe { ffi::opus_encoder_destroy(self.ptr) }
}
}
// "A single codec state may only be accessed from a single thread at
// a time and any required locking must be performed by the caller. Separate
// streams must be decoded with separate decoder states and can be decoded
// in parallel unless the library was compiled with NONTHREADSAFE_PSEUDOSTACK
// defined."
//
// In other words, opus states may be moved between threads at will. A special
// compilation mode intended for embedded platforms forbids multithreaded use
// of the library as a whole rather than on a per-state basis, but the opus-sys
// crate does not use this mode.
unsafe impl Send for Encoder {}
// ============================================================================
// Decoder
macro_rules! dec_ctl {
($this:ident, $ctl:ident $(, $rest:expr)*) => {
ctl!(opus_decoder_ctl, $this, $ctl, $($rest),*)
}
}
/// An Opus decoder with associated state.
#[derive(Debug)]
pub struct Decoder {
ptr: *mut ffi::OpusDecoder,
channels: Channels,
}
impl Decoder {
/// Create and initialize a decoder.
pub fn new(sample_rate: u32, channels: Channels) -> Result<Decoder> {
let mut error = 0;
let ptr = unsafe { ffi::opus_decoder_create(
sample_rate as i32,
channels as c_int,
&mut error) };
if error != ffi::OPUS_OK || ptr.is_null() {
Err(Error::from_code("opus_decoder_create", error))
} else {
Ok(Decoder { ptr: ptr, channels: channels })
}
}
/// Decode an Opus packet.
pub fn decode(&mut self, input: &[u8], output: &mut [i16], fec: bool) -> Result<usize> {
let ptr = match input.len() {
0 => std::ptr::null(),
_ => input.as_ptr(),
};
let len = ffi!(opus_decode, self.ptr,
ptr, len(input),
output.as_mut_ptr(), len(output) / self.channels as c_int,
fec as c_int);
Ok(len as usize)
}
/// Decode an Opus packet with floating point output.
pub fn decode_float(&mut self, input: &[u8], output: &mut [f32], fec: bool) -> Result<usize> {
let ptr = match input.len() {
0 => std::ptr::null(),
_ => input.as_ptr(),
};
let len = ffi!(opus_decode_float, self.ptr,
ptr, len(input),
output.as_mut_ptr(), len(output) / self.channels as c_int,
fec as c_int);
Ok(len as usize)
}
/// Get the number of samples of an Opus packet.
pub fn get_nb_samples(&self, packet: &[u8]) -> Result<usize> {
let len = ffi!(opus_decoder_get_nb_samples, self.ptr,
packet.as_ptr(), packet.len() as i32);
Ok(len as usize)
}
// ------------
// Generic CTLs
/// Reset the codec state to be equivalent to a freshly initialized state.
pub fn reset_state(&mut self) -> Result<()> {
dec_ctl!(self, OPUS_RESET_STATE);
Ok(())
}
/// Get the final range of the codec's entropy coder.
pub fn get_final_range(&mut self) -> Result<u32> {
let mut value: u32 = 0;
dec_ctl!(self, OPUS_GET_FINAL_RANGE, &mut value);
Ok(value)
}
/// Get the decoder's last bandpass.
pub fn get_bandwidth(&mut self) -> Result<Bandwidth> {
let mut value: i32 = 0;
dec_ctl!(self, OPUS_GET_BANDWIDTH, &mut value);
Bandwidth::decode(value, "opus_decoder_ctl(OPUS_GET_BANDWIDTH)")
}
/// Get the samping rate the decoder was intialized with.
pub fn get_sample_rate(&mut self) -> Result<u32> {
let mut value: i32 = 0;
dec_ctl!(self, OPUS_GET_SAMPLE_RATE, &mut value);
Ok(value as u32)
}
// ------------
// Decoder CTLs
/// Configures decoder gain adjustment.
///
/// Scales the decoded output by a factor specified in Q8 dB units. This has
/// a maximum range of -32768 to 32768 inclusive, and returns `BadArg`
/// otherwise. The default is zero indicating no adjustment. This setting
/// survives decoder reset.
///
/// `gain = pow(10, x / (20.0 * 256))`
pub fn set_gain(&mut self, gain: i32) -> Result<()> {
dec_ctl!(self, OPUS_SET_GAIN, gain);
Ok(())
}
/// Gets the decoder's configured gain adjustment.
pub fn get_gain(&mut self) -> Result<i32> {
let mut value: i32 = 0;
dec_ctl!(self, OPUS_GET_GAIN, &mut value);
Ok(value)
}
/// Gets the duration (in samples) of the last packet successfully decoded
/// or concealed.
pub fn get_last_packet_duration(&mut self) -> Result<u32> {
let mut value: i32 = 0;
dec_ctl!(self, OPUS_GET_LAST_PACKET_DURATION, &mut value);
Ok(value as u32)
}
/// Gets the pitch of the last decoded frame, if available.
///
/// This can be used for any post-processing algorithm requiring the use of
/// pitch, e.g. time stretching/shortening. If the last frame was not
/// voiced, or if the pitch was not coded in the frame, then zero is
/// returned.
pub fn get_pitch(&mut self) -> Result<i32> {
let mut value: i32 = 0;
dec_ctl!(self, OPUS_GET_PITCH, &mut value);
Ok(value)
}
}
impl Drop for Decoder {
fn drop(&mut self) {
unsafe { ffi::opus_decoder_destroy(self.ptr) }
}
}
// See `unsafe impl Send for Encoder`.
unsafe impl Send for Decoder {}
// ============================================================================
// Packet Analysis
/// Analyze raw Opus packets.
pub mod packet {
use super::*;
use super::ffi;
use std::{ptr, slice};
/// Get the bandwidth of an Opus packet.
pub fn get_bandwidth(packet: &[u8]) -> Result<Bandwidth> {
if packet.len() < 1 {
return Err(Error::bad_arg("opus_packet_get_bandwidth"));
}
let bandwidth = ffi!(opus_packet_get_bandwidth, packet.as_ptr());
Bandwidth::decode(bandwidth, "opus_packet_get_bandwidth")
}
/// Get the number of channels from an Opus packet.
pub fn get_nb_channels(packet: &[u8]) -> Result<Channels> {
if packet.len() < 1 {
return Err(Error::bad_arg("opus_packet_get_nb_channels"));
}
let channels = ffi!(opus_packet_get_nb_channels, packet.as_ptr());
match channels {
1 => Ok(Channels::Mono),
2 => Ok(Channels::Stereo),
_ => Err(Error::bad_arg("opus_packet_get_nb_channels")),
}
}
/// Get the number of frames in an Opus packet.
pub fn get_nb_frames(packet: &[u8]) -> Result<usize> {
let frames = ffi!(opus_packet_get_nb_frames, packet.as_ptr(), len(packet));
Ok(frames as usize)
}
/// Get the number of samples of an Opus packet.
pub fn get_nb_samples(packet: &[u8], sample_rate: u32) -> Result<usize> {
let frames = ffi!(opus_packet_get_nb_samples,
packet.as_ptr(), len(packet),
sample_rate as c_int);
Ok(frames as usize)
}
/// Get the number of samples per frame from an Opus packet.
pub fn get_samples_per_frame(packet: &[u8], sample_rate: u32) -> Result<usize> {
if packet.len() < 1 {
return Err(Error::bad_arg("opus_packet_get_samples_per_frame"))
}
let samples = ffi!(opus_packet_get_samples_per_frame,
packet.as_ptr(), sample_rate as c_int);
Ok(samples as usize)
}
/// Parse an Opus packet into one or more frames.
pub fn parse(packet: &[u8]) -> Result<Packet> {
let mut toc: u8 = 0;
let mut frames = [ptr::null(); 48];
let mut sizes = [0i16; 48];
let mut payload_offset: i32 = 0;
let num_frames = ffi!(opus_packet_parse,
packet.as_ptr(), len(packet),
&mut toc, frames.as_mut_ptr(),
sizes.as_mut_ptr(), &mut payload_offset);
let mut frames_vec = Vec::with_capacity(num_frames as usize);
for i in 0..num_frames as usize {
frames_vec.push(unsafe { slice::from_raw_parts(frames[i], sizes[i] as usize) });
}
Ok(Packet {
toc: toc,
frames: frames_vec,
payload_offset: payload_offset as usize,
})
}
/// A parsed Opus packet, retuned from `parse`.
#[derive(Debug)]
pub struct Packet<'a> {
/// The TOC byte of the packet.
pub toc: u8,
/// The frames contained in the packet.
pub frames: Vec<&'a [u8]>,
/// The offset into the packet at which the payload is located.
pub payload_offset: usize,
}
/// Pad a given Opus packet to a larger size.
///
/// The packet will be extended from the first `prev_len` bytes of the
/// buffer into the rest of the available space.
pub fn pad(packet: &mut [u8], prev_len: usize) -> Result<usize> {
let result = ffi!(opus_packet_pad, packet.as_mut_ptr(),
check_len(prev_len), len(packet));
Ok(result as usize)
}
/// Remove all padding from a given Opus packet and rewrite the TOC sequence
/// to minimize space usage.
pub fn unpad(packet: &mut [u8]) -> Result<usize> {
let result = ffi!(opus_packet_unpad, packet.as_mut_ptr(), len(packet));
Ok(result as usize)
}
}
// ============================================================================
// Float Soft Clipping
/// Soft-clipping to bring a float signal within the [-1,1] range.
#[derive(Debug)]
pub struct SoftClip {
channels: Channels,
memory: [f32; 2],
}
impl SoftClip {
/// Initialize a new soft-clipping state.
pub fn new(channels: Channels) -> SoftClip {
SoftClip { channels: channels, memory: [0.0; 2] }
}
/// Apply soft-clipping to a float signal.
pub fn apply(&mut self, signal: &mut [f32]) {
unsafe { ffi::opus_pcm_soft_clip(
signal.as_mut_ptr(),
len(signal) / self.channels as c_int,
self.channels as c_int,
self.memory.as_mut_ptr()) };
}
}
// ============================================================================
// Repacketizer
/// A repacketizer used to merge together or split apart multiple Opus packets.
#[derive(Debug)]
pub struct Repacketizer {
ptr: *mut ffi::OpusRepacketizer,
}
impl Repacketizer {
/// Create and initialize a repacketizer.
pub fn new() -> Result<Repacketizer> {
let ptr = unsafe { ffi::opus_repacketizer_create() };
if ptr.is_null() {
Err(Error::from_code("opus_repacketizer_create", ffi::OPUS_ALLOC_FAIL))
} else {
Ok(Repacketizer { ptr: ptr })
}
}
/// Shortcut to combine several smaller packets into one larger one.
pub fn combine(&mut self, input: &[&[u8]], output: &mut [u8]) -> Result<usize> {
let mut state = self.begin();
for &packet in input {
state.cat(packet)?;
}
state.out(output)
}
/// Begin using the repacketizer.
pub fn begin<'rp, 'buf>(&'rp mut self) -> RepacketizerState<'rp, 'buf> {
unsafe { ffi::opus_repacketizer_init(self.ptr); }
RepacketizerState { rp: self, phantom: PhantomData }
}
}
impl Drop for Repacketizer {
fn drop(&mut self) {
unsafe { ffi::opus_repacketizer_destroy(self.ptr) }
}
}
// See `unsafe impl Send for Encoder`.
unsafe impl Send for Repacketizer {}
// To understand why these lifetime bounds are needed, imagine that the
// repacketizer keeps an internal Vec<&'buf [u8]>, which is added to by cat()
// and accessed by get_nb_frames(), out(), and out_range(). To prove that these
// lifetime bounds are correct, a dummy implementation with the same signatures
// but a real Vec<&'buf [u8]> rather than unsafe blocks may be substituted.
/// An in-progress repacketization.
#[derive(Debug)]
pub struct RepacketizerState<'rp, 'buf> {
rp: &'rp mut Repacketizer,
phantom: PhantomData<&'buf [u8]>,
}
impl<'rp, 'buf> RepacketizerState<'rp, 'buf> {
/// Add a packet to the current repacketizer state.
pub fn cat(&mut self, packet: &'buf [u8]) -> Result<()> {
ffi!(opus_repacketizer_cat, self.rp.ptr,
packet.as_ptr(), len(packet));
Ok(())
}
/// Add a packet to the current repacketizer state, moving it.
#[inline]
pub fn cat_move<'b2>(self, packet: &'b2 [u8]) -> Result<RepacketizerState<'rp, 'b2>> where 'buf: 'b2 {
let mut shorter = self;
shorter.cat(packet)?;
Ok(shorter)
}
/// Get the total number of frames contained in packet data submitted so
/// far via `cat`.
pub fn get_nb_frames(&mut self) -> usize {
unsafe { ffi::opus_repacketizer_get_nb_frames(self.rp.ptr) as usize }
}
/// Construct a new packet from data previously submitted via `cat`.
///
/// All previously submitted frames are used.
pub fn out(&mut self, buffer: &mut [u8]) -> Result<usize> {
let result = ffi!(opus_repacketizer_out, self.rp.ptr,
buffer.as_mut_ptr(), len(buffer));
Ok(result as usize)
}
/// Construct a new packet from data previously submitted via `cat`, with
/// a manually specified subrange.
///
/// The `end` index should not exceed the value of `get_nb_frames()`.
pub fn out_range(&mut self, begin: usize, end: usize, buffer: &mut [u8]) -> Result<usize> {
let result = ffi!(opus_repacketizer_out_range, self.rp.ptr,
check_len(begin), check_len(end),
buffer.as_mut_ptr(), len(buffer));
Ok(result as usize)
}
}
// ============================================================================
// TODO: Multistream API
// ============================================================================
// Error Handling
/// Opus error Result alias.
pub type Result<T> = std::result::Result<T, Error>;
/// An error generated by the Opus library.
#[derive(Debug)]
pub struct Error {
function: &'static str,
code: ErrorCode,
}
impl Error {
fn bad_arg(what: &'static str) -> Error {
Error { function: what, code: ErrorCode::BadArg }
}
fn from_code(what: &'static str, code: c_int) -> Error {
Error { function: what, code: ErrorCode::from_int(code) }
}
/// Get the name of the Opus function from which the error originated.
#[inline]
pub fn function(&self) -> &'static str { self.function }
/// Get a textual description of the error provided by Opus.
#[inline]
pub fn description(&self) -> &'static str { self.code.description() }
/// Get the Opus error code of the error.
#[inline]
pub fn code(&self) -> ErrorCode { self.code }
}
impl std::fmt::Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "{}: {}", self.function, self.description())
}
}
impl std::error::Error for Error {
fn description(&self) -> &str {
self.code.description()
}
}
fn check_len(val: usize) -> c_int {
let len = val as c_int;
if len as usize != val {
panic!("length out of range: {}", val);
}
len
}
#[inline]
fn len<T>(slice: &[T]) -> c_int {
check_len(slice.len())
}

View File

@@ -0,0 +1,6 @@
#![allow(non_upper_case_globals)]
#![allow(non_camel_case_types)]
#![allow(non_snake_case)]
#![allow(dead_code)]
include!(concat!(env!("OUT_DIR"), "/opus_ffi.rs"));

View File

@@ -0,0 +1,10 @@
extern crate opus;
fn main() {
let mut rp = opus::Repacketizer::new().unwrap();
let mut wip = rp.begin().cat_move(
&[1, 2, 3]
//~^ ERROR borrowed value does not live long enough
).unwrap();
wip.out(&mut []);
}

View File

@@ -0,0 +1,13 @@
//! Test that supplying empty packets does forward error correction.
extern crate magnum_opus;
use magnum_opus::*;
#[test]
fn blah() {
let mut magnum_opus = Decoder::new(48000, Channels::Mono).unwrap();
let mut output = vec![0i16; 5760];
let size = magnum_opus.decode(&[], &mut output[..], true).unwrap();
assert_eq!(size, 5760);
}

View File

@@ -0,0 +1,29 @@
// Based on libmagnum_opus/tests/test_magnum_opus_padding.c
/* Check for overflow in reading the padding length.
* http://lists.xiph.org/pipermail/magnum_opus/2012-November/001834.html
*/
extern crate magnum_opus;
#[test]
fn test_overflow() {
const PACKETSIZE: usize = 16909318;
const CHANNELS: magnum_opus::Channels = magnum_opus::Channels::Stereo;
const FRAMESIZE: usize = 5760;
let mut input = vec![0xff; PACKETSIZE];
let mut output = vec![0i16; FRAMESIZE * 2];
input[0] = 0xff;
input[1] = 0x41;
*input.last_mut().unwrap() = 0x0b;
let mut decoder = magnum_opus::Decoder::new(48000, CHANNELS).unwrap();
let result = decoder.decode(&input[..], &mut output[..], false);
drop(decoder);
drop(input);
drop(output);
assert_eq!(result.unwrap_err().code(), magnum_opus::ErrorCode::InvalidPacket);
}

View File

@@ -0,0 +1,127 @@
extern crate magnum_opus;
fn check_ascii(s: &str) -> &str {
for &b in s.as_bytes() {
assert!(b < 0x80, "Non-ASCII character in string");
assert!(b > 0x00, "NUL in string")
}
std::str::from_utf8(s.as_bytes()).unwrap()
}
#[test]
fn strings_ascii() {
use magnum_opus::ErrorCode::*;
println!("\nVersion: {}", check_ascii(magnum_opus::version()));
let codes = [BadArg, BufferTooSmall, InternalError, InvalidPacket,
Unimplemented, InvalidState, AllocFail, Unknown];
for &code in codes.iter() {
println!("{:?}: {}", code, check_ascii(code.description()));
}
}
// 48000Hz * 1 channel * 20 ms / 1000
const MONO_20MS: usize = 48000 * 1 * 20 / 1000;
#[test]
fn encode_mono() {
let mut encoder = magnum_opus::Encoder::new(48000, magnum_opus::Channels::Mono, magnum_opus::Application::Audio).unwrap();
let mut output = [0; 256];
let len = encoder.encode(&[0_i16; MONO_20MS], &mut output).unwrap();
assert_eq!(&output[..len], &[248, 255, 254]);
let len = encoder.encode(&[0_i16; MONO_20MS], &mut output).unwrap();
assert_eq!(&output[..len], &[248, 255, 254]);
let len = encoder.encode(&[1_i16; MONO_20MS], &mut output).unwrap();
assert!(len > 190 && len < 220);
let len = encoder.encode(&[0_i16; MONO_20MS], &mut output).unwrap();
assert!(len > 170 && len < 190);
let myvec = encoder.encode_vec(&[1_i16; MONO_20MS], output.len()).unwrap();
assert!(myvec.len() > 120 && myvec.len() < 140);
}
#[test]
fn encode_stereo() {
let mut encoder = magnum_opus::Encoder::new(48000, magnum_opus::Channels::Stereo, magnum_opus::Application::Audio).unwrap();
let mut output = [0; 512];
let len = encoder.encode(&[0_i16; 2 * MONO_20MS], &mut output).unwrap();
assert_eq!(&output[..len], &[252, 255, 254]);
let len = encoder.encode(&[0_i16; 4 * MONO_20MS], &mut output).unwrap();
assert_eq!(&output[..len], &[253, 255, 254, 255, 254]);
let len = encoder.encode(&[17_i16; 2 * MONO_20MS], &mut output).unwrap();
assert!(len > 240);
let len = encoder.encode(&[0_i16; 2 * MONO_20MS], &mut output).unwrap();
assert!(len > 240);
// Very small buffer should still succeed
let len = encoder.encode(&[95_i16; 2 * MONO_20MS], &mut [0; 20]).unwrap();
assert!(len <= 20);
let myvec = encoder.encode_vec(&[95_i16; 2 * MONO_20MS], 20).unwrap();
assert!(myvec.len() <= 20);
}
#[test]
fn encode_bad_rate() {
match magnum_opus::Encoder::new(48001, magnum_opus::Channels::Mono, magnum_opus::Application::Audio) {
Ok(_) => panic!("Encoder::new did not return BadArg"),
Err(err) => assert_eq!(err.code(), magnum_opus::ErrorCode::BadArg),
}
}
#[test]
fn encode_bad_buffer() {
let mut encoder = magnum_opus::Encoder::new(48000, magnum_opus::Channels::Stereo, magnum_opus::Application::Audio).unwrap();
match encoder.encode(&[1_i16; 2 * MONO_20MS], &mut [0; 0]) {
Ok(_) => panic!("encode with 0-length buffer did not return BadArg"),
Err(err) => assert_eq!(err.code(), magnum_opus::ErrorCode::BadArg),
}
}
#[test]
fn repacketizer() {
let mut rp = magnum_opus::Repacketizer::new().unwrap();
let mut out = [0; 256];
for _ in 0..2 {
let packet1 = [249, 255, 254, 255, 254];
let packet2 = [248, 255, 254];
let mut state = rp.begin();
state.cat(&packet1).unwrap();
state.cat(&packet2).unwrap();
let len = state.out(&mut out).unwrap();
assert_eq!(&out[..len], &[251, 3, 255, 254, 255, 254, 255, 254]);
}
for _ in 0..2 {
let packet = [248, 255, 254];
let state = rp.begin().cat_move(&packet).unwrap();
let packet = [249, 255, 254, 255, 254];
let state = state.cat_move(&packet).unwrap();
let len = {state}.out(&mut out).unwrap();
assert_eq!(&out[..len], &[251, 3, 255, 254, 255, 254, 255, 254]);
}
for _ in 0..2 {
let len = rp.combine(&[
&[249, 255, 254, 255, 254],
&[248, 255, 254],
], &mut out).unwrap();
assert_eq!(&out[..len], &[251, 3, 255, 254, 255, 254, 255, 254]);
}
for _ in 0..2 {
let len = rp.begin()
.cat_move(&[248, 255, 254]).unwrap()
.cat_move(&[248, 71, 71]).unwrap()
.out(&mut out).unwrap();
assert_eq!(&out[..len], &[249, 255, 254, 71, 71]);
}
}

3
libs/parity-tokio-ipc/.gitignore vendored Normal file
View File

@@ -0,0 +1,3 @@
target
Cargo.lock
.idea

View File

@@ -0,0 +1,20 @@
language: rust
rust:
- stable
- beta
- nightly
matrix:
allow_failures:
- rust: nightly
after_success:
- |-
[ $TRAVIS_BRANCH = master ] &&
[ $TRAVIS_PULL_REQUEST = false ] &&
cargo doc --all --no-deps &&
echo '<meta http-equiv=refresh content=0;url=parity_tokio_ipc/index.html>' > target/doc/index.html &&
pip install --user ghp-import &&
/home/travis/.local/bin/ghp-import -n target/doc &&
git push -fq https://${TOKEN}@github.com/${TRAVIS_REPO_SLUG}.git gh-pages
env:
global:
secure: eUHPLjVMSVclRcEgwgybIKZQJTBW8QDjcjgIsEhOHZn7Kpzw0+rwJVoKkvr/uqyJwyY7pHy36mWX31J8YDSbSiM3W8jXeI97sk+FTUkleqUffPzXnbnR1D4kHZlKndFIbcuO5Z+rtVgsAv5E/u1w9XR+mvgK2lfaIEay+26gBl6dl/1TxWvrwDBeMvfq1JGVDQH4Etubncpi3LSWhbRkie1AKnVnsDIY9sUYVKSnIqjxx0qW6Z7EiCdwZ8gf04LNnqyIoKDpyldotL+nJ67ZlVI2O2DrbOOt55nliFHsH4BcWZIZOyIAM4PxIwhDl8g9E55FLkkUX9VUpVtqjTu9RWkVl7rzyrSxLoBUEjguIPrpFWBwLo0FSDvplB2XCXt8x035Io5PEg6m5dVxx5iytTIbI6HQwcA0ESTuDPuAdRJMNvJS/9e2UzPukdYYaaxF6g8wSmiIQjLuZU/nGBdmAl7Uw6cFlQnyLc/GXQg0oZ+B/J8sc4W2C/Z64oB8jK72RLNTKeeWs/XSOt8NxQiNkWeFIhGqiYOPJgjBiTCLSKJPY3CUTiBT8QpAcpj1x1gsWi+5fRoXYxNig/CmeTwZjuxKNxfQIu3J+lJbNdt44x7whnwhZ/AKVuLFPNNiC2OBNpa738UY60VYDoNZyhomWSdBnz3E6i1VtdiSnujFFnc=

View File

@@ -0,0 +1,24 @@
[package]
name = "parity-tokio-ipc"
version = "0.7.2"
edition = "2018"
authors = ["NikVolf <nikvolf@gmail.com>"]
license = "MIT/Apache-2.0"
readme = "README.md"
repository = "https://github.com/nikvolf/parity-tokio-ipc"
homepage = "https://github.com/nikvolf/parity-tokio-ipc"
description = """
Interprocess communication library for tokio.
"""
[dependencies]
futures = "0.3"
log = "0.4"
mio-named-pipes = "0.1"
miow = "0.3"
rand = "0.7"
tokio = { version = "0.2", features = ["io-driver", "io-util", "uds", "stream", "rt-core", "macros", "time"] }
libc = "0.2"
[target.'cfg(windows)'.dependencies]
winapi = { version = "0.3", features = ["winbase", "winnt", "accctrl", "aclapi", "securitybaseapi", "minwinbase", "winbase"] }

View File

@@ -0,0 +1,201 @@
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 [yyyy] [name of copyright owner]
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.

View File

@@ -0,0 +1,25 @@
Copyright (c) 2017 Nikolay Volf
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.

View File

@@ -0,0 +1,28 @@
# parity-tokio-ipc
[![Build Status](https://travis-ci.org/NikVolf/parity-tokio-ipc.svg?branch=master)](https://travis-ci.org/NikVolf/parity-tokio-ipc)
[Documentation](https://nikvolf.github.io/parity-tokio-ipc)
This crate abstracts interprocess transport for UNIX/Windows. On UNIX it utilizes unix sockets (`tokio_uds` crate) and named pipe on windows (experimental `tokio-named-pipes` crate).
Endpoint is transport-agnostic interface for incoming connections:
```rust
let endpoint = Endpoint::new(endpoint_addr, handle).unwrap();
endpoint.incoming().for_each(|_| println!("Connection received!"));
```
And IpcStream is transport-agnostic io:
```rust
let endpoint = Endpoint::new(endpoint_addr, handle).unwrap();
endpoint.incoming().for_each(|(ipc_stream: IpcStream, _)| io::write_all(ipc_stream, b"Hello!"));
```
# License
`parity-tokio-ipc` is primarily distributed under the terms of both the MIT
license and the Apache License (Version 2.0), with portions covered by various
BSD-like licenses.
See LICENSE-APACHE, and LICENSE-MIT for details.

View File

@@ -0,0 +1,16 @@
environment:
matrix:
- TARGET: x86_64-pc-windows-msvc
install:
- curl -sSf -o rustup-init.exe https://win.rustup.rs/
- rustup-init.exe -y --default-host %TARGET%
- set PATH=%PATH%;C:\Users\appveyor\.cargo\bin;C:\MinGW\bin
- rustc -vV
- cargo -vV
build: false
test_script:
- cargo test

View File

@@ -0,0 +1,24 @@
use tokio::{self, prelude::*};
use parity_tokio_ipc::Endpoint;
#[tokio::main]
async fn main() {
let path = std::env::args().nth(1).expect("Run it with server path to connect as argument");
let mut client = Endpoint::connect(&path).await
.expect("Failed to connect client.");
loop {
let mut buf = [0u8; 4];
println!("SEND: PING");
client.write_all(b"ping").await.expect("Unable to write message to client");
client.read_exact(&mut buf[..]).await.expect("Unable to read buffer");
if let Ok("pong") = std::str::from_utf8(&buf[..]) {
println!("RECEIVED: PONG");
} else {
break;
}
tokio::time::delay_for(std::time::Duration::from_secs(2)).await;
}
}

View File

@@ -0,0 +1,47 @@
use futures::StreamExt as _;
use tokio::{
prelude::*,
self,
io::split,
};
use parity_tokio_ipc::{Endpoint, SecurityAttributes};
async fn run_server(path: String) {
let mut endpoint = Endpoint::new(path);
endpoint.set_security_attributes(SecurityAttributes::allow_everyone_create().unwrap());
let mut incoming = endpoint.incoming().expect("failed to open new socket");
while let Some(result) = incoming.next().await
{
match result {
Ok(stream) => {
let (mut reader, mut writer) = split(stream);
tokio::spawn(async move {
loop {
let mut buf = [0u8; 4];
let pong_buf = b"pong";
if let Err(_) = reader.read_exact(&mut buf).await {
println!("Closing socket");
break;
}
if let Ok("ping") = std::str::from_utf8(&buf[..]) {
println!("RECIEVED: PING");
writer.write_all(pong_buf).await.expect("unable to write to socket");
println!("SEND: PONG");
}
}
});
}
_ => unreachable!("ideally")
}
};
}
#[tokio::main]
async fn main() {
let path = std::env::args().nth(1).expect("Run it with server path as argument");
run_server(path).await
}

View File

@@ -0,0 +1,7 @@
#!/bin/bash
echo "Spawning 100 processes"
for i in {1..100} ;
do
( cargo run --example client -- /tmp/test.ipc & )
done

View File

@@ -0,0 +1,154 @@
//! Tokio IPC transport. Under the hood uses Unix Domain Sockets for Linux/Mac
//! and Named Pipes for Windows.
//#![warn(missing_docs)]
//#![deny(rust_2018_idioms)]
#[cfg(windows)]
mod win;
#[cfg(not(windows))]
mod unix;
/// Endpoint for IPC transport
///
/// # Examples
///
/// ```ignore
/// use parity_tokio_ipc::{Endpoint, dummy_endpoint};
/// use futures::{future, Future, Stream, StreamExt};
/// use tokio::runtime::Runtime;
///
/// fn main() {
/// let mut runtime = Runtime::new().unwrap();
/// let mut endpoint = Endpoint::new(dummy_endpoint());
/// let server = endpoint.incoming()
/// .expect("failed to open up a new pipe/socket")
/// .for_each(|_stream| {
/// println!("Connection received");
/// futures::future::ready(())
/// });
/// runtime.block_on(server)
/// }
///```
#[cfg(windows)]
pub use win::{SecurityAttributes, Endpoint, Connection, Incoming};
#[cfg(unix)]
pub use unix::{SecurityAttributes, Endpoint, Connection, Incoming};
/// For testing/examples
pub fn dummy_endpoint() -> String {
let num: u64 = rand::Rng::gen(&mut rand::thread_rng());
if cfg!(windows) {
format!(r"\\.\pipe\my-pipe-{}", num)
} else {
format!(r"/tmp/my-uds-{}", num)
}
}
#[cfg(test)]
mod tests {
use tokio::prelude::*;
use futures::{channel::oneshot, StreamExt as _, FutureExt as _};
use std::time::Duration;
use tokio::{
self,
io::split,
};
use super::{dummy_endpoint, Endpoint, SecurityAttributes};
use std::path::Path;
use futures::future::{Either, select, ready};
async fn run_server(path: String) {
let path = path.to_owned();
let mut endpoint = Endpoint::new(path);
endpoint.set_security_attributes(
SecurityAttributes::empty()
.set_mode(0o777)
.unwrap()
);
let mut incoming = endpoint.incoming().expect("failed to open up a new socket");
while let Some(result) = incoming.next().await {
match result {
Ok(stream) => {
let (mut reader, mut writer) = split(stream);
let mut buf = [0u8; 5];
reader.read_exact(&mut buf).await.expect("unable to read from socket");
writer.write_all(&buf[..]).await.expect("unable to write to socket");
}
_ => unreachable!("ideally")
}
};
}
#[tokio::test]
async fn smoke_test() {
let path = dummy_endpoint();
let (shutdown_tx, shutdown_rx) = oneshot::channel();
let server = select(Box::pin(run_server(path.clone())), shutdown_rx)
.then(|either| {
match either {
Either::Right((_, server)) => {
drop(server);
}
_ => unreachable!("also ideally")
};
ready(())
});
tokio::spawn(server);
tokio::time::delay_for(Duration::from_secs(2)).await;
println!("Connecting to client 0...");
let mut client_0 = Endpoint::connect(&path).await
.expect("failed to open client_0");
tokio::time::delay_for(Duration::from_secs(2)).await;
println!("Connecting to client 1...");
let mut client_1 = Endpoint::connect(&path).await
.expect("failed to open client_1");
let msg = b"hello";
let mut rx_buf = vec![0u8; msg.len()];
client_0.write_all(msg).await.expect("Unable to write message to client");
client_0.read_exact(&mut rx_buf).await.expect("Unable to read message from client");
let mut rx_buf2 = vec![0u8; msg.len()];
client_1.write_all(msg).await.expect("Unable to write message to client");
client_1.read_exact(&mut rx_buf2).await.expect("Unable to read message from client");
assert_eq!(rx_buf, msg);
assert_eq!(rx_buf2, msg);
// shutdown server
if let Ok(()) = shutdown_tx.send(()) {
// wait one second for the file to be deleted.
tokio::time::delay_for(Duration::from_secs(1)).await;
let path = Path::new(&path);
// assert that it has
assert!(!path.exists());
}
}
#[cfg(windows)]
fn create_pipe_with_permissions(attr: SecurityAttributes) -> ::std::io::Result<()> {
let path = dummy_endpoint();
let mut endpoint = Endpoint::new(path);
endpoint.set_security_attributes(attr);
endpoint.incoming().map(|_| ())
}
#[cfg(windows)]
#[tokio::test]
async fn test_pipe_permissions() {
create_pipe_with_permissions(SecurityAttributes::empty())
.expect("failed with no attributes");
create_pipe_with_permissions(SecurityAttributes::allow_everyone_create().unwrap())
.expect("failed with attributes for creating");
create_pipe_with_permissions(SecurityAttributes::empty().allow_everyone_connect().unwrap())
.expect("failed with attributes for connecting");
}
}

View File

@@ -0,0 +1,163 @@
use libc::chmod;
use std::ffi::CString;
use std::io::{self, Error};
use tokio::prelude::*;
use tokio::net::{UnixListener, UnixStream};
use std::path::Path;
use std::pin::Pin;
use std::task::{Context, Poll};
use std::mem::MaybeUninit;
/// Socket permissions and ownership on UNIX
pub struct SecurityAttributes {
// read/write permissions for owner, group and others in unix octal.
mode: Option<u16>
}
impl SecurityAttributes {
/// New default security attributes.
pub fn empty() -> Self {
SecurityAttributes {
mode: None
}
}
/// New security attributes that allow everyone to connect.
pub fn allow_everyone_connect(mut self) -> io::Result<Self> {
self.mode = Some(0o777);
Ok(self)
}
/// Set a custom permission on the socket
pub fn set_mode(mut self, mode: u16) -> io::Result<Self> {
self.mode = Some(mode);
Ok(self)
}
/// New security attributes that allow everyone to create.
pub fn allow_everyone_create() -> io::Result<Self> {
Ok(SecurityAttributes {
mode: None
})
}
/// called in unix, after server socket has been created
/// will apply security attributes to the socket.
pub(crate) unsafe fn apply_permissions(&self, path: &str) -> io::Result<()> {
let path = CString::new(path.to_owned())?;
if let Some(mode) = self.mode {
if chmod(path.as_ptr(), mode as _) == -1 {
return Err(Error::last_os_error())
}
}
Ok(())
}
}
/// Endpoint implementation for unix systems
pub struct Endpoint {
path: String,
security_attributes: SecurityAttributes,
}
pub struct Incoming {
socket: UnixListener,
}
impl Incoming {
pub async fn next(&mut self) -> Option<io::Result<Connection>> {
match self.socket.accept().await {
Ok((stream, _)) => Some(Ok(Connection::wrap(stream))),
Err(err) => Some(Err(err))
}
}
}
impl Endpoint {
/// Stream of incoming connections
pub fn incoming(&mut self) -> io::Result<Incoming> {
unsafe {
// the call to bind in `inner()` creates the file
// `apply_permission()` will set the file permissions.
self.security_attributes.apply_permissions(&self.path)?;
};
let socket = self.inner()?;
Ok(Incoming { socket })
}
/// Inner platform-dependant state of the endpoint
fn inner(&self) -> io::Result<UnixListener> {
UnixListener::bind(&self.path)
}
/// Set security attributes for the connection
pub fn set_security_attributes(&mut self, security_attributes: SecurityAttributes) {
self.security_attributes = security_attributes;
}
/// Make new connection using the provided path and running event pool
pub async fn connect<P: AsRef<Path>>(path: P) -> io::Result<Connection> {
Ok(Connection::wrap(UnixStream::connect(path.as_ref()).await?))
}
/// Returns the path of the endpoint.
pub fn path(&self) -> &str {
&self.path
}
/// New IPC endpoint at the given path
pub fn new(path: String) -> Self {
Endpoint {
path,
security_attributes: SecurityAttributes::empty(),
}
}
}
/// IPC connection.
pub struct Connection {
inner: UnixStream,
}
impl Connection {
fn wrap(stream: UnixStream) -> Self {
Self { inner: stream }
}
}
impl AsyncRead for Connection {
unsafe fn prepare_uninitialized_buffer(&self, buf: &mut [MaybeUninit<u8>]) -> bool {
self.inner.prepare_uninitialized_buffer(buf)
}
fn poll_read(
self: Pin<&mut Self>,
ctx: &mut Context<'_>,
buf: &mut [u8],
) -> Poll<io::Result<usize>> {
let this = Pin::into_inner(self);
Pin::new(&mut this.inner).poll_read(ctx, buf)
}
}
impl AsyncWrite for Connection {
fn poll_write(
self: Pin<&mut Self>,
ctx: &mut Context<'_>,
buf: &[u8],
) -> Poll<Result<usize, io::Error>> {
let this = Pin::into_inner(self);
Pin::new(&mut this.inner).poll_write(ctx, buf)
}
fn poll_flush(self: Pin<&mut Self>, ctx: &mut Context<'_>) -> Poll<Result<(), io::Error>> {
let this = Pin::into_inner(self);
Pin::new(&mut this.inner).poll_flush(ctx)
}
fn poll_shutdown(self: Pin<&mut Self>, ctx: &mut Context<'_>) -> Poll<Result<(), io::Error>> {
let this = Pin::into_inner(self);
Pin::new(&mut this.inner).poll_shutdown(ctx)
}
}

View File

@@ -0,0 +1,488 @@
use winapi::shared::winerror::ERROR_SUCCESS;
use winapi::um::accctrl::*;
use winapi::um::aclapi::*;
use winapi::um::minwinbase::{LPTR, PSECURITY_ATTRIBUTES, SECURITY_ATTRIBUTES};
use winapi::um::securitybaseapi::*;
use winapi::um::winbase::{LocalAlloc, LocalFree};
use winapi::um::winnt::*;
use std::io;
use std::marker;
use std::mem;
use std::ptr;
use futures::Stream;
use tokio::prelude::*;
use std::pin::Pin;
use std::task::{Context, Poll};
use std::path::Path;
use std::mem::MaybeUninit;
use tokio::io::PollEvented;
type NamedPipe = PollEvented<mio_named_pipes::NamedPipe>;
const PIPE_AVAILABILITY_TIMEOUT: u64 = 5000;
/// Endpoint implementation for windows
pub struct Endpoint {
path: String,
security_attributes: SecurityAttributes,
}
impl Endpoint {
/// Stream of incoming connections
pub fn incoming(mut self) -> io::Result<Incoming> {
let pipe = self.inner()?;
Ok(Incoming {
path: self.path.clone(),
inner: NamedPipeSupport {
path: self.path,
pipe,
security_attributes: self.security_attributes,
},
})
}
/// Inner platform-dependant state of the endpoint
fn inner(&mut self) -> io::Result<NamedPipe> {
use miow::pipe::NamedPipeBuilder;
use std::os::windows::io::*;
let raw_handle = unsafe {
NamedPipeBuilder::new(&self.path)
.first(true)
.inbound(true)
.outbound(true)
.out_buffer_size(65536)
.in_buffer_size(65536)
.with_security_attributes(self.security_attributes.as_ptr())?
.into_raw_handle()
};
let mio_pipe = unsafe { mio_named_pipes::NamedPipe::from_raw_handle(raw_handle) };
NamedPipe::new(mio_pipe)
}
/// Set security attributes for the connection
pub fn set_security_attributes(&mut self, security_attributes: SecurityAttributes) {
self.security_attributes = security_attributes;
}
/// Returns the path of the endpoint.
pub fn path(&self) -> &str {
&self.path
}
/// Make new connection using the provided path and running event pool.
pub async fn connect<P: AsRef<Path>>(path: P) -> io::Result<Connection> {
Ok(Connection::wrap(Self::connect_inner(path.as_ref())?))
}
fn connect_inner(path: &Path) -> io::Result<NamedPipe> {
use std::fs::OpenOptions;
use std::os::windows::fs::OpenOptionsExt;
use std::os::windows::io::{FromRawHandle, IntoRawHandle};
use winapi::um::winbase::FILE_FLAG_OVERLAPPED;
// Wait for the pipe to become available or fail after 5 seconds.
miow::pipe::NamedPipe::wait(
path,
Some(std::time::Duration::from_millis(PIPE_AVAILABILITY_TIMEOUT)),
)?;
let file = OpenOptions::new()
.read(true)
.write(true)
.custom_flags(FILE_FLAG_OVERLAPPED)
.open(path)?;
let mio_pipe =
unsafe { mio_named_pipes::NamedPipe::from_raw_handle(file.into_raw_handle()) };
let pipe = NamedPipe::new(mio_pipe)?;
Ok(pipe)
}
/// New IPC endpoint at the given path
pub fn new(path: String) -> Self {
Endpoint {
path,
security_attributes: SecurityAttributes::empty(),
}
}
}
struct NamedPipeSupport {
path: String,
pipe: NamedPipe,
security_attributes: SecurityAttributes,
}
impl NamedPipeSupport {
fn replacement_pipe(&mut self) -> io::Result<NamedPipe> {
use miow::pipe::NamedPipeBuilder;
use std::os::windows::io::*;
let raw_handle = unsafe {
NamedPipeBuilder::new(&self.path)
.first(false)
.inbound(true)
.outbound(true)
.out_buffer_size(65536)
.in_buffer_size(65536)
.with_security_attributes(self.security_attributes.as_ptr())?
.into_raw_handle()
};
let mio_pipe = unsafe { mio_named_pipes::NamedPipe::from_raw_handle(raw_handle) };
NamedPipe::new(mio_pipe)
}
}
/// Stream of incoming connections
pub struct Incoming {
#[allow(dead_code)]
path: String,
inner: NamedPipeSupport,
}
impl Stream for Incoming {
type Item = tokio::io::Result<Connection>;
fn poll_next(mut self: Pin<&mut Self>, ctx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
match self.inner.pipe.get_ref().connect() {
Ok(()) => {
log::trace!("Incoming connection polled successfully");
let new_listener = self.inner.replacement_pipe()?;
Poll::Ready(
Some(Ok(Connection::wrap(std::mem::replace(&mut self.inner.pipe, new_listener))))
)
}
Err(e) => {
if e.kind() == io::ErrorKind::WouldBlock {
self.inner.pipe.clear_write_ready(ctx);
Poll::Pending
} else {
Poll::Ready(Some(Err(e)))
}
}
}
}
}
/// IPC connection.
pub struct Connection {
inner: NamedPipe,
}
impl Connection {
pub fn wrap(pipe: NamedPipe) -> Self {
Self { inner: pipe }
}
}
impl AsyncRead for Connection {
unsafe fn prepare_uninitialized_buffer(&self, buf: &mut [MaybeUninit<u8>]) -> bool {
self.inner.prepare_uninitialized_buffer(buf)
}
fn poll_read(
self: Pin<&mut Self>,
ctx: &mut Context<'_>,
buf: &mut [u8],
) -> Poll<io::Result<usize>> {
let this = Pin::into_inner(self);
Pin::new(&mut this.inner).poll_read(ctx, buf)
}
}
impl AsyncWrite for Connection {
fn poll_write(
self: Pin<&mut Self>,
ctx: &mut Context<'_>,
buf: &[u8],
) -> Poll<Result<usize, io::Error>> {
let this = Pin::into_inner(self);
Pin::new(&mut this.inner).poll_write(ctx, buf)
}
fn poll_flush(self: Pin<&mut Self>, ctx: &mut Context<'_>) -> Poll<Result<(), io::Error>> {
let this = Pin::into_inner(self);
Pin::new(&mut this.inner).poll_flush(ctx)
}
fn poll_shutdown(self: Pin<&mut Self>, ctx: &mut Context<'_>) -> Poll<Result<(), io::Error>> {
let this = Pin::into_inner(self);
Pin::new(&mut this.inner).poll_shutdown(ctx)
}
}
/// Security attributes.
pub struct SecurityAttributes {
attributes: Option<InnerAttributes>,
}
impl SecurityAttributes {
/// New default security attributes.
pub fn empty() -> SecurityAttributes {
SecurityAttributes { attributes: None }
}
/// New default security attributes that allow everyone to connect.
pub fn allow_everyone_connect(&self) -> io::Result<SecurityAttributes> {
let attributes = Some(InnerAttributes::allow_everyone(
GENERIC_READ | FILE_WRITE_DATA,
)?);
Ok(SecurityAttributes { attributes })
}
/// Set a custom permission on the socket
pub fn set_mode(self, _mode: u32) -> io::Result<Self> {
// for now, does nothing.
Ok(self)
}
/// New default security attributes that allow everyone to create.
pub fn allow_everyone_create() -> io::Result<SecurityAttributes> {
let attributes = Some(InnerAttributes::allow_everyone(
GENERIC_READ | GENERIC_WRITE,
)?);
Ok(SecurityAttributes { attributes })
}
/// Return raw handle of security attributes.
pub(crate) unsafe fn as_ptr(&mut self) -> PSECURITY_ATTRIBUTES {
match self.attributes.as_mut() {
Some(attributes) => attributes.as_ptr(),
None => ptr::null_mut(),
}
}
}
unsafe impl Send for SecurityAttributes {}
struct Sid {
sid_ptr: PSID,
}
impl Sid {
fn everyone_sid() -> io::Result<Sid> {
let mut sid_ptr = ptr::null_mut();
let result = unsafe {
AllocateAndInitializeSid(
SECURITY_WORLD_SID_AUTHORITY.as_mut_ptr() as *mut _,
1,
SECURITY_WORLD_RID,
0,
0,
0,
0,
0,
0,
0,
&mut sid_ptr,
)
};
if result == 0 {
Err(io::Error::last_os_error())
} else {
Ok(Sid { sid_ptr })
}
}
// Unsafe - the returned pointer is only valid for the lifetime of self.
unsafe fn as_ptr(&self) -> PSID {
self.sid_ptr
}
}
impl Drop for Sid {
fn drop(&mut self) {
if !self.sid_ptr.is_null() {
unsafe {
FreeSid(self.sid_ptr);
}
}
}
}
struct AceWithSid<'a> {
explicit_access: EXPLICIT_ACCESS_W,
_marker: marker::PhantomData<&'a Sid>,
}
impl<'a> AceWithSid<'a> {
fn new(sid: &'a Sid, trustee_type: u32) -> AceWithSid<'a> {
let mut explicit_access = unsafe { mem::zeroed::<EXPLICIT_ACCESS_W>() };
explicit_access.Trustee.TrusteeForm = TRUSTEE_IS_SID;
explicit_access.Trustee.TrusteeType = trustee_type;
explicit_access.Trustee.ptstrName = unsafe { sid.as_ptr() as *mut _ };
AceWithSid {
explicit_access,
_marker: marker::PhantomData,
}
}
fn set_access_mode(&mut self, access_mode: u32) -> &mut Self {
self.explicit_access.grfAccessMode = access_mode;
self
}
fn set_access_permissions(&mut self, access_permissions: u32) -> &mut Self {
self.explicit_access.grfAccessPermissions = access_permissions;
self
}
fn allow_inheritance(&mut self, inheritance_flags: u32) -> &mut Self {
self.explicit_access.grfInheritance = inheritance_flags;
self
}
}
struct Acl {
acl_ptr: PACL,
}
impl Acl {
fn empty() -> io::Result<Acl> {
Self::new(&mut [])
}
fn new(entries: &mut [AceWithSid<'_>]) -> io::Result<Acl> {
let mut acl_ptr = ptr::null_mut();
let result = unsafe {
SetEntriesInAclW(
entries.len() as u32,
entries.as_mut_ptr() as *mut _,
ptr::null_mut(),
&mut acl_ptr,
)
};
if result != ERROR_SUCCESS {
return Err(io::Error::from_raw_os_error(result as i32));
}
Ok(Acl { acl_ptr })
}
unsafe fn as_ptr(&self) -> PACL {
self.acl_ptr
}
}
impl Drop for Acl {
fn drop(&mut self) {
if !self.acl_ptr.is_null() {
unsafe { LocalFree(self.acl_ptr as *mut _) };
}
}
}
struct SecurityDescriptor {
descriptor_ptr: PSECURITY_DESCRIPTOR,
}
impl SecurityDescriptor {
fn new() -> io::Result<Self> {
let descriptor_ptr = unsafe { LocalAlloc(LPTR, SECURITY_DESCRIPTOR_MIN_LENGTH) };
if descriptor_ptr.is_null() {
return Err(io::Error::new(
io::ErrorKind::Other,
"Failed to allocate security descriptor",
));
}
if unsafe {
InitializeSecurityDescriptor(descriptor_ptr, SECURITY_DESCRIPTOR_REVISION) == 0
} {
return Err(io::Error::last_os_error());
};
Ok(SecurityDescriptor { descriptor_ptr })
}
fn set_dacl(&mut self, acl: &Acl) -> io::Result<()> {
if unsafe {
SetSecurityDescriptorDacl(self.descriptor_ptr, true as i32, acl.as_ptr(), false as i32)
== 0
} {
return Err(io::Error::last_os_error());
}
Ok(())
}
unsafe fn as_ptr(&self) -> PSECURITY_DESCRIPTOR {
self.descriptor_ptr
}
}
impl Drop for SecurityDescriptor {
fn drop(&mut self) {
if !self.descriptor_ptr.is_null() {
unsafe { LocalFree(self.descriptor_ptr) };
self.descriptor_ptr = ptr::null_mut();
}
}
}
struct InnerAttributes {
descriptor: SecurityDescriptor,
acl: Acl,
attrs: SECURITY_ATTRIBUTES,
}
impl InnerAttributes {
fn empty() -> io::Result<InnerAttributes> {
let descriptor = SecurityDescriptor::new()?;
let mut attrs = unsafe { mem::zeroed::<SECURITY_ATTRIBUTES>() };
attrs.nLength = mem::size_of::<SECURITY_ATTRIBUTES>() as u32;
attrs.lpSecurityDescriptor = unsafe { descriptor.as_ptr() };
attrs.bInheritHandle = false as i32;
let acl = Acl::empty().expect("this should never fail");
Ok(InnerAttributes {
acl,
descriptor,
attrs,
})
}
fn allow_everyone(permissions: u32) -> io::Result<InnerAttributes> {
let mut attributes = Self::empty()?;
let sid = Sid::everyone_sid()?;
let mut everyone_ace = AceWithSid::new(&sid, TRUSTEE_IS_WELL_KNOWN_GROUP);
everyone_ace
.set_access_mode(SET_ACCESS)
.set_access_permissions(permissions)
.allow_inheritance(false as u32);
let mut entries = vec![everyone_ace];
attributes.acl = Acl::new(&mut entries)?;
attributes.descriptor.set_dacl(&attributes.acl)?;
Ok(attributes)
}
unsafe fn as_ptr(&mut self) -> PSECURITY_ATTRIBUTES {
&mut self.attrs as *mut _
}
}
#[cfg(test)]
mod test {
use super::SecurityAttributes;
#[test]
fn test_allow_everyone_everything() {
SecurityAttributes::allow_everyone_create()
.expect("failed to create security attributes that allow everyone to create a pipe");
}
#[test]
fn test_allow_eveyone_read_write() {
SecurityAttributes::empty()
.allow_everyone_connect()
.expect("failed to create security attributes that allow everyone to read and write to/from a pipe");
}
}

4
libs/pulsectl/.gitignore vendored Normal file
View File

@@ -0,0 +1,4 @@
**/target
/target
**/*.rs.bk
.idea/

129
libs/pulsectl/Cargo.lock generated Normal file
View File

@@ -0,0 +1,129 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
[[package]]
name = "autocfg"
version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cdb031dd78e28731d87d56cc8ffef4a8f36ca26c38fe2de700543e627f8a464a"
[[package]]
name = "libc"
version = "0.2.65"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1a31a0627fdf1f6a39ec0dd577e101440b7db22672c0901fe00a9a6fbb5c24e8"
[[package]]
name = "libpulse-binding"
version = "2.18.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fe925a4d3a96961316c9c1488f97a95938a6093f0d4691eec888776057ce965e"
dependencies = [
"libc",
"libpulse-sys",
"num-derive",
"num-traits",
"winapi",
]
[[package]]
name = "libpulse-sys"
version = "1.15.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2d9073c83dda6aff9b611dc368e8db6e0aa29027546d8800a18b4417e182b4d5"
dependencies = [
"libc",
"num-derive",
"num-traits",
"pkg-config",
"winapi",
]
[[package]]
name = "num-derive"
version = "0.3.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "876a53fff98e03a936a674b29568b0e605f06b29372c2489ff4de23f1949743d"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "num-traits"
version = "0.2.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9a64b1ec5cda2586e284722486d802acf1f7dbdc623e2bfc57e65ca1cd099290"
dependencies = [
"autocfg",
]
[[package]]
name = "pkg-config"
version = "0.3.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "05da548ad6865900e60eaba7f589cc0783590a92e940c26953ff81ddbab2d677"
[[package]]
name = "proc-macro2"
version = "1.0.24"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1e0704ee1a7e00d7bb417d0770ea303c1bccbabf0ef1667dae92b5967f5f8a71"
dependencies = [
"unicode-xid",
]
[[package]]
name = "quote"
version = "1.0.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aa563d17ecb180e500da1cfd2b028310ac758de548efdd203e18f283af693f37"
dependencies = [
"proc-macro2",
]
[[package]]
name = "rust-pulsectl"
version = "0.2.9"
dependencies = [
"libpulse-binding",
]
[[package]]
name = "syn"
version = "1.0.51"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3b4f34193997d92804d359ed09953e25d5138df6bcc055a71bf68ee89fdf9223"
dependencies = [
"proc-macro2",
"quote",
"unicode-xid",
]
[[package]]
name = "unicode-xid"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f7fe0bb3479651439c9112f72b6c505038574c9fbb575ed1bf3b797fa39dd564"
[[package]]
name = "winapi"
version = "0.3.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419"
dependencies = [
"winapi-i686-pc-windows-gnu",
"winapi-x86_64-pc-windows-gnu",
]
[[package]]
name = "winapi-i686-pc-windows-gnu"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6"
[[package]]
name = "winapi-x86_64-pc-windows-gnu"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"

19
libs/pulsectl/Cargo.toml Normal file
View File

@@ -0,0 +1,19 @@
[package]
name = "rust-pulsectl"
version = "0.2.10"
authors = ["Kristopher Ruzic <krruzic@gmail.com>"]
edition = "2018"
license = "GPL-3.0+"
description = "A higher level API for libpulse_binding"
readme = "README.md"
keywords = ["pulse", "pulseaudio", "binding", "audio", "api"]
categories = ["api-bindings", "multimedia::audio"]
homepage = "https://github.com/krruzic/pulsectl"
repository = "https://github.com/krruzic/pulsectl"
[lib]
name = "pulsectl"
path = "src/lib.rs"
[dependencies]
libpulse-binding = "2.21"

13
libs/pulsectl/LICENSE.md Normal file
View File

@@ -0,0 +1,13 @@
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.

43
libs/pulsectl/README.md Normal file
View File

@@ -0,0 +1,43 @@
Rust PulsecAudio API
====================
`pulsectl-rust` is a API wrapper for `libpulse_binding` to make pulseaudio application development easier.
This is a wrapper around the introspector, and thus this library is only capable of modifying PulseAudio data (changing volume, routing applications and muting right now).
### Usage
Add this to your `Cargo.toml`:
```toml
[dependencies]
rust-pulsectl = "0.2.6"
```
Then, connect to PulseAudio by creating a `SinkController` for audio playback devices and apps or a `SourceController` for audio recording devices and apps.
```rust
// Simple application that lists all playback devices and their status
// See examples/change_device_vol.rs for a more complete example
extern crate pulsectl;
use std::io;
use pulsectl::controllers::SinkController;
use pulsectl::controllers::DeviceControl;
fn main() {
// create handler that calls functions on playback devices and apps
let mut handler = SinkController::create();
let devices = handler
.list_devices()
.expect("Could not get list of playback devices");
println!("Playback Devices");
for dev in devices.clone() {
println!(
"[{}] {}, [Volume: {}]",
dev.index,
dev.description.as_ref().unwrap(),
dev.volume.print()
);
}
}
```

View File

@@ -0,0 +1,34 @@
extern crate pulsectl;
use std::io;
use pulsectl::controllers::DeviceControl;
use pulsectl::controllers::SinkController;
fn main() {
// create handler that calls functions on playback devices and apps
let mut handler = SinkController::create().unwrap();
let devices = handler
.list_devices()
.expect("Could not get list of playback devices");
println!("Playback Devices");
for dev in devices.clone() {
println!(
"[{}] {}, [Volume: {}]",
dev.index,
dev.description.as_ref().unwrap(),
dev.volume.print()
);
}
let mut selection = String::new();
io::stdin()
.read_line(&mut selection)
.expect("error: unable to read user input");
for dev in devices.clone() {
if let true = selection.trim() == dev.index.to_string() {
handler.increase_device_volume_by_percent(dev.index, 0.05);
}
}
}

View File

@@ -0,0 +1,51 @@
use std::fmt;
use crate::PulseCtlError;
/// if the error occurs within the Mainloop, we bubble up the error with
/// this conversion
impl From<PulseCtlError> for ControllerError {
fn from(error: super::errors::PulseCtlError) -> Self {
ControllerError {
error: ControllerErrorType::PulseCtlError,
message: format!("{:?}", error),
}
}
}
impl fmt::Debug for ControllerError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut error_string = String::new();
match self.error {
ControllerErrorType::PulseCtlError => {
error_string.push_str("PulseCtlError");
}
ControllerErrorType::GetInfoError => {
error_string.push_str("GetInfoError");
}
}
write!(f, "[{}]: {}", error_string, self.message)
}
}
pub(crate) enum ControllerErrorType {
PulseCtlError,
GetInfoError,
}
/// Error thrown while fetching data from pulseaudio,
/// has two variants: PulseCtlError for when PulseAudio returns an error code
/// and GetInfoError when a request for data fails for whatever reason
pub struct ControllerError {
error: ControllerErrorType,
message: String,
}
impl ControllerError {
pub(crate) fn new(err: ControllerErrorType, msg: &str) -> Self {
ControllerError {
error: err,
message: msg.to_string(),
}
}
}

View File

@@ -0,0 +1,595 @@
/// Source = microphone etc. something that takes in audio
/// Source Output = application consuming that audio
///
/// Sink = headphones etc. something that plays out audio
/// Sink Input = application producing that audio
/// When you create a `SinkController`, you are working with audio playback devices and applications
/// if you want to manipulate recording devices such as microphone volume,
/// you'll need to use a `SourceController`. Both of these implement the same api, defined by
/// the traits DeviceControl and AppControl
use std::cell::RefCell;
use std::clone::Clone;
use std::rc::Rc;
use pulse::{
callbacks::ListResult,
context::introspect,
volume::{ChannelVolumes, Volume},
};
use errors::{ControllerError, ControllerErrorType::*};
use types::{ApplicationInfo, DeviceInfo, ServerInfo};
use crate::Handler;
pub(crate) mod errors;
pub mod types;
pub trait DeviceControl<T> {
fn get_default_device(&mut self) -> Result<T, ControllerError>;
fn set_default_device(&mut self, name: &str) -> Result<bool, ControllerError>;
fn list_devices(&mut self) -> Result<Vec<T>, ControllerError>;
fn get_device_by_index(&mut self, index: u32) -> Result<T, ControllerError>;
fn get_device_by_name(&mut self, name: &str) -> Result<T, ControllerError>;
fn set_device_volume_by_index(&mut self, index: u32, volume: &ChannelVolumes);
fn set_device_volume_by_name(&mut self, name: &str, volume: &ChannelVolumes);
fn increase_device_volume_by_percent(&mut self, index: u32, delta: f64);
fn decrease_device_volume_by_percent(&mut self, index: u32, delta: f64);
}
pub trait AppControl<T> {
fn list_applications(&mut self) -> Result<Vec<T>, ControllerError>;
fn get_app_by_index(&mut self, index: u32) -> Result<T, ControllerError>;
fn increase_app_volume_by_percent(&mut self, index: u32, delta: f64);
fn decrease_app_volume_by_percent(&mut self, index: u32, delta: f64);
fn move_app_by_index(
&mut self,
stream_index: u32,
device_index: u32,
) -> Result<bool, ControllerError>;
fn move_app_by_name(
&mut self,
stream_index: u32,
device_name: &str,
) -> Result<bool, ControllerError>;
fn set_app_mute(&mut self, index: u32, mute: bool) -> Result<bool, ControllerError>;
}
fn volume_from_percent(volume: f64) -> f64 {
(volume * 100.0) * (f64::from(pulse::volume::VOLUME_NORM.0) / 100.0)
}
pub struct SinkController {
pub handler: Handler,
}
impl SinkController {
pub fn create() -> Result<Self, ControllerError> {
let handler = Handler::connect("SinkController")?;
Ok(SinkController { handler })
}
pub fn get_server_info(&mut self) -> Result<ServerInfo, ControllerError> {
let server = Rc::new(RefCell::new(Some(None)));
let server_ref = server.clone();
let op = self.handler.introspect.get_server_info(move |res| {
server_ref
.borrow_mut()
.as_mut()
.unwrap()
.replace(res.into());
});
self.handler.wait_for_operation(op)?;
let mut result = server.borrow_mut();
result.take().unwrap().ok_or(ControllerError::new(
GetInfoError,
"Error getting information about the server",
))
}
}
impl DeviceControl<DeviceInfo> for SinkController {
fn get_default_device(&mut self) -> Result<DeviceInfo, ControllerError> {
let server_info = self.get_server_info();
match server_info {
Ok(info) => self.get_device_by_name(info.default_sink_name.unwrap().as_ref()),
Err(e) => Err(e),
}
}
fn set_default_device(&mut self, name: &str) -> Result<bool, ControllerError> {
let success = Rc::new(RefCell::new(false));
let success_ref = success.clone();
let op = self
.handler
.context
.borrow_mut()
.set_default_sink(name, move |res| success_ref.borrow_mut().clone_from(&res));
self.handler.wait_for_operation(op)?;
let result = success.borrow_mut().clone();
Ok(result)
}
fn list_devices(&mut self) -> Result<Vec<DeviceInfo>, ControllerError> {
let list = Rc::new(RefCell::new(Some(Vec::new())));
let list_ref = list.clone();
let op = self.handler.introspect.get_sink_info_list(
move |sink_list: ListResult<&introspect::SinkInfo>| {
if let ListResult::Item(item) = sink_list {
list_ref.borrow_mut().as_mut().unwrap().push(item.into());
}
},
);
self.handler.wait_for_operation(op)?;
let mut result = list.borrow_mut();
result.take().ok_or(ControllerError::new(
GetInfoError,
"Error getting device list",
))
}
fn get_device_by_index(&mut self, index: u32) -> Result<DeviceInfo, ControllerError> {
let device = Rc::new(RefCell::new(Some(None)));
let dev_ref = device.clone();
let op = self.handler.introspect.get_sink_info_by_index(
index,
move |sink_list: ListResult<&introspect::SinkInfo>| {
if let ListResult::Item(item) = sink_list {
dev_ref.borrow_mut().as_mut().unwrap().replace(item.into());
}
},
);
self.handler.wait_for_operation(op)?;
let mut result = device.borrow_mut();
result.take().unwrap().ok_or(ControllerError::new(
GetInfoError,
"Error getting requested device",
))
}
fn get_device_by_name(&mut self, name: &str) -> Result<DeviceInfo, ControllerError> {
let device = Rc::new(RefCell::new(Some(None)));
let dev_ref = device.clone();
let op = self.handler.introspect.get_sink_info_by_name(
name,
move |sink_list: ListResult<&introspect::SinkInfo>| {
if let ListResult::Item(item) = sink_list {
dev_ref.borrow_mut().as_mut().unwrap().replace(item.into());
}
},
);
self.handler.wait_for_operation(op)?;
let mut result = device.borrow_mut();
result.take().unwrap().ok_or(ControllerError::new(
GetInfoError,
"Error getting requested device",
))
}
fn set_device_volume_by_index(&mut self, index: u32, volume: &ChannelVolumes) {
let op = self
.handler
.introspect
.set_sink_volume_by_index(index, volume, None);
self.handler.wait_for_operation(op).ok();
}
fn set_device_volume_by_name(&mut self, name: &str, volume: &ChannelVolumes) {
let op = self
.handler
.introspect
.set_sink_volume_by_name(name, volume, None);
self.handler.wait_for_operation(op).ok();
}
fn increase_device_volume_by_percent(&mut self, index: u32, delta: f64) {
if let Ok(mut dev_ref) = self.get_device_by_index(index) {
let new_vol = Volume::from(Volume(volume_from_percent(delta) as u32));
if let Some(volumes) = dev_ref.volume.increase(new_vol) {
let op = self
.handler
.introspect
.set_sink_volume_by_index(index, &volumes, None);
self.handler.wait_for_operation(op).ok();
}
}
}
fn decrease_device_volume_by_percent(&mut self, index: u32, delta: f64) {
if let Ok(mut dev_ref) = self.get_device_by_index(index) {
let new_vol = Volume::from(Volume(volume_from_percent(delta) as u32));
if let Some(volumes) = dev_ref.volume.decrease(new_vol) {
let op = self
.handler
.introspect
.set_sink_volume_by_index(index, &volumes, None);
self.handler.wait_for_operation(op).ok();
}
}
}
}
impl AppControl<ApplicationInfo> for SinkController {
fn list_applications(&mut self) -> Result<Vec<ApplicationInfo>, ControllerError> {
let list = Rc::new(RefCell::new(Some(Vec::new())));
let list_ref = list.clone();
let op = self.handler.introspect.get_sink_input_info_list(
move |sink_list: ListResult<&introspect::SinkInputInfo>| {
if let ListResult::Item(item) = sink_list {
list_ref.borrow_mut().as_mut().unwrap().push(item.into());
}
},
);
self.handler.wait_for_operation(op)?;
let mut result = list.borrow_mut();
result.take().ok_or(ControllerError::new(
GetInfoError,
"Error getting application list",
))
}
fn get_app_by_index(&mut self, index: u32) -> Result<ApplicationInfo, ControllerError> {
let app = Rc::new(RefCell::new(Some(None)));
let app_ref = app.clone();
let op = self.handler.introspect.get_sink_input_info(
index,
move |sink_list: ListResult<&introspect::SinkInputInfo>| {
if let ListResult::Item(item) = sink_list {
app_ref.borrow_mut().as_mut().unwrap().replace(item.into());
}
},
);
self.handler.wait_for_operation(op)?;
let mut result = app.borrow_mut();
result.take().unwrap().ok_or(ControllerError::new(
GetInfoError,
"Error getting requested app",
))
}
fn increase_app_volume_by_percent(&mut self, index: u32, delta: f64) {
if let Ok(mut app_ref) = self.get_app_by_index(index) {
let new_vol = Volume::from(Volume(volume_from_percent(delta) as u32));
if let Some(volumes) = app_ref.volume.increase(new_vol) {
let op = self
.handler
.introspect
.set_sink_input_volume(index, &volumes, None);
self.handler.wait_for_operation(op).ok();
}
}
}
fn decrease_app_volume_by_percent(&mut self, index: u32, delta: f64) {
if let Ok(mut app_ref) = self.get_app_by_index(index) {
let new_vol = Volume::from(Volume(volume_from_percent(delta) as u32));
if let Some(volumes) = app_ref.volume.decrease(new_vol) {
let op = self
.handler
.introspect
.set_sink_input_volume(index, &volumes, None);
self.handler.wait_for_operation(op).ok();
}
}
}
fn move_app_by_index(
&mut self,
stream_index: u32,
device_index: u32,
) -> Result<bool, ControllerError> {
let success = Rc::new(RefCell::new(false));
let success_ref = success.clone();
let op = self.handler.introspect.move_sink_input_by_index(
stream_index,
device_index,
Some(Box::new(move |res| {
success_ref.borrow_mut().clone_from(&res)
})),
);
self.handler.wait_for_operation(op)?;
let result = success.borrow_mut().clone();
Ok(result)
}
fn move_app_by_name(
&mut self,
stream_index: u32,
device_name: &str,
) -> Result<bool, ControllerError> {
let success = Rc::new(RefCell::new(false));
let success_ref = success.clone();
let op = self.handler.introspect.move_sink_input_by_name(
stream_index,
device_name,
Some(Box::new(move |res| {
success_ref.borrow_mut().clone_from(&res)
})),
);
self.handler.wait_for_operation(op)?;
let result = success.borrow_mut().clone();
Ok(result)
}
fn set_app_mute(&mut self, index: u32, mute: bool) -> Result<bool, ControllerError> {
let success = Rc::new(RefCell::new(false));
let success_ref = success.clone();
let op = self.handler.introspect.set_sink_input_mute(
index,
mute,
Some(Box::new(move |res| {
success_ref.borrow_mut().clone_from(&res)
})),
);
self.handler.wait_for_operation(op)?;
let result = success.borrow_mut().clone();
Ok(result)
}
}
pub struct SourceController {
pub handler: Handler,
}
impl SourceController {
pub fn create() -> Result<Self, ControllerError> {
let handler = Handler::connect("SourceController")?;
Ok(SourceController { handler })
}
pub fn get_server_info(&mut self) -> Result<ServerInfo, ControllerError> {
let server = Rc::new(RefCell::new(Some(None)));
let server_ref = server.clone();
let op = self.handler.introspect.get_server_info(move |res| {
server_ref
.borrow_mut()
.as_mut()
.unwrap()
.replace(res.into());
});
self.handler.wait_for_operation(op)?;
let mut result = server.borrow_mut();
result.take().unwrap().ok_or(ControllerError::new(
GetInfoError,
"Error getting application list",
))
}
}
impl DeviceControl<DeviceInfo> for SourceController {
fn get_default_device(&mut self) -> Result<DeviceInfo, ControllerError> {
let server_info = self.get_server_info();
match server_info {
Ok(info) => self.get_device_by_name(info.default_sink_name.unwrap().as_ref()),
Err(e) => Err(e),
}
}
fn set_default_device(&mut self, name: &str) -> Result<bool, ControllerError> {
let success = Rc::new(RefCell::new(false));
let success_ref = success.clone();
let op = self
.handler
.context
.borrow_mut()
.set_default_source(name, move |res| success_ref.borrow_mut().clone_from(&res));
self.handler.wait_for_operation(op)?;
let result = success.borrow_mut().clone();
Ok(result)
}
fn list_devices(&mut self) -> Result<Vec<DeviceInfo>, ControllerError> {
let list = Rc::new(RefCell::new(Some(Vec::new())));
let list_ref = list.clone();
let op = self.handler.introspect.get_source_info_list(
move |sink_list: ListResult<&introspect::SourceInfo>| {
if let ListResult::Item(item) = sink_list {
list_ref.borrow_mut().as_mut().unwrap().push(item.into());
}
},
);
self.handler.wait_for_operation(op)?;
let mut result = list.borrow_mut();
result.take().ok_or(ControllerError::new(
GetInfoError,
"Error getting application list",
))
}
fn get_device_by_index(&mut self, index: u32) -> Result<DeviceInfo, ControllerError> {
let device = Rc::new(RefCell::new(Some(None)));
let dev_ref = device.clone();
let op = self.handler.introspect.get_source_info_by_index(
index,
move |sink_list: ListResult<&introspect::SourceInfo>| {
if let ListResult::Item(item) = sink_list {
dev_ref.borrow_mut().as_mut().unwrap().replace(item.into());
}
},
);
self.handler.wait_for_operation(op)?;
let mut result = device.borrow_mut();
result.take().unwrap().ok_or(ControllerError::new(
GetInfoError,
"Error getting application list",
))
}
fn get_device_by_name(&mut self, name: &str) -> Result<DeviceInfo, ControllerError> {
let device = Rc::new(RefCell::new(Some(None)));
let dev_ref = device.clone();
let op = self.handler.introspect.get_source_info_by_name(
name,
move |sink_list: ListResult<&introspect::SourceInfo>| {
if let ListResult::Item(item) = sink_list {
dev_ref.borrow_mut().as_mut().unwrap().replace(item.into());
}
},
);
self.handler.wait_for_operation(op)?;
let mut result = device.borrow_mut();
result.take().unwrap().ok_or(ControllerError::new(
GetInfoError,
"Error getting application list",
))
}
fn set_device_volume_by_index(&mut self, index: u32, volume: &ChannelVolumes) {
let op = self
.handler
.introspect
.set_source_volume_by_index(index, volume, None);
self.handler.wait_for_operation(op).ok();
}
fn set_device_volume_by_name(&mut self, name: &str, volume: &ChannelVolumes) {
let op = self
.handler
.introspect
.set_source_volume_by_name(name, volume, None);
self.handler.wait_for_operation(op).ok();
}
fn increase_device_volume_by_percent(&mut self, index: u32, delta: f64) {
if let Ok(mut dev_ref) = self.get_device_by_index(index) {
let new_vol = Volume::from(Volume(volume_from_percent(delta) as u32));
if let Some(volumes) = dev_ref.volume.increase(new_vol) {
let op = self
.handler
.introspect
.set_source_volume_by_index(index, &volumes, None);
self.handler.wait_for_operation(op).ok();
}
}
}
fn decrease_device_volume_by_percent(&mut self, index: u32, delta: f64) {
if let Ok(mut dev_ref) = self.get_device_by_index(index) {
let new_vol = Volume::from(Volume(volume_from_percent(delta) as u32));
if let Some(volumes) = dev_ref.volume.decrease(new_vol) {
let op = self
.handler
.introspect
.set_source_volume_by_index(index, &volumes, None);
self.handler.wait_for_operation(op).ok();
}
}
}
}
impl AppControl<ApplicationInfo> for SourceController {
fn list_applications(&mut self) -> Result<Vec<ApplicationInfo>, ControllerError> {
let list = Rc::new(RefCell::new(Some(Vec::new())));
let list_ref = list.clone();
let op = self.handler.introspect.get_source_output_info_list(
move |sink_list: ListResult<&introspect::SourceOutputInfo>| {
if let ListResult::Item(item) = sink_list {
list_ref.borrow_mut().as_mut().unwrap().push(item.into());
}
},
);
self.handler.wait_for_operation(op)?;
let mut result = list.borrow_mut();
result.take().ok_or(ControllerError::new(
GetInfoError,
"Error getting application list",
))
}
fn get_app_by_index(&mut self, index: u32) -> Result<ApplicationInfo, ControllerError> {
let app = Rc::new(RefCell::new(Some(None)));
let app_ref = app.clone();
let op = self.handler.introspect.get_source_output_info(
index,
move |sink_list: ListResult<&introspect::SourceOutputInfo>| {
if let ListResult::Item(item) = sink_list {
app_ref.borrow_mut().as_mut().unwrap().replace(item.into());
}
},
);
self.handler.wait_for_operation(op)?;
let mut result = app.borrow_mut();
result.take().unwrap().ok_or(ControllerError::new(
GetInfoError,
"Error getting application list",
))
}
fn increase_app_volume_by_percent(&mut self, index: u32, delta: f64) {
if let Ok(mut app_ref) = self.get_app_by_index(index) {
let new_vol = Volume::from(Volume(volume_from_percent(delta) as u32));
if let Some(volumes) = app_ref.volume.increase(new_vol) {
let op = self
.handler
.introspect
.set_source_output_volume(index, &volumes, None);
self.handler.wait_for_operation(op).ok();
}
}
}
fn decrease_app_volume_by_percent(&mut self, index: u32, delta: f64) {
if let Ok(mut app_ref) = self.get_app_by_index(index) {
let new_vol = Volume::from(Volume(volume_from_percent(delta) as u32));
if let Some(volumes) = app_ref.volume.decrease(new_vol) {
let op = self
.handler
.introspect
.set_source_output_volume(index, &volumes, None);
self.handler.wait_for_operation(op).ok();
}
}
}
fn move_app_by_index(
&mut self,
stream_index: u32,
device_index: u32,
) -> Result<bool, ControllerError> {
let success = Rc::new(RefCell::new(false));
let success_ref = success.clone();
let op = self.handler.introspect.move_source_output_by_index(
stream_index,
device_index,
Some(Box::new(move |res| {
success_ref.borrow_mut().clone_from(&res)
})),
);
self.handler.wait_for_operation(op)?;
let result = success.borrow_mut().clone();
Ok(result)
}
fn move_app_by_name(
&mut self,
stream_index: u32,
device_name: &str,
) -> Result<bool, ControllerError> {
let success = Rc::new(RefCell::new(false));
let success_ref = success.clone();
let op = self.handler.introspect.move_source_output_by_name(
stream_index,
device_name,
Some(Box::new(move |res| {
success_ref.borrow_mut().clone_from(&res)
})),
);
self.handler.wait_for_operation(op)?;
let result = success.borrow_mut().clone();
Ok(result)
}
fn set_app_mute(&mut self, index: u32, mute: bool) -> Result<bool, ControllerError> {
let success = Rc::new(RefCell::new(false));
let success_ref = success.clone();
let op = self.handler.introspect.set_source_mute_by_index(
index,
mute,
Some(Box::new(move |res| {
success_ref.borrow_mut().clone_from(&res)
})),
);
self.handler.wait_for_operation(op)?;
let result = success.borrow_mut().clone();
Ok(result)
}
}

View File

@@ -0,0 +1,354 @@
use pulse::{
channelmap,
context::introspect,
def,
def::PortAvailable,
format,
proplist::Proplist,
sample,
time::MicroSeconds,
volume::{ChannelVolumes, Volume},
};
/// These structs are direct representations of what libpulse_binding gives
/// created to be copyable / cloneable for use in and out of callbacks
/// This is a wrapper around SinkPortInfo and SourcePortInfo as they have the same members
#[derive(Clone)]
pub struct DevicePortInfo {
/// Name of the sink.
pub name: Option<String>,
/// Description of this sink.
pub description: Option<String>,
/// The higher this value is, the more useful this port is as a default.
pub priority: u32,
/// A flag indicating availability status of this port.
pub available: PortAvailable,
}
impl<'a> From<&'a Box<introspect::SinkPortInfo<'a>>> for DevicePortInfo {
fn from(item: &'a Box<introspect::SinkPortInfo<'a>>) -> Self {
DevicePortInfo {
name: item.name.as_ref().map(|cow| cow.to_string()),
description: item.description.as_ref().map(|cow| cow.to_string()),
priority: item.priority,
available: item.available,
}
}
}
impl<'a> From<&'a introspect::SinkPortInfo<'a>> for DevicePortInfo {
fn from(item: &'a introspect::SinkPortInfo<'a>) -> Self {
DevicePortInfo {
name: item.name.as_ref().map(|cow| cow.to_string()),
description: item.description.as_ref().map(|cow| cow.to_string()),
priority: item.priority,
available: item.available,
}
}
}
impl<'a> From<&'a Box<introspect::SourcePortInfo<'a>>> for DevicePortInfo {
fn from(item: &'a Box<introspect::SourcePortInfo<'a>>) -> Self {
DevicePortInfo {
name: item.name.as_ref().map(|cow| cow.to_string()),
description: item.description.as_ref().map(|cow| cow.to_string()),
priority: item.priority,
available: item.available,
}
}
}
impl<'a> From<&'a introspect::SourcePortInfo<'a>> for DevicePortInfo {
fn from(item: &'a introspect::SourcePortInfo<'a>) -> Self {
DevicePortInfo {
name: item.name.as_ref().map(|cow| cow.to_string()),
description: item.description.as_ref().map(|cow| cow.to_string()),
priority: item.priority,
available: item.available,
}
}
}
/// This is a wrapper around SinkState and SourceState as they have the same values
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum DevState {
/// This state is used when the server does not support sink state introspection.
Invalid = -1,
/// Running, sink is playing and used by at least one non-corked sink-input.
Running = 0,
/// When idle, the sink is playing but there is no non-corked sink-input attached to it.
Idle = 1,
/// When suspended, actual sink access can be closed, for instance.
Suspended = 2,
}
impl<'a> From<def::SourceState> for DevState {
fn from(s: def::SourceState) -> Self {
match s {
def::SourceState::Idle => DevState::Idle,
def::SourceState::Invalid => DevState::Invalid,
def::SourceState::Running => DevState::Running,
def::SourceState::Suspended => DevState::Suspended,
}
}
}
impl<'a> From<def::SinkState> for DevState {
fn from(s: def::SinkState) -> Self {
match s {
def::SinkState::Idle => DevState::Idle,
def::SinkState::Invalid => DevState::Invalid,
def::SinkState::Running => DevState::Running,
def::SinkState::Suspended => DevState::Suspended,
}
}
}
#[derive(Clone)]
pub enum Flags {
SourceFLags(def::SourceFlagSet),
SinkFlags(def::SinkFlagSet),
}
#[derive(Clone)]
pub struct DeviceInfo {
/// Index of the sink.
pub index: u32,
/// Name of the sink.
pub name: Option<String>,
/// Description of this sink.
pub description: Option<String>,
/// Sample spec of this sink.
pub sample_spec: sample::Spec,
/// Channel map.
pub channel_map: channelmap::Map,
/// Index of the owning module of this sink, or `None` if is invalid.
pub owner_module: Option<u32>,
/// Volume of the sink.
pub volume: ChannelVolumes,
/// Mute switch of the sink.
pub mute: bool,
/// Index of the monitor source connected to this sink.
pub monitor: Option<u32>,
/// The name of the monitor source.
pub monitor_name: Option<String>,
/// Length of queued audio in the output buffer.
pub latency: MicroSeconds,
/// Driver name.
pub driver: Option<String>,
/// Flags.
pub flags: Flags,
/// Property list.
pub proplist: Proplist,
/// The latency this device has been configured to.
pub configured_latency: MicroSeconds,
/// Some kind of “base” volume that refers to unamplified/unattenuated volume in the context of
/// the output device.
pub base_volume: Volume,
/// State.
pub state: DevState,
/// Number of volume steps for sinks which do not support arbitrary volumes.
pub n_volume_steps: u32,
/// Card index, or `None` if invalid.
pub card: Option<u32>,
/// Set of available ports.
pub ports: Vec<DevicePortInfo>,
// Pointer to active port in the set, or None.
pub active_port: Option<DevicePortInfo>,
/// Set of formats supported by the sink.
pub formats: Vec<format::Info>,
}
impl<'a> From<&'a introspect::SinkInfo<'a>> for DeviceInfo {
fn from(item: &'a introspect::SinkInfo<'a>) -> Self {
DeviceInfo {
name: item.name.as_ref().map(|cow| cow.to_string()),
index: item.index,
description: item.description.as_ref().map(|cow| cow.to_string()),
sample_spec: item.sample_spec,
channel_map: item.channel_map,
owner_module: item.owner_module,
volume: item.volume,
mute: item.mute,
monitor: Some(item.monitor_source),
monitor_name: item.monitor_source_name.as_ref().map(|cow| cow.to_string()),
latency: item.latency,
driver: item.driver.as_ref().map(|cow| cow.to_string()),
flags: Flags::SinkFlags(item.flags),
proplist: item.proplist.clone(),
configured_latency: item.configured_latency,
base_volume: item.base_volume,
state: DevState::from(item.state),
n_volume_steps: item.n_volume_steps,
card: item.card,
ports: item.ports.iter().map(From::from).collect(),
active_port: item.active_port.as_ref().map(From::from),
formats: item.formats.clone(),
}
}
}
impl<'a> From<&'a introspect::SourceInfo<'a>> for DeviceInfo {
fn from(item: &'a introspect::SourceInfo<'a>) -> Self {
DeviceInfo {
name: item.name.as_ref().map(|cow| cow.to_string()),
index: item.index,
description: item.description.as_ref().map(|cow| cow.to_string()),
sample_spec: item.sample_spec,
channel_map: item.channel_map,
owner_module: item.owner_module,
volume: item.volume,
mute: item.mute,
monitor: item.monitor_of_sink,
monitor_name: item
.monitor_of_sink_name
.as_ref()
.map(|cow| cow.to_string()),
latency: item.latency,
driver: item.driver.as_ref().map(|cow| cow.to_string()),
flags: Flags::SourceFLags(item.flags),
proplist: item.proplist.clone(),
configured_latency: item.configured_latency,
base_volume: item.base_volume,
state: DevState::from(item.state),
n_volume_steps: item.n_volume_steps,
card: item.card,
ports: item.ports.iter().map(From::from).collect(),
active_port: item.active_port.as_ref().map(From::from),
formats: item.formats.clone(),
}
}
}
#[derive(Clone)]
pub struct ApplicationInfo {
/// Index of the sink input.
pub index: u32,
/// Name of the sink input.
pub name: Option<String>,
/// Index of the module this sink input belongs to, or `None` when it does not belong to any
/// module.
pub owner_module: Option<u32>,
/// Index of the client this sink input belongs to, or invalid when it does not belong to any
/// client.
pub client: Option<u32>,
/// Index of the connected sink/source.
pub connection_id: u32,
/// The sample specification of the sink input.
pub sample_spec: sample::Spec,
/// Channel map.
pub channel_map: channelmap::Map,
/// The volume of this sink input.
pub volume: ChannelVolumes,
/// Latency due to buffering in sink input, see
/// [`def::TimingInfo`](../../def/struct.TimingInfo.html) for details.
pub buffer_usec: MicroSeconds,
/// Latency of the sink device, see
/// [`def::TimingInfo`](../../def/struct.TimingInfo.html) for details.
pub connection_usec: MicroSeconds,
/// The resampling method used by this sink input.
pub resample_method: Option<String>,
/// Driver name.
pub driver: Option<String>,
/// Stream muted.
pub mute: bool,
/// Property list.
pub proplist: Proplist,
/// Stream corked.
pub corked: bool,
/// Stream has volume. If not set, then the meaning of this structs volume member is unspecified.
pub has_volume: bool,
/// The volume can be set. If not set, the volume can still change even though clients cant
/// control the volume.
pub volume_writable: bool,
/// Stream format information.
pub format: format::Info,
}
impl<'a> From<&'a introspect::SinkInputInfo<'a>> for ApplicationInfo {
fn from(item: &'a introspect::SinkInputInfo<'a>) -> Self {
ApplicationInfo {
index: item.index,
name: item.name.as_ref().map(|cow| cow.to_string()),
owner_module: item.owner_module,
client: item.client,
connection_id: item.sink,
sample_spec: item.sample_spec,
channel_map: item.channel_map,
volume: item.volume,
buffer_usec: item.buffer_usec,
connection_usec: item.sink_usec,
resample_method: item.resample_method.as_ref().map(|cow| cow.to_string()),
driver: item.driver.as_ref().map(|cow| cow.to_string()),
mute: item.mute,
proplist: item.proplist.clone(),
corked: item.corked,
has_volume: item.has_volume,
volume_writable: item.volume_writable,
format: item.format.clone(),
}
}
}
impl<'a> From<&'a introspect::SourceOutputInfo<'a>> for ApplicationInfo {
fn from(item: &'a introspect::SourceOutputInfo<'a>) -> Self {
ApplicationInfo {
index: item.index,
name: item.name.as_ref().map(|cow| cow.to_string()),
owner_module: item.owner_module,
client: item.client,
connection_id: item.source,
sample_spec: item.sample_spec,
channel_map: item.channel_map,
volume: item.volume,
buffer_usec: item.buffer_usec,
connection_usec: item.source_usec,
resample_method: item.resample_method.as_ref().map(|cow| cow.to_string()),
driver: item.driver.as_ref().map(|cow| cow.to_string()),
mute: item.mute,
proplist: item.proplist.clone(),
corked: item.corked,
has_volume: item.has_volume,
volume_writable: item.volume_writable,
format: item.format.clone(),
}
}
}
pub struct ServerInfo {
/// User name of the daemon process.
pub user_name: Option<String>,
/// Host name the daemon is running on.
pub host_name: Option<String>,
/// Version string of the daemon.
pub server_version: Option<String>,
/// Server package name (usually “pulseaudio”).
pub server_name: Option<String>,
/// Default sample specification.
pub sample_spec: sample::Spec,
/// Name of default sink.
pub default_sink_name: Option<String>,
/// Name of default source.
pub default_source_name: Option<String>,
/// A random cookie for identifying this instance of PulseAudio.
pub cookie: u32,
/// Default channel map.
pub channel_map: channelmap::Map,
}
impl<'a> From<&'a introspect::ServerInfo<'a>> for ServerInfo {
fn from(info: &'a introspect::ServerInfo<'a>) -> Self {
ServerInfo {
user_name: info.user_name.as_ref().map(|cow| cow.to_string()),
host_name: info.host_name.as_ref().map(|cow| cow.to_string()),
server_version: info.server_version.as_ref().map(|cow| cow.to_string()),
server_name: info.server_name.as_ref().map(|cow| cow.to_string()),
sample_spec: info.sample_spec,
default_sink_name: info.default_sink_name.as_ref().map(|cow| cow.to_string()),
default_source_name: info.default_source_name.as_ref().map(|cow| cow.to_string()),
cookie: info.cookie,
channel_map: info.channel_map,
}
}
}

View File

@@ -0,0 +1,54 @@
use std::fmt;
use pulse::error::{PAErr};
impl From<PAErr> for PulseCtlError {
fn from(error: PAErr) -> Self {
PulseCtlError {
error: PulseCtlErrorType::PulseAudioError,
message: format!("PulseAudio returned error: {}", error.to_string().unwrap_or("Unknown".to_owned())),
}
}
}
impl fmt::Debug for PulseCtlError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut error_string = String::new();
match self.error {
PulseCtlErrorType::ConnectError => {
error_string.push_str("ConnectError");
}
PulseCtlErrorType::OperationError => {
error_string.push_str("OperationError");
}
PulseCtlErrorType::PulseAudioError => {
error_string.push_str("PulseAudioError");
}
}
write!(f, "[{}]: {}", error_string, self.message)
}
}
pub(crate) enum PulseCtlErrorType {
ConnectError,
OperationError,
PulseAudioError,
}
/// Error thrown when PulseAudio throws an error code, there are 3 variants
/// `PulseCtlErrorType::ConnectError` when there's an error establishing a connection
/// `PulseCtlErrorType::OperationError` when the requested operation quis unexpecdatly or is cancelled
/// `PulseCtlErrorType::PulseAudioError` when PulseAudio returns an error code in any circumstance
pub struct PulseCtlError {
error: PulseCtlErrorType,
message: String,
}
impl PulseCtlError {
pub(crate) fn new(err: PulseCtlErrorType, msg: &str) -> Self {
PulseCtlError {
error: err,
message: msg.to_string(),
}
}
}

166
libs/pulsectl/src/lib.rs Normal file
View File

@@ -0,0 +1,166 @@
/// `pulsectl` is a high level wrapper around the PulseAudio bindings supplied by
/// `libpulse_binding`. It provides simple access to sinks, inputs, sources and outputs allowing
/// one to write audio control programs with ease.
///
/// ## Quick Example
///
/// The following example demonstrates listing all of the playback devices currently connected
///
/// See examples/change_device_vol.rs for a more complete example
/// ```no_run
/// extern crate pulsectl;
///
/// use std::io;
///
/// use pulsectl::controllers::SinkController;
/// use pulsectl::controllers::DeviceControl;
/// fn main() {
/// // create handler that calls functions on playback devices and apps
/// let mut handler = SinkController::create().unwrap();
/// let devices = handler
/// .list_devices()
/// .expect("Could not get list of playback devices");
///
/// println!("Playback Devices");
/// for dev in devices.clone() {
/// println!(
/// "[{}] {}, Volume: {}",
/// dev.index,
/// dev.description.as_ref().unwrap(),
/// dev.volume.print()
/// );
/// }
/// }
/// ```
extern crate libpulse_binding as pulse;
use std::cell::RefCell;
use std::ops::Deref;
use std::rc::Rc;
use pulse::{
context::{introspect, Context},
mainloop::standard::{IterateResult, Mainloop},
operation::{Operation, State},
proplist::Proplist,
};
use crate::errors::{PulseCtlError, PulseCtlErrorType::*};
pub mod controllers;
mod errors;
pub struct Handler {
pub mainloop: Rc<RefCell<Mainloop>>,
pub context: Rc<RefCell<Context>>,
pub introspect: introspect::Introspector,
}
fn connect_error(err: &str) -> PulseCtlError {
PulseCtlError::new(ConnectError, err)
}
impl Handler {
pub fn connect(name: &str) -> Result<Handler, PulseCtlError> {
let mut proplist = Proplist::new().unwrap();
proplist
.set_str(pulse::proplist::properties::APPLICATION_NAME, name)
.unwrap();
let mainloop;
if let Some(m) = Mainloop::new() {
mainloop = Rc::new(RefCell::new(m));
} else {
return Err(connect_error("Failed to create mainloop"));
}
let context;
if let Some(c) =
Context::new_with_proplist(mainloop.borrow().deref(), "MainConn", &proplist)
{
context = Rc::new(RefCell::new(c));
} else {
return Err(connect_error("Failed to create new context"));
}
context
.borrow_mut()
.connect(None, pulse::context::flags::NOFLAGS, None)
.map_err(|_| connect_error("Failed to connect context"))?;
loop {
match mainloop.borrow_mut().iterate(false) {
IterateResult::Err(e) => {
eprintln!("iterate state was not success, quitting...");
return Err(e.into());
}
IterateResult::Success(_) => {}
IterateResult::Quit(_) => {
eprintln!("iterate state was not success, quitting...");
return Err(PulseCtlError::new(
ConnectError,
"Iterate state quit without an error",
));
}
}
match context.borrow().get_state() {
pulse::context::State::Ready => break,
pulse::context::State::Failed | pulse::context::State::Terminated => {
eprintln!("context state failed/terminated, quitting...");
return Err(PulseCtlError::new(
ConnectError,
"Context state failed/terminated without an error",
));
}
_ => {}
}
}
let introspect = context.borrow_mut().introspect();
Ok(Handler {
mainloop,
context,
introspect,
})
}
// loop until the passed operation is completed
pub fn wait_for_operation<G: ?Sized>(
&mut self,
op: Operation<G>,
) -> Result<(), errors::PulseCtlError> {
loop {
match self.mainloop.borrow_mut().iterate(false) {
IterateResult::Err(e) => return Err(e.into()),
IterateResult::Success(_) => {}
IterateResult::Quit(_) => {
return Err(PulseCtlError::new(
OperationError,
"Iterate state quit without an error",
));
}
}
match op.get_state() {
State::Done => {
break;
}
State::Running => {}
State::Cancelled => {
return Err(PulseCtlError::new(
OperationError,
"Operation cancelled without an error",
));
}
}
}
Ok(())
}
}
impl Drop for Handler {
fn drop(&mut self) {
self.context.borrow_mut().disconnect();
self.mainloop.borrow_mut().quit(pulse::def::Retval(0));
}
}

View File

@@ -9,9 +9,6 @@ license = "MIT"
authors = ["Ram <quadrupleslap@gmail.com>"]
edition = "2018"
[features]
wayland = ["gstreamer", "gstreamer-app", "gstreamer-video", "dbus", "tracing"]
[dependencies]
block = "0.1"
cfg-if = "1.0"
@@ -21,7 +18,7 @@ num_cpus = "1.13"
[dependencies.winapi]
version = "0.3"
default-features = true
features = ["dxgi", "dxgi1_2", "dxgi1_5", "d3d11", "winuser"]
features = ["dxgi", "dxgi1_2", "dxgi1_5", "d3d11"]
[dev-dependencies]
repng = "0.2"
@@ -32,11 +29,4 @@ quest = "0.3"
[build-dependencies]
target_build_utils = "0.3"
bindgen = "0.59"
[target.'cfg(target_os = "linux")'.dependencies]
dbus = { version = "0.9", optional = true }
tracing = { version = "0.1", optional = true }
gstreamer = { version = "0.16", optional = true }
gstreamer-app = { version = "0.16", features = ["v1_10"], optional = true }
gstreamer-video = { version = "0.16", optional = true }
bindgen = "0.53"

View File

@@ -1,5 +1,3 @@
Derived from https://github.com/quadrupleslap/scrap
# scrap
Scrap records your screen! At least it does if you're on Windows, macOS, or Linux.

View File

@@ -12,22 +12,26 @@ fn find_package(name: &str) -> Vec<PathBuf> {
target_arch = "x64".to_owned();
} else if target_arch == "aarch64" {
target_arch = "arm64".to_owned();
} else {
target_arch = "arm".to_owned();
}
let mut target = if target_os == "macos" {
let target = if target_os == "macos" {
"x64-osx".to_owned()
} else if target_os == "windows" {
"x64-windows-static".to_owned()
} else if target_os == "android" {
format!("{}-android-static", target_arch)
} else {
format!("{}-{}", target_arch, target_os)
"x64-linux".to_owned()
};
if target_arch == "x86" {
target = target.replace("x64", "x86");
}
println!("cargo:info={}", target);
path.push("installed");
path.push(target);
let lib = name.trim_start_matches("lib").to_string();
println!("{}", format!("cargo:rustc-link-lib=static={}", lib));
let mut lib = name.trim_start_matches("lib").to_string();
if lib == "vpx" && target_os == "windows" {
lib = format!("{}mt", lib);
}
println!("{}", format!("cargo:rustc-link-lib={}", lib));
println!(
"{}",
format!(
@@ -48,9 +52,9 @@ fn generate_bindings(
) {
let mut b = bindgen::builder()
.header(ffi_header.to_str().unwrap())
.allowlist_type("^[vV].*")
.allowlist_var("^[vV].*")
.allowlist_function("^[vV].*")
.whitelist_type("^[vV].*")
.whitelist_var("^[vV].*")
.whitelist_function("^[vV].*")
.rustified_enum("^v.*")
.trust_clang_mangling(false)
.layout_tests(false) // breaks 32/64-bit compat
@@ -89,7 +93,7 @@ fn main() {
// then set x64 to default by "rustup default stable-x86_64-pc-windows-msvc"
let target = target_build_utils::TargetInfo::new();
if target.unwrap().target_pointer_width() != "64" {
// panic!("Only support 64bit system");
panic!("Only support 64bit system");
}
env::remove_var("CARGO_CFG_TARGET_FEATURE");
env::set_var("CARGO_CFG_TARGET_FEATURE", "crt-static");

View File

@@ -23,10 +23,6 @@ fn record(i: usize) {
let one_second = Duration::new(1, 0);
let one_frame = one_second / 60;
for d in Display::all().unwrap() {
println!("{:?} {} {}", d.origin(), d.width(), d.height());
}
let display = get_display(i);
let mut capturer = Capturer::new(display, false).expect("Couldn't begin capture.");
let (w, h) = (capturer.width(), capturer.height());

View File

@@ -66,7 +66,7 @@ macro_rules! call_vpx {
macro_rules! call_vpx_ptr {
($x:expr) => {{
let result = unsafe { $x }; // original expression
let result_int = unsafe { std::mem::transmute::<_, isize>(result) };
let result_int = unsafe { std::mem::transmute::<_, i64>(result) };
if result_int == 0 {
return Err(Error::BadPtr(format!(
"errcode={} {}:{}:{}:{}",

View File

@@ -62,23 +62,13 @@ pub struct Display(dxgi::Display);
impl Display {
pub fn primary() -> io::Result<Display> {
// not implemented yet
Err(NotFound.into())
match dxgi::Displays::new()?.next() {
Some(inner) => Ok(Display(inner)),
None => Err(NotFound.into()),
}
}
pub fn all() -> io::Result<Vec<Display>> {
let tmp = Self::all_().unwrap_or(Default::default());
if tmp.is_empty() {
println!("Display got from gdi");
return Ok(dxgi::Displays::get_from_gdi()
.drain(..)
.map(Display)
.collect::<Vec<_>>());
}
Ok(tmp)
}
fn all_() -> io::Result<Vec<Display>> {
Ok(dxgi::Displays::new()?.map(Display).collect::<Vec<_>>())
}
@@ -102,12 +92,13 @@ impl Display {
self.0.is_online()
}
pub fn origin(&self) -> (i32, i32) {
self.0.origin()
pub fn origin(&self) -> (usize, usize) {
let o = self.0.origin();
(o.0 as usize, o.1 as usize)
}
// to-do: not found primary display api for dxgi
pub fn is_primary(&self) -> bool {
// https://docs.microsoft.com/en-us/windows/win32/api/wingdi/ns-wingdi-devmodea
self.origin() == (0, 0)
self.name() == Self::primary().unwrap().name()
}
}

View File

@@ -1,117 +0,0 @@
use crate::common::{
wayland,
x11::{self, Frame},
};
use std::io;
pub enum Capturer {
X11(x11::Capturer),
WAYLAND(wayland::Capturer),
}
impl Capturer {
pub fn new(display: Display, yuv: bool) -> io::Result<Capturer> {
Ok(match display {
Display::X11(d) => Capturer::X11(x11::Capturer::new(d, yuv)?),
Display::WAYLAND(d) => Capturer::WAYLAND(wayland::Capturer::new(d, yuv)?),
})
}
pub fn width(&self) -> usize {
match self {
Capturer::X11(d) => d.width(),
Capturer::WAYLAND(d) => d.width(),
}
}
pub fn height(&self) -> usize {
match self {
Capturer::X11(d) => d.height(),
Capturer::WAYLAND(d) => d.height(),
}
}
pub fn frame<'a>(&'a mut self, timeout_ms: u32) -> io::Result<Frame<'a>> {
match self {
Capturer::X11(d) => d.frame(timeout_ms),
Capturer::WAYLAND(d) => d.frame(timeout_ms),
}
}
}
pub enum Display {
X11(x11::Display),
WAYLAND(wayland::Display),
}
#[inline]
fn is_wayland() -> bool {
std::env::var("IS_WAYLAND").is_ok()
|| std::env::var("XDG_SESSION_TYPE") == Ok("wayland".to_owned())
}
impl Display {
pub fn primary() -> io::Result<Display> {
Ok(if is_wayland() {
Display::WAYLAND(wayland::Display::primary()?)
} else {
Display::X11(x11::Display::primary()?)
})
}
pub fn all() -> io::Result<Vec<Display>> {
Ok(if is_wayland() {
wayland::Display::all()?
.drain(..)
.map(|x| Display::WAYLAND(x))
.collect()
} else {
x11::Display::all()?
.drain(..)
.map(|x| Display::X11(x))
.collect()
})
}
pub fn width(&self) -> usize {
match self {
Display::X11(d) => d.width(),
Display::WAYLAND(d) => d.width(),
}
}
pub fn height(&self) -> usize {
match self {
Display::X11(d) => d.height(),
Display::WAYLAND(d) => d.height(),
}
}
pub fn origin(&self) -> (i32, i32) {
match self {
Display::X11(d) => d.origin(),
Display::WAYLAND(d) => d.origin(),
}
}
pub fn is_online(&self) -> bool {
match self {
Display::X11(d) => d.is_online(),
Display::WAYLAND(d) => d.is_online(),
}
}
pub fn is_primary(&self) -> bool {
match self {
Display::X11(d) => d.is_primary(),
Display::WAYLAND(d) => d.is_primary(),
}
}
pub fn name(&self) -> String {
match self {
Display::X11(d) => d.name(),
Display::WAYLAND(d) => d.name(),
}
}
}

View File

@@ -5,17 +5,8 @@ cfg_if! {
mod quartz;
pub use self::quartz::*;
} else if #[cfg(x11)] {
cfg_if! {
if #[cfg(feature="wayland")] {
mod linux;
mod wayland;
mod x11;
pub use self::linux::*;
} else {
mod x11;
pub use self::x11::*;
}
}
pub use self::x11::*;
} else if #[cfg(dxgi)] {
mod dxgi;
pub use self::dxgi::*;

View File

@@ -114,9 +114,9 @@ impl Display {
self.0.is_online()
}
pub fn origin(&self) -> (i32, i32) {
pub fn origin(&self) -> (usize, usize) {
let o = self.0.bounds().origin;
(o.x as _, o.y as _)
(o.x as usize, o.y as usize)
}
pub fn is_primary(&self) -> bool {

View File

@@ -1,81 +0,0 @@
use crate::common::x11::Frame;
use crate::wayland::{capturable::*, *};
use std::io;
pub struct Capturer(Display, Box<dyn Recorder>, bool, Vec<u8>);
fn map_err<E: ToString>(err: E) -> io::Error {
io::Error::new(io::ErrorKind::Other, err.to_string())
}
impl Capturer {
pub fn new(display: Display, yuv: bool) -> io::Result<Capturer> {
let r = display.0.recorder(false).map_err(map_err)?;
Ok(Capturer(display, r, yuv, Default::default()))
}
pub fn width(&self) -> usize {
self.0.width()
}
pub fn height(&self) -> usize {
self.0.height()
}
pub fn frame<'a>(&'a mut self, timeout_ms: u32) -> io::Result<Frame<'a>> {
match self.1.capture(timeout_ms as _).map_err(map_err)? {
PixelProvider::BGR0(w, h, x) => Ok(Frame(if self.2 {
crate::common::bgra_to_i420(w as _, h as _, &x, &mut self.3);
&self.3[..]
} else {
x
})),
PixelProvider::NONE => Err(std::io::ErrorKind::WouldBlock.into()),
_ => Err(map_err("Invalid data")),
}
}
}
pub struct Display(pipewire::PipeWireCapturable);
impl Display {
pub fn primary() -> io::Result<Display> {
let mut all = Display::all()?;
if all.is_empty() {
return Err(io::ErrorKind::NotFound.into());
}
Ok(all.remove(0))
}
pub fn all() -> io::Result<Vec<Display>> {
Ok(pipewire::get_capturables(false)
.map_err(map_err)?
.drain(..)
.map(|x| Display(x))
.collect())
}
pub fn width(&self) -> usize {
self.0.size.0
}
pub fn height(&self) -> usize {
self.0.size.1
}
pub fn origin(&self) -> (i32, i32) {
self.0.position
}
pub fn is_online(&self) -> bool {
true
}
pub fn is_primary(&self) -> bool {
false
}
pub fn name(&self) -> String {
"".to_owned()
}
}

View File

@@ -21,7 +21,7 @@ impl Capturer {
}
}
pub struct Frame<'a>(pub(crate) &'a [u8]);
pub struct Frame<'a>(&'a [u8]);
impl<'a> ops::Deref for Frame<'a> {
type Target = [u8];
@@ -68,7 +68,7 @@ impl Display {
self.0.rect().h as usize
}
pub fn origin(&self) -> (i32, i32) {
pub fn origin(&self) -> (usize, usize) {
let r = self.0.rect();
(r.x as _, r.y as _)
}

View File

@@ -13,7 +13,6 @@ use winapi::{
BITMAPINFO,
BITMAPINFOHEADER,
BI_RGB,
CAPTUREBLT,
DIB_RGB_COLORS, //CAPTUREBLT,
HGDI_ERROR,
RGBQUAD,
@@ -98,7 +97,7 @@ impl CapturerGDI {
self.screen_dc,
0,
0,
SRCCOPY | CAPTUREBLT, // CAPTUREBLT enable layered window but also make cursor blinking
SRCCOPY, // | CAPTUREBLT, // CAPTUREBLT enable layered window but also make cursor blinking
);
if res == 0 {
return Err("Failed to copy screen to Windows buffer".into());

View File

@@ -12,7 +12,7 @@ use winapi::{
// shared::dxgiformat::{DXGI_FORMAT, DXGI_FORMAT_B8G8R8A8_UNORM, DXGI_FORMAT_420_OPAQUE},
shared::dxgi1_2::{IDXGIOutput1, IID_IDXGIOutput1},
shared::dxgitype::DXGI_MODE_ROTATION,
shared::minwindef::{DWORD, FALSE, TRUE, UINT},
shared::minwindef::{TRUE, UINT},
shared::ntdef::LONG,
shared::windef::HMONITOR,
shared::winerror::{
@@ -25,35 +25,18 @@ use winapi::{
D3D11_CPU_ACCESS_READ, D3D11_SDK_VERSION, D3D11_USAGE_STAGING,
},
um::d3dcommon::D3D_DRIVER_TYPE_UNKNOWN,
um::unknwnbase::IUnknown,
um::wingdi::*,
um::winnt::HRESULT,
um::winuser::*,
};
pub struct ComPtr<T>(*mut T);
impl<T> ComPtr<T> {
fn is_null(&self) -> bool {
self.0.is_null()
}
}
impl<T> Drop for ComPtr<T> {
fn drop(&mut self) {
unsafe {
if !self.is_null() {
(*(self.0 as *mut IUnknown)).Release();
}
}
}
}
//TODO: Split up into files.
pub struct Capturer {
device: ComPtr<ID3D11Device>,
device: *mut ID3D11Device,
display: Display,
context: ComPtr<ID3D11DeviceContext>,
duplication: ComPtr<IDXGIOutputDuplication>,
context: *mut ID3D11DeviceContext,
duplication: *mut IDXGIOutputDuplication,
fastlane: bool,
surface: ComPtr<IDXGISurface>,
surface: *mut IDXGISurface,
data: *const u8,
len: usize,
width: usize,
@@ -72,26 +55,20 @@ impl Capturer {
let mut desc = unsafe { mem::MaybeUninit::uninit().assume_init() };
let mut gdi_capturer = None;
let mut res = if display.gdi {
wrap_hresult(1)
} else {
wrap_hresult(unsafe {
D3D11CreateDevice(
display.adapter.0 as *mut _,
D3D_DRIVER_TYPE_UNKNOWN,
ptr::null_mut(), // No software rasterizer.
0, // No device flags.
ptr::null_mut(), // Feature levels.
0, // Feature levels' length.
D3D11_SDK_VERSION,
&mut device,
ptr::null_mut(),
&mut context,
)
})
};
let device = ComPtr(device);
let context = ComPtr(context);
let mut res = wrap_hresult(unsafe {
D3D11CreateDevice(
display.adapter as *mut _,
D3D_DRIVER_TYPE_UNKNOWN,
ptr::null_mut(), // No software rasterizer.
0, // No device flags.
ptr::null_mut(), // Feature levels.
0, // Feature levels' length.
D3D11_SDK_VERSION,
&mut device,
ptr::null_mut(),
&mut context,
)
});
if res.is_err() {
gdi_capturer = display.create_gdi();
@@ -101,7 +78,7 @@ impl Capturer {
}
} else {
res = wrap_hresult(unsafe {
let hres = (*display.inner.0).DuplicateOutput(device.0 as *mut _, &mut duplication);
let hres = (*display.inner).DuplicateOutput(device as *mut _, &mut duplication);
if hres != S_OK {
gdi_capturer = display.create_gdi();
println!("Fallback to GDI");
@@ -141,7 +118,17 @@ impl Capturer {
});
}
res?;
if let Err(err) = res {
unsafe {
if !device.is_null() {
(*device).Release();
}
if !context.is_null() {
(*context).Release();
}
}
return Err(err);
}
if !duplication.is_null() {
unsafe {
@@ -152,9 +139,9 @@ impl Capturer {
Ok(Capturer {
device,
context,
duplication: ComPtr(duplication),
duplication,
fastlane: desc.DesktopImageInSystemMemory == TRUE,
surface: ComPtr(ptr::null_mut()),
surface: ptr::null_mut(),
width: display.width() as usize,
height: display.height() as usize,
display,
@@ -186,23 +173,36 @@ impl Capturer {
let mut info = mem::MaybeUninit::uninit().assume_init();
self.data = ptr::null();
wrap_hresult((*self.duplication.0).AcquireNextFrame(timeout, &mut info, &mut frame))?;
let frame = ComPtr(frame);
wrap_hresult((*self.duplication).AcquireNextFrame(timeout, &mut info, &mut frame))?;
if *info.LastPresentTime.QuadPart() == 0 {
return Err(std::io::ErrorKind::WouldBlock.into());
}
let mut rect = mem::MaybeUninit::uninit().assume_init();
if self.fastlane {
wrap_hresult((*self.duplication.0).MapDesktopSurface(&mut rect))?;
let mut rect = mem::MaybeUninit::uninit().assume_init();
let res = wrap_hresult((*self.duplication).MapDesktopSurface(&mut rect));
(*frame).Release();
if let Err(err) = res {
Err(err)
} else {
self.data = rect.pBits;
self.len = self.height * rect.Pitch as usize;
Ok(())
}
} else {
self.surface = ComPtr(self.ohgodwhat(frame.0)?);
wrap_hresult((*self.surface.0).Map(&mut rect, DXGI_MAP_READ))?;
self.surface = ptr::null_mut();
self.surface = self.ohgodwhat(frame)?;
let mut rect = mem::MaybeUninit::uninit().assume_init();
wrap_hresult((*self.surface).Map(&mut rect, DXGI_MAP_READ))?;
self.data = rect.pBits;
self.len = self.height * rect.Pitch as usize;
Ok(())
}
self.data = rect.pBits;
self.len = self.height * rect.Pitch as usize;
Ok(())
}
// copy from GPU memory to system memory
@@ -212,10 +212,9 @@ impl Capturer {
&IID_ID3D11Texture2D,
&mut texture as *mut *mut _ as *mut *mut _,
);
let texture = ComPtr(texture);
let mut texture_desc = mem::MaybeUninit::uninit().assume_init();
(*texture.0).GetDesc(&mut texture_desc);
(*texture).GetDesc(&mut texture_desc);
texture_desc.Usage = D3D11_USAGE_STAGING;
texture_desc.BindFlags = 0;
@@ -223,23 +222,33 @@ impl Capturer {
texture_desc.MiscFlags = 0;
let mut readable = ptr::null_mut();
wrap_hresult((*self.device.0).CreateTexture2D(
let res = wrap_hresult((*self.device).CreateTexture2D(
&mut texture_desc,
ptr::null(),
&mut readable,
))?;
(*readable).SetEvictionPriority(DXGI_RESOURCE_PRIORITY_MAXIMUM);
let readable = ComPtr(readable);
));
let mut surface = ptr::null_mut();
(*readable.0).QueryInterface(
&IID_IDXGISurface,
&mut surface as *mut *mut _ as *mut *mut _,
);
if let Err(err) = res {
(*frame).Release();
(*texture).Release();
(*readable).Release();
Err(err)
} else {
(*readable).SetEvictionPriority(DXGI_RESOURCE_PRIORITY_MAXIMUM);
(*self.context.0).CopyResource(readable.0 as *mut _, texture.0 as *mut _);
let mut surface = ptr::null_mut();
(*readable).QueryInterface(
&IID_IDXGISurface,
&mut surface as *mut *mut _ as *mut *mut _,
);
Ok(surface)
(*self.context).CopyResource(readable as *mut _, texture as *mut _);
(*frame).Release();
(*texture).Release();
(*readable).Release();
Ok(surface)
}
}
pub fn frame<'a>(&'a mut self, timeout: UINT) -> io::Result<&'a [u8]> {
@@ -256,7 +265,17 @@ impl Capturer {
}
}
} else {
self.unmap();
if self.fastlane {
(*self.duplication).UnMapDesktopSurface();
} else {
if !self.surface.is_null() {
(*self.surface).Unmap();
(*self.surface).Release();
self.surface = ptr::null_mut();
}
}
(*self.duplication).ReleaseFrame();
self.load_frame(timeout)?;
slice::from_raw_parts(self.data, self.len)
}
@@ -276,32 +295,31 @@ impl Capturer {
})
}
}
}
fn unmap(&self) {
impl Drop for Capturer {
fn drop(&mut self) {
unsafe {
(*self.duplication.0).ReleaseFrame();
if self.fastlane {
(*self.duplication.0).UnMapDesktopSurface();
} else {
if !self.surface.is_null() {
(*self.surface.0).Unmap();
}
if !self.surface.is_null() {
(*self.surface).Unmap();
(*self.surface).Release();
}
if !self.duplication.is_null() {
(*self.duplication).Release();
}
if !self.device.is_null() {
(*self.device).Release();
}
if !self.context.is_null() {
(*self.context).Release();
}
}
}
}
impl Drop for Capturer {
fn drop(&mut self) {
if !self.duplication.is_null() {
self.unmap();
}
}
}
pub struct Displays {
factory: ComPtr<IDXGIFactory1>,
adapter: ComPtr<IDXGIAdapter1>,
factory: *mut IDXGIFactory1,
adapter: *mut IDXGIAdapter1,
/// Index of the CURRENT adapter.
nadapter: UINT,
/// Index of the NEXT display to fetch.
@@ -321,63 +339,13 @@ impl Displays {
};
Ok(Displays {
factory: ComPtr(factory),
adapter: ComPtr(adapter),
factory,
adapter,
nadapter: 0,
ndisplay: 0,
})
}
pub fn get_from_gdi() -> Vec<Display> {
let mut all = Vec::new();
let mut i: DWORD = 0;
loop {
let mut d: DISPLAY_DEVICEW = unsafe { std::mem::MaybeUninit::uninit().assume_init() };
d.cb = std::mem::size_of::<DISPLAY_DEVICEW>() as _;
let ok = unsafe { EnumDisplayDevicesW(std::ptr::null(), i, &mut d as _, 0) };
if ok == FALSE {
break;
}
i += 1;
if 0 == (d.StateFlags & DISPLAY_DEVICE_ACTIVE)
|| (d.StateFlags & DISPLAY_DEVICE_MIRRORING_DRIVER) > 0
{
continue;
}
// let is_primary = (d.StateFlags & DISPLAY_DEVICE_PRIMARY_DEVICE) > 0;
let mut disp = Display {
inner: ComPtr(std::ptr::null_mut()),
adapter: ComPtr(std::ptr::null_mut()),
desc: unsafe { std::mem::zeroed() },
gdi: true,
};
disp.desc.DeviceName = d.DeviceName;
let mut m: DEVMODEW = unsafe { std::mem::MaybeUninit::uninit().assume_init() };
m.dmSize = std::mem::size_of::<DEVMODEW>() as _;
m.dmDriverExtra = 0;
let ok = unsafe {
EnumDisplaySettingsExW(
disp.desc.DeviceName.as_ptr(),
ENUM_CURRENT_SETTINGS,
&mut m as _,
0,
)
};
if ok == FALSE {
continue;
}
disp.desc.DesktopCoordinates.left = unsafe { m.u1.s2().dmPosition.x };
disp.desc.DesktopCoordinates.top = unsafe { m.u1.s2().dmPosition.y };
disp.desc.DesktopCoordinates.right =
disp.desc.DesktopCoordinates.left + m.dmPelsWidth as i32;
disp.desc.DesktopCoordinates.bottom =
disp.desc.DesktopCoordinates.top + m.dmPelsHeight as i32;
disp.desc.AttachedToDesktop = 1;
all.push(disp);
}
all
}
// No Adapter => Some(None)
// Non-Empty Adapter => Some(Some(OUTPUT))
// End of Adapter => None
@@ -392,15 +360,18 @@ impl Displays {
let output = unsafe {
let mut output = ptr::null_mut();
(*self.adapter.0).EnumOutputs(self.ndisplay, &mut output);
ComPtr(output)
(*self.adapter).EnumOutputs(self.ndisplay, &mut output);
output
};
// If the current adapter is done, we free it.
// We return None so the caller gets the next adapter and tries again.
if output.is_null() {
self.adapter = ComPtr(ptr::null_mut());
unsafe {
(*self.adapter).Release();
self.adapter = ptr::null_mut();
}
return None;
}
@@ -412,7 +383,7 @@ impl Displays {
let desc = unsafe {
let mut desc = mem::MaybeUninit::uninit().assume_init();
(*output.0).GetDesc(&mut desc);
(*output).GetDesc(&mut desc);
desc
};
@@ -420,26 +391,29 @@ impl Displays {
let mut inner: *mut IDXGIOutput1 = ptr::null_mut();
unsafe {
(*output.0).QueryInterface(&IID_IDXGIOutput1, &mut inner as *mut *mut _ as *mut *mut _);
(*output).QueryInterface(&IID_IDXGIOutput1, &mut inner as *mut *mut _ as *mut *mut _);
(*output).Release();
}
// If it's null, we have an error.
// So we act like the adapter is done.
if inner.is_null() {
self.adapter = ComPtr(ptr::null_mut());
unsafe {
(*self.adapter).Release();
self.adapter = ptr::null_mut();
}
return None;
}
unsafe {
(*self.adapter.0).AddRef();
(*self.adapter).AddRef();
}
Some(Some(Display {
inner: ComPtr(inner),
adapter: ComPtr(self.adapter.0),
inner,
adapter: self.adapter,
desc,
gdi: false,
}))
}
}
@@ -457,8 +431,8 @@ impl Iterator for Displays {
self.adapter = unsafe {
let mut adapter = ptr::null_mut();
(*self.factory.0).EnumAdapters1(self.nadapter, &mut adapter);
ComPtr(adapter)
(*self.factory).EnumAdapters1(self.nadapter, &mut adapter);
adapter
};
if let Some(res) = self.read_and_invalidate() {
@@ -471,14 +445,22 @@ impl Iterator for Displays {
}
}
pub struct Display {
inner: ComPtr<IDXGIOutput1>,
adapter: ComPtr<IDXGIAdapter1>,
desc: DXGI_OUTPUT_DESC,
gdi: bool,
impl Drop for Displays {
fn drop(&mut self) {
unsafe {
(*self.factory).Release();
if !self.adapter.is_null() {
(*self.adapter).Release();
}
}
}
}
// https://github.com/dchapyshev/aspia/blob/59233c5d01a4d03ed6de19b03ce77d61a6facf79/source/base/desktop/win/screen_capture_utils.cc
pub struct Display {
inner: *mut IDXGIOutput1,
adapter: *mut IDXGIAdapter1,
desc: DXGI_OUTPUT_DESC,
}
impl Display {
pub fn width(&self) -> LONG {
@@ -527,6 +509,15 @@ impl Display {
}
}
impl Drop for Display {
fn drop(&mut self) {
unsafe {
(*self.inner).Release();
(*self.adapter).Release();
}
}
}
fn wrap_hresult(x: HRESULT) -> io::Result<()> {
use std::io::ErrorKind::*;
Err((match x {

View File

@@ -14,9 +14,6 @@ pub mod quartz;
#[cfg(x11)]
pub mod x11;
#[cfg(all(x11, feature="wayland"))]
pub mod wayland;
#[cfg(dxgi)]
pub mod dxgi;

View File

@@ -1,3 +0,0 @@
pub mod pipewire;
mod pipewire_dbus;
pub mod capturable;

View File

@@ -1,11 +0,0 @@
# About
Derived from https://github.com/H-M-H/Weylus/tree/master/src/capturable with the author's consent, https://github.com/rustdesk/rustdesk/issues/56#issuecomment-882727967
# Dep
Works fine on Ubuntu 21.04 with pipewire 3 and xdg-desktop-portal 1.8
`
apt install -y libgstreamer1.0-dev libgstreamer-plugins-base1.0-dev
`

View File

@@ -1,58 +0,0 @@
use std::boxed::Box;
use std::error::Error;
pub enum PixelProvider<'a> {
// 8 bits per color
RGB(usize, usize, &'a [u8]),
BGR0(usize, usize, &'a [u8]),
// width, height, stride
BGR0S(usize, usize, usize, &'a [u8]),
NONE,
}
impl<'a> PixelProvider<'a> {
pub fn size(&self) -> (usize, usize) {
match self {
PixelProvider::RGB(w, h, _) => (*w, *h),
PixelProvider::BGR0(w, h, _) => (*w, *h),
PixelProvider::BGR0S(w, h, _, _) => (*w, *h),
PixelProvider::NONE => (0, 0),
}
}
}
pub trait Recorder {
fn capture(&mut self, timeout_ms: u64) -> Result<PixelProvider, Box<dyn Error>>;
}
pub trait BoxCloneCapturable {
fn box_clone(&self) -> Box<dyn Capturable>;
}
impl<T> BoxCloneCapturable for T
where
T: Clone + Capturable + 'static,
{
fn box_clone(&self) -> Box<dyn Capturable> {
Box::new(self.clone())
}
}
pub trait Capturable: Send + BoxCloneCapturable {
/// Name of the Capturable, for example the window title, if it is a window.
fn name(&self) -> String;
/// Return x, y, width, height of the Capturable as floats relative to the absolute size of the
/// screen. For example x=0.5, y=0.0, width=0.5, height=1.0 means the right half of the screen.
fn geometry_relative(&self) -> Result<(f64, f64, f64, f64), Box<dyn Error>>;
/// Callback that is called right before input is simulated.
/// Useful to focus the window on input.
fn before_input(&mut self) -> Result<(), Box<dyn Error>>;
/// Return a Recorder that can record the current capturable.
fn recorder(&self, capture_cursor: bool) -> Result<Box<dyn Recorder>, Box<dyn Error>>;
}
impl Clone for Box<dyn Capturable> {
fn clone(&self) -> Self {
self.box_clone()
}
}

View File

@@ -1,530 +0,0 @@
use std::collections::HashMap;
use std::error::Error;
use std::os::unix::io::AsRawFd;
use std::sync::{atomic::AtomicBool, Arc, Mutex};
use std::time::Duration;
use tracing::{debug, trace, warn};
use dbus::{
arg::{OwnedFd, PropMap, RefArg, Variant},
blocking::{Proxy, SyncConnection},
message::{MatchRule, MessageType},
Message,
};
use gstreamer as gst;
use gstreamer::prelude::*;
use gstreamer_app::AppSink;
use super::capturable::PixelProvider;
use super::capturable::{Capturable, Recorder};
use super::pipewire_dbus::{OrgFreedesktopPortalRequestResponse, OrgFreedesktopPortalScreenCast};
#[derive(Debug, Clone, Copy)]
struct PwStreamInfo {
path: u64,
source_type: u64,
position: (i32, i32),
size: (usize, usize),
}
#[derive(Debug)]
pub struct DBusError(String);
impl std::fmt::Display for DBusError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let Self(s) = self;
write!(f, "{}", s)
}
}
impl Error for DBusError {}
#[derive(Debug)]
pub struct GStreamerError(String);
impl std::fmt::Display for GStreamerError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let Self(s) = self;
write!(f, "{}", s)
}
}
impl Error for GStreamerError {}
#[derive(Clone)]
pub struct PipeWireCapturable {
// connection needs to be kept alive for recording
dbus_conn: Arc<SyncConnection>,
fd: OwnedFd,
path: u64,
source_type: u64,
pub position: (i32, i32),
pub size: (usize, usize),
}
impl PipeWireCapturable {
fn new(conn: Arc<SyncConnection>, fd: OwnedFd, stream: PwStreamInfo) -> Self {
Self {
dbus_conn: conn,
fd,
path: stream.path,
source_type: stream.source_type,
position: stream.position,
size: stream.size,
}
}
}
impl std::fmt::Debug for PipeWireCapturable {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"PipeWireCapturable {{dbus: {}, fd: {}, path: {}, source_type: {}}}",
self.dbus_conn.unique_name(),
self.fd.as_raw_fd(),
self.path,
self.source_type
)
}
}
impl Capturable for PipeWireCapturable {
fn name(&self) -> String {
let type_str = match self.source_type {
1 => "Desktop",
2 => "Window",
_ => "Unknow",
};
format!("Pipewire {}, path: {}", type_str, self.path)
}
fn geometry_relative(&self) -> Result<(f64, f64, f64, f64), Box<dyn Error>> {
Ok((0.0, 0.0, 1.0, 1.0))
}
fn before_input(&mut self) -> Result<(), Box<dyn Error>> {
Ok(())
}
fn recorder(&self, _capture_cursor: bool) -> Result<Box<dyn Recorder>, Box<dyn Error>> {
Ok(Box::new(PipeWireRecorder::new(self.clone())?))
}
}
pub struct PipeWireRecorder {
buffer: Option<gst::MappedBuffer<gst::buffer::Readable>>,
buffer_cropped: Vec<u8>,
is_cropped: bool,
pipeline: gst::Pipeline,
appsink: AppSink,
width: usize,
height: usize,
}
impl PipeWireRecorder {
pub fn new(capturable: PipeWireCapturable) -> Result<Self, Box<dyn Error>> {
let pipeline = gst::Pipeline::new(None);
let src = gst::ElementFactory::make("pipewiresrc", None)?;
src.set_property("fd", &capturable.fd.as_raw_fd())?;
src.set_property("path", &format!("{}", capturable.path))?;
// For some reason pipewire blocks on destruction of AppSink if this is not set to true,
// see: https://gitlab.freedesktop.org/pipewire/pipewire/-/issues/982
src.set_property("always-copy", &true)?;
let sink = gst::ElementFactory::make("appsink", None)?;
sink.set_property("drop", &true)?;
sink.set_property("max-buffers", &1u32)?;
pipeline.add_many(&[&src, &sink])?;
src.link(&sink)?;
let appsink = sink
.dynamic_cast::<AppSink>()
.map_err(|_| GStreamerError("Sink element is expected to be an appsink!".into()))?;
appsink.set_caps(Some(&gst::Caps::new_simple(
"video/x-raw",
&[("format", &"BGRx")],
)));
pipeline.set_state(gst::State::Playing)?;
Ok(Self {
pipeline,
appsink,
buffer: None,
width: 0,
height: 0,
buffer_cropped: vec![],
is_cropped: false,
})
}
}
impl Recorder for PipeWireRecorder {
fn capture(&mut self, timeout_ms: u64) -> Result<PixelProvider, Box<dyn Error>> {
if let Some(sample) = self
.appsink
.try_pull_sample(gst::ClockTime::from_mseconds(timeout_ms))
{
let cap = sample
.get_caps()
.ok_or("Failed get caps")?
.get_structure(0)
.ok_or("Failed to get structure")?;
let w: i32 = cap.get_value("width")?.get_some()?;
let h: i32 = cap.get_value("height")?.get_some()?;
let w = w as usize;
let h = h as usize;
let buf = sample
.get_buffer_owned()
.ok_or_else(|| GStreamerError("Failed to get owned buffer.".into()))?;
let mut crop = buf
.get_meta::<gstreamer_video::VideoCropMeta>()
.map(|m| m.get_rect());
// only crop if necessary
if Some((0, 0, w as u32, h as u32)) == crop {
crop = None;
}
let buf = buf
.into_mapped_buffer_readable()
.map_err(|_| GStreamerError("Failed to map buffer.".into()))?;
let buf_size = buf.get_size();
// BGRx is 4 bytes per pixel
if buf_size != (w * h * 4) {
// for some reason the width and height of the caps do not guarantee correct buffer
// size, so ignore those buffers, see:
// https://gitlab.freedesktop.org/pipewire/pipewire/-/issues/985
trace!(
"Size of mapped buffer: {} does NOT match size of capturable {}x{}@BGRx, \
dropping it!",
buf_size,
w,
h
);
} else {
// Copy region specified by crop into self.buffer_cropped
// TODO: Figure out if ffmpeg provides a zero copy alternative
if let Some((x_off, y_off, w_crop, h_crop)) = crop {
let x_off = x_off as usize;
let y_off = y_off as usize;
let w_crop = w_crop as usize;
let h_crop = h_crop as usize;
self.buffer_cropped.clear();
let data = buf.as_slice();
// BGRx is 4 bytes per pixel
self.buffer_cropped.reserve(w_crop * h_crop * 4);
for y in y_off..(y_off + h_crop) {
let i = 4 * (w * y + x_off);
self.buffer_cropped.extend(&data[i..i + 4 * w_crop]);
}
self.width = w_crop;
self.height = h_crop;
} else {
self.width = w;
self.height = h;
}
self.is_cropped = crop.is_some();
self.buffer = Some(buf);
}
} else {
return Ok(PixelProvider::NONE);
}
if self.buffer.is_none() {
return Err(Box::new(GStreamerError("No buffer available!".into())));
}
Ok(PixelProvider::BGR0(
self.width,
self.height,
if self.is_cropped {
self.buffer_cropped.as_slice()
} else {
self.buffer.as_ref().unwrap().as_slice()
},
))
}
}
impl Drop for PipeWireRecorder {
fn drop(&mut self) {
if let Err(err) = self.pipeline.set_state(gst::State::Null) {
warn!("Failed to stop GStreamer pipeline: {}.", err);
}
}
}
fn handle_response<F>(
conn: &SyncConnection,
path: dbus::Path<'static>,
mut f: F,
failure_out: Arc<AtomicBool>,
) -> Result<dbus::channel::Token, dbus::Error>
where
F: FnMut(
OrgFreedesktopPortalRequestResponse,
&SyncConnection,
&Message,
) -> Result<(), Box<dyn Error>>
+ Send
+ Sync
+ 'static,
{
let mut m = MatchRule::new();
m.path = Some(path);
m.msg_type = Some(MessageType::Signal);
m.sender = Some("org.freedesktop.portal.Desktop".into());
m.interface = Some("org.freedesktop.portal.Request".into());
conn.add_match(m, move |r: OrgFreedesktopPortalRequestResponse, c, m| {
debug!("Response from DBus: response: {:?}, message: {:?}", r, m);
match r.response {
0 => {}
1 => {
warn!("DBus response: User cancelled interaction.");
failure_out.store(true, std::sync::atomic::Ordering::Relaxed);
return true;
}
c => {
warn!("DBus response: Unknown error, code: {}.", c);
failure_out.store(true, std::sync::atomic::Ordering::Relaxed);
return true;
}
}
if let Err(err) = f(r, c, m) {
warn!("Error requesting screen capture via dbus: {}", err);
failure_out.store(true, std::sync::atomic::Ordering::Relaxed);
}
true
})
}
fn get_portal(conn: &SyncConnection) -> Proxy<&SyncConnection> {
conn.with_proxy(
"org.freedesktop.portal.Desktop",
"/org/freedesktop/portal/desktop",
Duration::from_millis(1000),
)
}
fn streams_from_response(response: OrgFreedesktopPortalRequestResponse) -> Vec<PwStreamInfo> {
(move || {
Some(
response
.results
.get("streams")?
.as_iter()?
.next()?
.as_iter()?
.filter_map(|stream| {
let mut itr = stream.as_iter()?;
let path = itr.next()?.as_u64()?;
let (keys, values): (Vec<(usize, &dyn RefArg)>, Vec<(usize, &dyn RefArg)>) =
itr.next()?
.as_iter()?
.enumerate()
.partition(|(i, _)| i % 2 == 0);
let attributes = keys
.iter()
.filter_map(|(_, key)| Some(key.as_str()?.to_owned()))
.zip(
values
.iter()
.map(|(_, arg)| *arg)
.collect::<Vec<&dyn RefArg>>(),
)
.collect::<HashMap<String, &dyn RefArg>>();
let mut info = PwStreamInfo {
path,
source_type: attributes
.get("source_type")
.map_or(Some(0), |v| v.as_u64())?,
position: (0, 0),
size: (0, 0),
};
let v = attributes
.get("size")?
.as_iter()?
.filter_map(|v| {
Some(
v.as_iter()?
.map(|x| x.as_i64().unwrap_or(0))
.collect::<Vec<i64>>(),
)
})
.next();
if let Some(v) = v {
if v.len() == 2 {
info.size.0 = v[0] as _;
info.size.1 = v[1] as _;
}
}
let v = attributes
.get("position")?
.as_iter()?
.filter_map(|v| {
Some(
v.as_iter()?
.map(|x| x.as_i64().unwrap_or(0))
.collect::<Vec<i64>>(),
)
})
.next();
if let Some(v) = v {
if v.len() == 2 {
info.position.0 = v[0] as _;
info.position.1 = v[1] as _;
}
}
Some(info)
})
.collect::<Vec<PwStreamInfo>>(),
)
})()
.unwrap_or_default()
}
static mut INIT: bool = false;
// mostly inspired by https://gitlab.gnome.org/snippets/19
fn request_screen_cast(
capture_cursor: bool,
) -> Result<(SyncConnection, OwnedFd, Vec<PwStreamInfo>), Box<dyn Error>> {
unsafe {
if !INIT {
gstreamer::init()?;
INIT = true;
}
}
let conn = SyncConnection::new_session()?;
let portal = get_portal(&conn);
let mut args: PropMap = HashMap::new();
let fd: Arc<Mutex<Option<OwnedFd>>> = Arc::new(Mutex::new(None));
let fd_res = fd.clone();
let streams: Arc<Mutex<Vec<PwStreamInfo>>> = Arc::new(Mutex::new(Vec::new()));
let streams_res = streams.clone();
let failure = Arc::new(AtomicBool::new(false));
let failure_res = failure.clone();
args.insert(
"session_handle_token".to_string(),
Variant(Box::new("u1".to_string())),
);
args.insert(
"handle_token".to_string(),
Variant(Box::new("u1".to_string())),
);
let path = portal.create_session(args)?;
handle_response(
&conn,
path,
move |r: OrgFreedesktopPortalRequestResponse, c, _| {
let portal = get_portal(c);
let mut args: PropMap = HashMap::new();
args.insert(
"handle_token".to_string(),
Variant(Box::new("u2".to_string())),
);
// https://flatpak.github.io/xdg-desktop-portal/portal-docs.html#gdbus-method-org-freedesktop-portal-ScreenCast.SelectSources
args.insert("multiple".into(), Variant(Box::new(true)));
args.insert("types".into(), Variant(Box::new(1u32))); //| 2u32)));
let cursor_mode = if capture_cursor { 2u32 } else { 1u32 };
let plasma = std::env::var("DESKTOP_SESSION").map_or(false, |s| s.contains("plasma"));
if plasma && capture_cursor {
// Warn the user if capturing the cursor is tried on kde as this can crash
// kwin_wayland and tear down the plasma desktop, see:
// https://bugs.kde.org/show_bug.cgi?id=435042
warn!("You are attempting to capture the cursor under KDE Plasma, this may crash your \
desktop, see https://bugs.kde.org/show_bug.cgi?id=435042 for details! \
You have been warned.");
}
args.insert("cursor_mode".into(), Variant(Box::new(cursor_mode)));
let session: dbus::Path = r
.results
.get("session_handle")
.ok_or_else(|| {
DBusError(format!(
"Failed to obtain session_handle from response: {:?}",
r
))
})?
.as_str()
.ok_or_else(|| DBusError("Failed to convert session_handle to string.".into()))?
.to_string()
.into();
let path = portal.select_sources(session.clone(), args)?;
let fd = fd.clone();
let streams = streams.clone();
let failure = failure.clone();
let failure_out = failure.clone();
handle_response(
c,
path,
move |_: OrgFreedesktopPortalRequestResponse, c, _| {
let portal = get_portal(c);
let mut args: PropMap = HashMap::new();
args.insert(
"handle_token".to_string(),
Variant(Box::new("u3".to_string())),
);
let path = portal.start(session.clone(), "", args)?;
let session = session.clone();
let fd = fd.clone();
let streams = streams.clone();
let failure = failure.clone();
let failure_out = failure.clone();
handle_response(
c,
path,
move |r: OrgFreedesktopPortalRequestResponse, c, _| {
streams
.clone()
.lock()
.unwrap()
.append(&mut streams_from_response(r));
let portal = get_portal(c);
fd.clone().lock().unwrap().replace(
portal.open_pipe_wire_remote(session.clone(), HashMap::new())?,
);
Ok(())
},
failure_out,
)?;
Ok(())
},
failure_out,
)?;
Ok(())
},
failure_res.clone(),
)?;
// wait 3 minutes for user interaction
for _ in 0..1800 {
conn.process(Duration::from_millis(100))?;
// Once we got a file descriptor we are done!
if fd_res.lock().unwrap().is_some() {
break;
}
if failure_res.load(std::sync::atomic::Ordering::Relaxed) {
break;
}
}
let fd_res = fd_res.lock().unwrap();
let streams_res = streams_res.lock().unwrap();
if fd_res.is_some() && !streams_res.is_empty() {
Ok((conn, fd_res.clone().unwrap(), streams_res.clone()))
} else {
Err(Box::new(DBusError(
"Failed to obtain screen capture.".into(),
)))
}
}
pub fn get_capturables(capture_cursor: bool) -> Result<Vec<PipeWireCapturable>, Box<dyn Error>> {
let (conn, fd, streams) = request_screen_cast(capture_cursor)?;
let conn = Arc::new(conn);
Ok(streams
.into_iter()
.map(|s| PipeWireCapturable::new(conn.clone(), fd.clone(), s))
.collect())
}

View File

@@ -1,144 +0,0 @@
// This code was autogenerated with `dbus-codegen-rust -c blocking -m None`, see https://github.com/diwic/dbus-rs
use dbus;
#[allow(unused_imports)]
use dbus::arg;
use dbus::blocking;
pub trait OrgFreedesktopPortalScreenCast {
fn create_session(&self, options: arg::PropMap) -> Result<dbus::Path<'static>, dbus::Error>;
fn select_sources(
&self,
session_handle: dbus::Path,
options: arg::PropMap,
) -> Result<dbus::Path<'static>, dbus::Error>;
fn start(
&self,
session_handle: dbus::Path,
parent_window: &str,
options: arg::PropMap,
) -> Result<dbus::Path<'static>, dbus::Error>;
fn open_pipe_wire_remote(
&self,
session_handle: dbus::Path,
options: arg::PropMap,
) -> Result<arg::OwnedFd, dbus::Error>;
fn available_source_types(&self) -> Result<u32, dbus::Error>;
fn available_cursor_modes(&self) -> Result<u32, dbus::Error>;
fn version(&self) -> Result<u32, dbus::Error>;
}
impl<'a, T: blocking::BlockingSender, C: ::std::ops::Deref<Target = T>>
OrgFreedesktopPortalScreenCast for blocking::Proxy<'a, C>
{
fn create_session(&self, options: arg::PropMap) -> Result<dbus::Path<'static>, dbus::Error> {
self.method_call(
"org.freedesktop.portal.ScreenCast",
"CreateSession",
(options,),
)
.map(|r: (dbus::Path<'static>,)| r.0)
}
fn select_sources(
&self,
session_handle: dbus::Path,
options: arg::PropMap,
) -> Result<dbus::Path<'static>, dbus::Error> {
self.method_call(
"org.freedesktop.portal.ScreenCast",
"SelectSources",
(session_handle, options),
)
.map(|r: (dbus::Path<'static>,)| r.0)
}
fn start(
&self,
session_handle: dbus::Path,
parent_window: &str,
options: arg::PropMap,
) -> Result<dbus::Path<'static>, dbus::Error> {
self.method_call(
"org.freedesktop.portal.ScreenCast",
"Start",
(session_handle, parent_window, options),
)
.map(|r: (dbus::Path<'static>,)| r.0)
}
fn open_pipe_wire_remote(
&self,
session_handle: dbus::Path,
options: arg::PropMap,
) -> Result<arg::OwnedFd, dbus::Error> {
self.method_call(
"org.freedesktop.portal.ScreenCast",
"OpenPipeWireRemote",
(session_handle, options),
)
.map(|r: (arg::OwnedFd,)| r.0)
}
fn available_source_types(&self) -> Result<u32, dbus::Error> {
<Self as blocking::stdintf::org_freedesktop_dbus::Properties>::get(
&self,
"org.freedesktop.portal.ScreenCast",
"AvailableSourceTypes",
)
}
fn available_cursor_modes(&self) -> Result<u32, dbus::Error> {
<Self as blocking::stdintf::org_freedesktop_dbus::Properties>::get(
&self,
"org.freedesktop.portal.ScreenCast",
"AvailableCursorModes",
)
}
fn version(&self) -> Result<u32, dbus::Error> {
<Self as blocking::stdintf::org_freedesktop_dbus::Properties>::get(
&self,
"org.freedesktop.portal.ScreenCast",
"version",
)
}
}
pub trait OrgFreedesktopPortalRequest {
fn close(&self) -> Result<(), dbus::Error>;
}
impl<'a, T: blocking::BlockingSender, C: ::std::ops::Deref<Target = T>> OrgFreedesktopPortalRequest
for blocking::Proxy<'a, C>
{
fn close(&self) -> Result<(), dbus::Error> {
self.method_call("org.freedesktop.portal.Request", "Close", ())
}
}
#[derive(Debug)]
pub struct OrgFreedesktopPortalRequestResponse {
pub response: u32,
pub results: arg::PropMap,
}
impl arg::AppendAll for OrgFreedesktopPortalRequestResponse {
fn append(&self, i: &mut arg::IterAppend) {
arg::RefArg::append(&self.response, i);
arg::RefArg::append(&self.results, i);
}
}
impl arg::ReadAll for OrgFreedesktopPortalRequestResponse {
fn read(i: &mut arg::Iter) -> Result<Self, arg::TypeMismatchError> {
Ok(OrgFreedesktopPortalRequestResponse {
response: i.read()?,
results: i.read()?,
})
}
}
impl dbus::message::SignalArgs for OrgFreedesktopPortalRequestResponse {
const NAME: &'static str = "Response";
const INTERFACE: &'static str = "org.freedesktop.portal.Request";
}

5
libs/systray-rs/.gitignore vendored Normal file
View File

@@ -0,0 +1,5 @@
# Remove Cargo.lock from gitignore if creating an executable, leave it for libraries
# More information here http://doc.crates.io/guide.html#cargotoml-vs-cargolock
Cargo.lock
/target/

View File

@@ -0,0 +1,32 @@
language: rust
rust:
- stable
- beta
- nightly
matrix:
allow_failures:
- rust: nightly
addons:
apt:
sources:
- ubuntu-toolchain-r-test
packages:
- build-essential
- libgtk-3-dev
- libappindicator3-dev
- gcc-5
before_install: . ./ci/before_install.sh
script:
- RUST_BACKTRACE=1 PKG_CONFIG_PATH=$HOME/local/lib/pkgconfig LD_LIBRARY_PATH=$HOME/local/lib:$LD_LIBRARY_PATH cargo build --verbose
- RUST_BACKTRACE=1 PKG_CONFIG_PATH=$HOME/local/lib/pkgconfig LD_LIBRARY_PATH=$HOME/local/lib:$LD_LIBRARY_PATH cargo test --verbose
global_env:
secure: O40C4FadE2C8yApgCbQNYmeWQuytrhu4W3a2HKRvGgB39LP0ysMU2UKXQIyZqlZUS9mP9qi5HYN+GTt83aE3Ac0eAwRqq+9zMjC2qMaiZ1JBSfCJI5wiiIXP0HpbsxXipG2Z21aqupVfu0HjNP4RVkaZ7ONKAeLAieI06+7VHbMPw6mcJd4Drv8VTyKn89VvB4lxKexLcURfagoic3fzeFKaIIVBSqGHiXrURbpD5tffOnzc5YFWxeGKTVFl8WqQVrRk2gnl/39UhSsOHGuSExw5GSxh+OaNHTiAkvOaSQLa05Y5mkNlHAsMyqg1mW3mI2xuzCQaFFT5G5JF7uxvZsa4GfROaEG8r1CZvpWxG2NtpupXvIC25nN+QQeeMZv5PHaxlk9OkG0k+2+z1Tu0Yd05x/o3+52YFo3geVwDmI3zx4Zgg9u9nIwGhdtzqbKV2fQNnKbNWVQH6D5M1DlBMYyY25jpkehcazqUbLsJXJFIoMkXhdkjTIpZg4w+CQ617WCnoDhXh6+Iqkw+iBBJJugaf2D6qBpXNiLZNJwbv2M5fj8uDsDtsUvjg56qBw+g+TeHJDKjzpEId/zFrAe4lmuFjN4/SlDk3n5xjZ5eY4PGRp1K8DGgeBQI5gyvHR3H7lm4GE2NCEvNILYFjpANZsiWwDepb2/rHvYNiLK+jhc=
env:
- LLVM_VERSION=3.9 CLANG_VERSION=clang_3_9

View File

@@ -0,0 +1,33 @@
# 0.4.0 (2020-02-15)
## Features
- Brought up to Rust 2018 (thanks to https://github.com/udoprog)
## Bugfixes
- Updated libappindicator to compile on modern rust
# 0.3.0 (2018-04-28)
## Bugfixes
- Update gtk so linux version will run again
# 0.2.0 (2017-05-04)
## Features
- Add Linux Support
# 0.1.1 (2017-02-28)
## Bugfixes
- Some cleanup and CI work
# 0.1.0 (2017-02-22)
## Features
- Basic Win32 systray support

View File

@@ -0,0 +1,28 @@
[package]
name = "systray"
version = "0.4.1"
authors = ["Kyle Machulis <kyle@machul.is>"]
description = "Rust library for making minimal cross-platform systray GUIs"
license = "BSD-3-Clause"
homepage = "http://github.com/qdot/systray-rs"
repository = "https://github.com/qdot/systray-rs.git"
readme = "README.md"
keywords = ["gui"]
edition = "2018"
[dependencies]
log= "0.4"
[target.'cfg(target_os = "windows")'.dependencies]
winapi= { version = "0.3", features = ["shellapi", "libloaderapi", "errhandlingapi", "impl-default"] }
libc= "0.2"
[target.'cfg(target_os = "linux")'.dependencies]
gtk= "0.9"
glib= "0.10"
libappindicator= "0.5"
# [target.'cfg(target_os = "macos")'.dependencies]
# objc="*"
# cocoa="*"
# core-foundation="*"

View File

@@ -0,0 +1,28 @@
Copyright (c) 2016, Kyle Machulis
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the project nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

58
libs/systray-rs/README.md Normal file
View File

@@ -0,0 +1,58 @@
# systray-rs
[![Crates.io](https://img.shields.io/crates/v/systray)](https://crates.io/crates/systray) [![Crates.io](https://img.shields.io/crates/d/systray)](https://crates.io/crates/systray)
[![Build Status](https://travis-ci.org/qdot/systray-rs.svg?branch=master)](https://travis-ci.org/qdot/systray-rs) [![Build status](https://ci.appveyor.com/api/projects/status/lhqm3lucb5w5559b?svg=true)](https://ci.appveyor.com/project/qdot/systray-rs)
systray-rs is a Rust library that makes it easy for applications to
have minimal UI in a platform specific way. It wraps the platform
specific calls required to show an icon in the system tray, as well as
add menu entries.
systray-rs is heavily influenced by
[the systray library for the Go Language](https://github.com/getlantern/systray).
systray-rs currently supports:
- Linux GTK
- Win32
Cocoa core still needed!
# License
systray-rs includes some code
from [winapi-rs, by retep998](https://github.com/retep998/winapi-rs).
This code is covered under the MIT license. This code will be removed
once winapi-rs has a 0.3 crate available.
systray-rs is BSD licensed.
Copyright (c) 2016-2020, Nonpolynomial Labs, LLC
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the project nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

View File

@@ -0,0 +1,22 @@
version: "0.1.0.{build}"
environment:
matrix:
- TARGET: nightly-x86_64-pc-windows-msvc
- TARGET: nightly-i686-pc-windows-msvc
- TARGET: nightly-x86_64-pc-windows-gnu
- TARGET: nightly-i686-pc-windows-gnu
install:
- ps: Start-FileDownload "https://static.rust-lang.org/dist/rust-${env:TARGET}.exe" -FileName "rust-install.exe"
- ps: .\rust-install.exe /VERYSILENT /NORESTART /DIR="C:\rust" | Out-Null
- ps: $env:PATH="$env:PATH;C:\rust\bin"
- rustc -vV
- cargo -vV
- erase rust-install.exe
build_script:
- cargo build
# Skip packaging step while we're running off a local winapi build
#- cargo package
skip_commits:
files:
- README.md
- .travis.yml

View File

@@ -0,0 +1,39 @@
set -e
pushd ~
# Workaround for Travis CI macOS bug (https://github.com/travis-ci/travis-ci/issues/6307)
if [ "${TRAVIS_OS_NAME}" == "osx" ]; then
rvm get head || true
fi
function llvm_version_triple() {
if [ "$1" == "3.8" ]; then
echo "3.8.0"
elif [ "$1" == "3.9" ]; then
echo "3.9.0"
fi
}
function llvm_download() {
export LLVM_VERSION_TRIPLE=`llvm_version_triple ${LLVM_VERSION}`
export LLVM=clang+llvm-${LLVM_VERSION_TRIPLE}-x86_64-$1
wget http://llvm.org/releases/${LLVM_VERSION_TRIPLE}/${LLVM}.tar.xz
mkdir llvm
tar -xf ${LLVM}.tar.xz -C llvm --strip-components=1
export LLVM_CONFIG_PATH=`pwd`/llvm/bin/llvm-config
if [ "${TRAVIS_OS_NAME}" == "osx" ]; then
cp llvm/lib/libclang.dylib /usr/local/lib/libclang.dylib
fi
}
if [ "${TRAVIS_OS_NAME}" == "linux" ]; then
llvm_download linux-gnu-ubuntu-14.04
else
llvm_download apple-darwin
fi
popd
set +e

View File

@@ -0,0 +1,43 @@
#![windows_subsystem = "windows"]
//#[cfg(target_os = "windows")]
fn main() -> Result<(), systray::Error> {
let mut app;
match systray::Application::new() {
Ok(w) => app = w,
Err(_) => panic!("Can't create window!"),
}
// w.set_icon_from_file(&"C:\\Users\\qdot\\code\\git-projects\\systray-rs\\resources\\rust.ico".to_string());
// w.set_tooltip(&"Whatever".to_string());
app.set_icon_from_file("/usr/share/gxkb/flags/ua.png")?;
app.add_menu_item("Print a thing", |_| {
println!("Printing a thing!");
Ok::<_, systray::Error>(())
})?;
app.add_menu_item("Add Menu Item", |window| {
window.add_menu_item("Interior item", |_| {
println!("what");
Ok::<_, systray::Error>(())
})?;
window.add_menu_separator()?;
Ok::<_, systray::Error>(())
})?;
app.add_menu_separator()?;
app.add_menu_item("Quit", |window| {
window.quit();
Ok::<_, systray::Error>(())
})?;
println!("Waiting on message!");
app.wait_for_message()?;
Ok(())
}
// #[cfg(not(target_os = "windows"))]
// fn main() {
// panic!("Not implemented on this platform!");
// }

Binary file not shown.

After

Width:  |  Height:  |  Size: 63 KiB

View File

@@ -0,0 +1,28 @@
use crate::Error;
use std;
pub struct Window {}
impl Window {
pub fn new() -> Result<Window, Error> {
Err(Error::NotImplementedError)
}
pub fn quit(&self) {
unimplemented!()
}
pub fn set_tooltip(&self, _: &str) -> Result<(), Error> {
unimplemented!()
}
pub fn add_menu_item<F>(&self, _: &str, _: F) -> Result<u32, Error>
where
F: std::ops::Fn(&Window) -> () + 'static,
{
unimplemented!()
}
pub fn wait_for_message(&mut self) {
unimplemented!()
}
pub fn set_icon_from_buffer(&self, _: &[u8], _: u32, _: u32) -> Result<(), Error> {
unimplemented!()
}
}

Some files were not shown because too many files have changed in this diff Show More