Merge pull request #1 from Faumaray/claude/gifted-lovelace-1crlx2

Voelin: stream UI, Android app, release hardening, packages for every platform
This commit is contained in:
faumaray authored and GitHub committed 2026-09-27 01:21:21 +03:00
commit 3e77f79c6f
224 files changed
+26148 -2270

No files matched your search

+15
View File
@@ -0,0 +1,15 @@
# Build context for docker/*.Dockerfile and crates/voelin-gateway/Dockerfile:
# the sources only. Builds keep target/ in cache mounts, never in the context.
.git
.claude
target
dist
fuzz/target
fuzz/corpus
fuzz/artifacts
dev/.state
android/.gradle
android/build
android/app/build
android/local.properties
**/node_modules
+21
View File
@@ -0,0 +1,21 @@
name: Security audit
# RustSec advisories for Cargo.lock (what `cargo audit` checks), daily, so
# new advisories show up without a push. CI's cargo-deny job checks the same
# on every push together with licenses and sources.
on:
schedule:
- cron: "41 4 * * *"
workflow_dispatch:
jobs:
advisories:
name: cargo-deny advisories
runs-on: ubuntu-24.04
steps:
- uses: actions/checkout@v4
- uses: EmbarkStudios/cargo-deny-action@v2
with:
command: check advisories
arguments: --workspace
+135 -58
View File
@@ -1,10 +1,29 @@
name: CI
# Fast checks on every push to main and every PR: lint, tests, license and
# advisory checks, and the integration tests against TS3/TS6 servers.
# Packages are built only by release.yml (tags, or by hand), which also runs
# these checks through workflow_call.
# Changes to documentation only need no build (same list twice: no YAML
# anchors in workflows). THIRD_PARTY_NOTICES.md is compiled into the app
# (About page) and checked below.
on:
push:
branches: [main, master]
paths:
- "**"
- "!docs/**"
- "!**/*.md"
- "THIRD_PARTY_NOTICES.md"
pull_request:
paths:
- "**"
- "!docs/**"
- "!**/*.md"
- "THIRD_PARTY_NOTICES.md"
workflow_dispatch:
workflow_call:
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
@@ -34,13 +53,11 @@ jobs:
- name: clippy (workspace, report only)
run: cargo clippy --workspace --all-targets
# Under Xvfb, so X11 tests (screen capture, global hotkeys through XTEST
# input) run instead of skipping. Windows tests run in release.yml.
test:
name: test (${{ matrix.os }})
strategy:
fail-fast: false
matrix:
os: [ubuntu-24.04, windows-2025]
runs-on: ${{ matrix.os }}
name: test (Linux)
runs-on: ubuntu-24.04
steps:
- uses: actions/checkout@v4
- uses: ./.github/actions/system-deps
@@ -49,67 +66,62 @@ jobs:
- uses: Swatinem/rust-cache@v2
- name: Build
run: cargo build --workspace --all-targets --locked
# Under Xvfb, so X11 tests (screen capture, global hotkeys through
# XTEST input) run instead of skipping.
- name: Test (Linux, Xvfb)
if: runner.os == 'Linux'
run: xvfb-run -a bash -c 'TSC_X11_TEST_DISPLAY="$DISPLAY" cargo test --workspace --locked'
- name: Test
if: runner.os != 'Linux'
run: cargo test --workspace --locked
run: xvfb-run -a bash -c 'VOELIN_X11_TEST_DISPLAY="$DISPLAY" cargo test --workspace --locked'
release-build:
name: release build (${{ matrix.os }})
strategy:
fail-fast: false
matrix:
include:
- os: ubuntu-24.04
artifact: tsc-desktop-linux-x86_64
- os: windows-2025
artifact: tsc-desktop-windows-x86_64
runs-on: ${{ matrix.os }}
# Windows-only code compiles and is lint-clean (MSVC, libvpx from vcpkg).
clippy-windows:
name: clippy (Windows)
runs-on: windows-2025
steps:
- uses: actions/checkout@v4
- uses: ./.github/actions/system-deps
- name: Install toolchain (rust-toolchain.toml)
run: rustup toolchain install
- uses: Swatinem/rust-cache@v2
with:
key: release
- name: Build tsc-desktop
run: cargo build --release --locked -p tsc-ui
- name: Stage (Linux)
if: runner.os == 'Linux'
run: |
mkdir -p dist
cp target/release/tsc-desktop dist/
cp packaging/linux/* dist/
# The installer is built when NSIS is on the runner; unsigned.
- name: Stage (Windows)
if: runner.os == 'Windows'
shell: pwsh
run: |
New-Item -ItemType Directory -Force dist | Out-Null
Copy-Item target\release\tsc-desktop.exe dist\
$makensis = (Get-Command makensis -ErrorAction SilentlyContinue).Source
if (-not $makensis) {
$makensis = "${env:ProgramFiles(x86)}\NSIS\makensis.exe"
}
if (Test-Path $makensis) {
$version = (cargo metadata --no-deps --format-version 1 | ConvertFrom-Json).packages |
Where-Object name -eq 'tsc-ui' | Select-Object -ExpandProperty version
& $makensis "/DVERSION=$version" "/DOUTDIR=$PWD\dist" packaging\windows\installer.nsi
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
} else {
Write-Host "::notice::NSIS not found, uploading the executable only"
}
- uses: actions/upload-artifact@v4
with:
name: ${{ matrix.artifact }}
path: dist/
if-no-files-found: error
- name: clippy (own crates, deny warnings)
shell: bash
run: cargo clippy $(scripts/own-crates.sh) --all-targets --no-deps --locked -- -D warnings
# The Android-only code (docs/android.md), for the Android target. The APKs
# are built by release.yml.
clippy-android:
name: clippy (Android)
runs-on: ubuntu-24.04
timeout-minutes: 45
env:
NDK_VERSION: 27.3.13750724
steps:
- uses: actions/checkout@v4
- name: Install toolchain (rust-toolchain.toml)
run: |
rustup toolchain install
rustup target add aarch64-linux-android
- uses: Swatinem/rust-cache@v2
with:
key: android
- uses: actions/setup-java@v4
with:
distribution: temurin
java-version: 17
- name: Android SDK packages
run: |
yes | "$ANDROID_HOME/cmdline-tools/latest/bin/sdkmanager" --licenses > /dev/null
"$ANDROID_HOME/cmdline-tools/latest/bin/sdkmanager" \
"ndk;$NDK_VERSION" "platforms;android-36" > /dev/null
echo "ANDROID_NDK_HOME=$ANDROID_HOME/ndk/$NDK_VERSION" >> "$GITHUB_ENV"
# CMake (libopus) and Slint's Java helper.
echo "ANDROID_NDK_ROOT=$ANDROID_HOME/ndk/$NDK_VERSION" >> "$GITHUB_ENV"
echo "ANDROID_JAR=$ANDROID_HOME/platforms/android-36/android.jar" >> "$GITHUB_ENV"
- name: Install cargo-ndk
run: cargo install cargo-ndk --locked --version 4.1.2
- name: clippy (Android target, deny warnings)
run: |
cargo ndk -t arm64-v8a --platform 29 clippy --locked -p voelin-android -p voelin-ui --no-deps -- -D warnings
cargo ndk -t arm64-v8a --platform 29 clippy --locked -p voelin-media --no-default-features --no-deps -- -D warnings
# Licenses, bans, sources and RustSec advisories (the `cargo audit`
# database); audit.yml repeats the advisories check daily.
deny:
name: cargo-deny
runs-on: ubuntu-24.04
@@ -121,10 +133,33 @@ jobs:
with:
arguments: --workspace
# THIRD_PARTY_NOTICES.md (shown in the About page) must match Cargo.lock.
# cargo-about's output is independent of the host (the graph is filtered
# by the targets in about.toml), so the committed file is compared exactly.
notices:
name: third-party notices
runs-on: ubuntu-24.04
steps:
- uses: actions/checkout@v4
- name: Install toolchain (rust-toolchain.toml)
run: rustup toolchain install
# Caches ~/.cargo/bin too, so cargo-about is built once.
- uses: Swatinem/rust-cache@v2
with:
key: notices
- name: Install cargo-about
run: cargo install cargo-about --locked --version 0.9.2 --features cli
- name: Check THIRD_PARTY_NOTICES.md
run: scripts/notices.sh --check
# voelinctl, the gateway, the engine and voelin-stream against real TS3 and TS6
# servers, including a synthetic VP8 + Opus stream through the TS6 server
# (scripts/it-smoke.sh).
smoke:
name: integration smoke (TS3 + TS6)
runs-on: ubuntu-24.04
needs: test
timeout-minutes: 45
steps:
- uses: actions/checkout@v4
- uses: ./.github/actions/system-deps
@@ -138,3 +173,45 @@ jobs:
- name: Server logs
if: failure()
run: docker compose -f dev/docker-compose.yml logs --no-color
# Client, gateway and stream logs the script keeps in dev/.state.
- name: Upload smoke logs
if: failure()
uses: actions/upload-artifact@v4
with:
name: smoke-logs
path: dev/.state/*.log
if-no-files-found: ignore
# Our WebRTC peers against Chromium's (libwebrtc, as in the official TS6
# client); see tests/interop/README.md. Informational: a failure is
# reported on the job but does not fail the workflow, since it depends on
# a browser download and the runner's network interfaces.
browser-interop:
name: browser interop (voelin-stream, Chromium)
runs-on: ubuntu-24.04
needs: test
continue-on-error: true
timeout-minutes: 30
env:
PLAYWRIGHT_VERSION: 1.56.1
steps:
- uses: actions/checkout@v4
- uses: ./.github/actions/system-deps
- name: Install toolchain (rust-toolchain.toml)
run: rustup toolchain install
- uses: Swatinem/rust-cache@v2
- uses: actions/setup-node@v4
with:
node-version: 22
- name: Cache Playwright browsers
uses: actions/cache@v4
with:
path: ~/.cache/ms-playwright
key: playwright-${{ env.PLAYWRIGHT_VERSION }}-chromium
# Global install: the test finds Playwright through `npm root -g`.
- name: Install Playwright and Chromium
run: |
npm install -g "playwright@$PLAYWRIGHT_VERSION"
playwright install --with-deps chromium
- name: Browser interop test
run: VOELIN_INTEROP=1 cargo test --locked -p voelin-stream --test browser_interop -- --nocapture
+39
View File
@@ -0,0 +1,39 @@
name: Docker builds
# The local builds in docker/ (docs/building.md), checked at every release
# tag and on demand (Actions → Docker builds → Run workflow). Each build
# uploads what it made: the same kinds of packages as release.yml, the
# Windows one cross-compiled with mingw-w64.
on:
push:
tags: ["v*"]
workflow_dispatch:
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
jobs:
build:
name: docker (${{ matrix.platform }})
strategy:
fail-fast: false
matrix:
platform: [linux, windows, android]
runs-on: ubuntu-24.04
timeout-minutes: 120
steps:
- uses: actions/checkout@v4
# The Android build needs more room than the runner leaves free.
- name: Free disk space
run: |
sudo rm -rf /usr/local/lib/android /usr/share/dotnet /opt/ghc /usr/local/.ghcup
df -h /
- name: Build
run: scripts/docker-build.sh ${{ matrix.platform }} --progress=plain
- uses: actions/upload-artifact@v4
with:
name: docker-${{ matrix.platform }}
path: dist/${{ matrix.platform }}/
if-no-files-found: error
+245
View File
@@ -0,0 +1,245 @@
name: Release
# The packages (docs/building.md), made by scripts/package.sh like the Docker
# builds in docker/. A v* tag attaches them to a draft GitHub release; run by
# hand (Actions → Release → Run workflow) they are only uploaded as artifacts.
# The package jobs run alongside the checks, so a manual run yields packages
# even when a check fails; a release needs everything green.
on:
push:
tags: ["v*"]
workflow_dispatch:
concurrency:
group: release-build-${{ github.ref }}
cancel-in-progress: false
permissions:
contents: read
env:
CARGO_TERM_COLOR: always
RUST_BACKTRACE: "0"
jobs:
# The same checks as every push (lint, Linux tests, Windows and Android
# clippy, deny, notices, integration tests).
checks:
uses: ./.github/workflows/ci.yml
test-windows:
name: test (Windows)
runs-on: windows-2025
steps:
- uses: actions/checkout@v4
- uses: ./.github/actions/system-deps
- name: Install toolchain (rust-toolchain.toml)
run: rustup toolchain install
- uses: Swatinem/rust-cache@v2
- name: Build
run: cargo build --workspace --all-targets --locked
- name: Test
run: cargo test --workspace --locked
package-linux:
name: package (Linux)
runs-on: ubuntu-24.04
steps:
- uses: actions/checkout@v4
- uses: ./.github/actions/system-deps
- name: Install toolchain (rust-toolchain.toml)
run: rustup toolchain install
- uses: Swatinem/rust-cache@v2
with:
key: release
- name: Build
run: cargo build --release --locked -p voelin-ui -p voelin-gateway
# dpkg-shlibdeps works out the .deb's dependencies.
- name: Package (.tar.gz, .deb)
run: |
sudo apt-get install -y --no-install-recommends dpkg-dev
scripts/package.sh linux dist
- uses: actions/upload-artifact@v4
with:
name: voelin-linux-x86_64
path: dist/
if-no-files-found: error
package-windows:
name: package (Windows)
runs-on: windows-2025
steps:
- uses: actions/checkout@v4
- uses: ./.github/actions/system-deps
- name: Install toolchain (rust-toolchain.toml)
run: rustup toolchain install
- uses: Swatinem/rust-cache@v2
with:
key: release
- name: Build
run: cargo build --release --locked -p voelin-ui
# The installer is required here: install NSIS when the image lacks it.
- name: NSIS
shell: pwsh
run: |
$makensis = (Get-Command makensis -ErrorAction SilentlyContinue).Source
if (-not $makensis) { $makensis = "${env:ProgramFiles(x86)}\NSIS\makensis.exe" }
if (-not (Test-Path $makensis)) {
choco install nsis -y --no-progress
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
}
"MAKENSIS=$($makensis.Replace('\', '/'))" >> $env:GITHUB_ENV
- name: Package (.zip, installer)
shell: bash
run: scripts/package.sh windows dist
- uses: actions/upload-artifact@v4
with:
name: voelin-windows-x86_64
path: dist/
if-no-files-found: error
# Flatpak bundle from packaging/flatpak (install with
# `flatpak install --user voelin.flatpak`). flatpak-builder builds
# offline, from the crates that flatpak-cargo-generator lists.
package-flatpak:
name: package (Flatpak)
runs-on: ubuntu-24.04
timeout-minutes: 90
container:
image: ghcr.io/flathub-infra/flatpak-github-actions:freedesktop-25.08
options: --privileged
env:
# flatpak-builder-tools, pinned.
FBT_COMMIT: 41c20aa10819cdb2a4f3ca171758a96d1955c018
steps:
- uses: actions/checkout@v4
- name: Cargo sources
run: |
curl -sSfL -o /tmp/flatpak-cargo-generator.py \
"https://raw.githubusercontent.com/flatpak/flatpak-builder-tools/$FBT_COMMIT/cargo/flatpak-cargo-generator.py"
python3 -m venv /tmp/venv
/tmp/venv/bin/pip install --quiet "aiohttp>=3.9.5,<4" "tomlkit>=0.13.3,<1" "PyYAML>=6.0.2,<7"
/tmp/venv/bin/python /tmp/flatpak-cargo-generator.py Cargo.lock -o packaging/flatpak/cargo-sources.json
- uses: flatpak/flatpak-github-actions/flatpak-builder@v6
with:
bundle: voelin.flatpak
manifest-path: packaging/flatpak/io.github.faumaray.Voelin.yml
cache-key: flatpak-builder-${{ hashFiles('Cargo.lock') }}
upload-artifact: false
- uses: actions/upload-artifact@v4
with:
name: voelin-flatpak-x86_64
path: voelin.flatpak
if-no-files-found: error
# The gateway's container image (crates/voelin-gateway/Dockerfile), saved as a
# file: `docker load -i tsgw-image.tar.gz`.
package-gateway-image:
name: package (gateway image)
runs-on: ubuntu-24.04
steps:
- uses: actions/checkout@v4
- name: Build and save
run: |
version=$(sed -n 's/^version = "\(.*\)"$/\1/p' crates/voelin-gateway/Cargo.toml | head -n 1)
docker build -f crates/voelin-gateway/Dockerfile -t "tsgw:$version" -t tsgw:latest .
mkdir -p dist
docker save "tsgw:$version" tsgw:latest | gzip > dist/tsgw-image.tar.gz
(cd dist && sha256sum tsgw-image.tar.gz > SHA256SUMS-gateway)
- uses: actions/upload-artifact@v4
with:
name: tsgw-image
path: dist/
if-no-files-found: error
# The Android app (docs/android.md): a debug APK for arm64-v8a and x86_64
# (emulators), and a signed release APK when the signing secrets are set
# (docs/release.md).
package-android:
name: package (Android)
runs-on: ubuntu-24.04
timeout-minutes: 90
env:
NDK_VERSION: 27.3.13750724
steps:
- uses: actions/checkout@v4
- name: Install toolchain (rust-toolchain.toml)
run: |
rustup toolchain install
rustup target add aarch64-linux-android x86_64-linux-android
- uses: Swatinem/rust-cache@v2
with:
key: android
- uses: actions/setup-java@v4
with:
distribution: temurin
java-version: 17
- name: Android SDK packages
run: |
yes | "$ANDROID_HOME/cmdline-tools/latest/bin/sdkmanager" --licenses > /dev/null
"$ANDROID_HOME/cmdline-tools/latest/bin/sdkmanager" \
"ndk;$NDK_VERSION" "platforms;android-36" "build-tools;36.0.0" > /dev/null
echo "ANDROID_NDK_HOME=$ANDROID_HOME/ndk/$NDK_VERSION" >> "$GITHUB_ENV"
# CMake (libopus) and Slint's Java helper.
echo "ANDROID_NDK_ROOT=$ANDROID_HOME/ndk/$NDK_VERSION" >> "$GITHUB_ENV"
echo "ANDROID_JAR=$ANDROID_HOME/platforms/android-36/android.jar" >> "$GITHUB_ENV"
- name: Install cargo-ndk
run: cargo install cargo-ndk --locked --version 4.1.2
- name: Debug APK
working-directory: android
run: ./gradlew --no-daemon assembleDebug -Pvoelin.abis=arm64-v8a,x86_64
# Only with the signing secrets; an unsigned release APK is not installable.
- name: Release APK (signed)
working-directory: android
env:
KEYSTORE_BASE64: ${{ secrets.ANDROID_KEYSTORE_BASE64 }}
VOELIN_SIGNING_STORE_PASSWORD: ${{ secrets.VOELIN_SIGNING_STORE_PASSWORD }}
VOELIN_SIGNING_KEY_ALIAS: ${{ secrets.VOELIN_SIGNING_KEY_ALIAS }}
VOELIN_SIGNING_KEY_PASSWORD: ${{ secrets.VOELIN_SIGNING_KEY_PASSWORD }}
run: |
if [ -z "$KEYSTORE_BASE64" ]; then
echo "::notice::No ANDROID_KEYSTORE_BASE64 secret: skipping the release APK"
exit 0
fi
export VOELIN_SIGNING_STORE_FILE="$RUNNER_TEMP/release.jks"
echo "$KEYSTORE_BASE64" | base64 -d > "$VOELIN_SIGNING_STORE_FILE"
./gradlew --no-daemon assembleRelease -Pvoelin.abis=arm64-v8a,x86_64
rm -f "$VOELIN_SIGNING_STORE_FILE"
- name: Package
run: scripts/package.sh android dist
- uses: actions/upload-artifact@v4
with:
name: voelin-android
path: dist/
if-no-files-found: error
# A v* tag: every package, attached to a draft GitHub release to review and
# publish by hand.
release:
name: draft release
if: startsWith(github.ref, 'refs/tags/v')
needs: [checks, test-windows, package-linux, package-windows, package-flatpak, package-gateway-image, package-android]
runs-on: ubuntu-24.04
permissions:
contents: write
steps:
- uses: actions/download-artifact@v4
with:
pattern: voelin-*
path: dist
merge-multiple: true
- uses: actions/download-artifact@v4
with:
name: tsgw-image
path: dist
- name: Checksums
run: |
cd dist
rm -f SHA256SUMS-*
sha256sum -- * > SHA256SUMS
- uses: softprops/action-gh-release@v2
with:
draft: true
generate_release_notes: true
files: dist/*
+1
View File
@@ -1,2 +1,3 @@
/target/
/dev/.state/
/dist/
+23
View File
@@ -0,0 +1,23 @@
# Changelog
User-visible changes of the apps and the `tsgw` gateway. The format follows
[Keep a Changelog](https://keepachangelog.com/en/1.1.0/); versions follow
[docs/release.md](docs/release.md#versioning).
## [Unreleased]
The first release is in preparation.
### Added
- Desktop app (Linux Wayland/X11, Windows): servers and bookmarks, channel
tree with talking indicators, server and channel chat, voice with
push-to-talk (global hotkeys), voice activation, echo cancellation, noise
suppression and gain control, per-user volume.
- Observing a server invisibly and chatting in channels without joining
them, through the `tsgw` gateway or own ServerQuery credentials.
- TeamSpeak 6 streams: watching and sharing screens with sound (VP8, VP9,
optional H.264 through Cisco's OpenH264, AV1 decoding).
- `tsgw`: companion gateway for server admins (presence, channel chat
relay, history).
- Opt-in local crash reports; third-party notices in the About page.
Generated
+430 -243
View File
@@ -249,6 +249,27 @@ dependencies = [
"pkg-config",
]
[[package]]
name = "android-activity"
version = "0.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ee91c0c2905bae44f84bfa4e044536541df26b7703fd0888deeb9060fcc44289"
dependencies = [
"android-properties",
"bitflags 2.13.2",
"cc",
"cesu8",
"jni 0.21.1",
"jni-sys 0.3.1",
"libc",
"log",
"ndk 0.8.0",
"ndk-context",
"ndk-sys 0.5.0+25.2.9519653",
"num_enum",
"thiserror 1.0.69",
]
[[package]]
name = "android-activity"
version = "0.6.1"
@@ -258,16 +279,25 @@ dependencies = [
"android-properties",
"bitflags 2.13.2",
"cc",
"jni",
"jni 0.22.4",
"libc",
"log",
"ndk",
"ndk 0.9.0",
"ndk-context",
"ndk-sys",
"ndk-sys 0.6.0+11769913",
"num_enum",
"thiserror 2.0.21",
]
[[package]]
name = "android-build"
version = "0.1.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f9fc9904ad2ad097c3c1cfe2eacaaf0fc24710936fa9ed941cb310b7c6ed2ab7"
dependencies = [
"windows-sys 0.52.0",
]
[[package]]
name = "android-properties"
version = "0.2.2"
@@ -1141,6 +1171,12 @@ dependencies = [
"subtle",
]
[[package]]
name = "cesu8"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6d43a04d8753f35258c91f8ec639f792891f748a1edbd759cf1dcea3382ad83c"
[[package]]
name = "cexpr"
version = "0.6.0"
@@ -1525,11 +1561,11 @@ dependencies = [
"block2 0.6.2",
"coreaudio-rs",
"dasp_sample",
"jni",
"jni 0.22.4",
"js-sys",
"libc",
"mach2",
"ndk",
"ndk 0.9.0",
"ndk-context",
"num-derive",
"num-traits",
@@ -3186,7 +3222,7 @@ dependencies = [
"hickory-proto",
"idna",
"ipnet",
"jni",
"jni 0.22.4",
"rand 0.10.3",
"thiserror 2.0.21",
"tinyvec",
@@ -3204,7 +3240,7 @@ dependencies = [
"data-encoding",
"idna",
"ipnet",
"jni",
"jni 0.22.4",
"once_cell",
"prefix-trie",
"rand 0.10.3",
@@ -3227,7 +3263,7 @@ dependencies = [
"hickory-proto",
"ipconfig",
"ipnet",
"jni",
"jni 0.22.4",
"moka",
"ndk-context",
"once_cell",
@@ -3407,6 +3443,23 @@ dependencies = [
"tracing",
]
[[package]]
name = "i-slint-backend-android-activity"
version = "1.18.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "70d538003a566d7312572ac1435be0704934e46a63d55abdabede513f72332cb"
dependencies = [
"android-activity 0.5.2",
"android-activity 0.6.1",
"android-build",
"i-slint-common",
"i-slint-core",
"i-slint-renderer-skia",
"jni 0.22.4",
"ndk 0.9.0",
"raw-window-handle",
]
[[package]]
name = "i-slint-backend-linuxkms"
version = "1.18.1"
@@ -3439,6 +3492,7 @@ checksum = "fb974705d61ba56034f6129ff61f3e6282a2c0c07752f25e6cb417d81c0f0958"
dependencies = [
"cfg-if",
"cfg_aliases",
"i-slint-backend-android-activity",
"i-slint-backend-linuxkms",
"i-slint-backend-testing",
"i-slint-backend-winit",
@@ -4088,6 +4142,22 @@ version = "1.0.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
[[package]]
name = "jni"
version = "0.21.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1a87aa2bb7d2af34197c04845522473242e1aa17c12f4935d5856491a7fb8c97"
dependencies = [
"cesu8",
"cfg-if",
"combine",
"jni-sys 0.3.1",
"log",
"thiserror 1.0.69",
"walkdir",
"windows-sys 0.45.0",
]
[[package]]
name = "jni"
version = "0.22.4"
@@ -4717,6 +4787,20 @@ version = "1.0.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "308d96db8debc727c3fd9744aac51751243420e46edf401010908da7f8d5e57c"
[[package]]
name = "ndk"
version = "0.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2076a31b7010b17a38c01907c45b945e8f11495ee4dd588309718901b1f7a5b7"
dependencies = [
"bitflags 2.13.2",
"jni-sys 0.3.1",
"log",
"ndk-sys 0.5.0+25.2.9519653",
"num_enum",
"thiserror 1.0.69",
]
[[package]]
name = "ndk"
version = "0.9.0"
@@ -4726,7 +4810,7 @@ dependencies = [
"bitflags 2.13.2",
"jni-sys 0.3.1",
"log",
"ndk-sys",
"ndk-sys 0.6.0+11769913",
"num_enum",
"raw-window-handle",
"thiserror 1.0.69",
@@ -4738,6 +4822,15 @@ version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "27b02d87554356db9e9a873add8782d4ea6e3e58ea071a9adb9a2e8ddb884a8b"
[[package]]
name = "ndk-sys"
version = "0.5.0+25.2.9519653"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8c196769dd60fd4f363e11d948139556a344e79d451aeb2fa2fd040738ef7691"
dependencies = [
"jni-sys 0.3.1",
]
[[package]]
name = "ndk-sys"
version = "0.6.0+11769913"
@@ -6893,7 +6986,7 @@ checksum = "1167586491e2b18b8bfbb293e8180ec17c201c4f076d7cb3070ca964e7598f98"
dependencies = [
"core-foundation 0.10.1",
"core-foundation-sys",
"jni",
"jni 0.22.4",
"log",
"once_cell",
"rustls",
@@ -7445,6 +7538,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "15e477d5ff6fec20909100ff8f7062432ebfbda7a62a0f37d0252aa126f38c83"
dependencies = [
"const-field-offset",
"i-slint-backend-android-activity",
"i-slint-backend-linuxkms",
"i-slint-backend-selector",
"i-slint-common",
@@ -7586,7 +7680,7 @@ dependencies = [
"fastrand",
"js-sys",
"memmap2",
"ndk",
"ndk 0.9.0",
"objc2 0.6.4",
"objc2-core-foundation",
"objc2-core-graphics",
@@ -8574,210 +8668,6 @@ dependencies = [
"tsproto-types",
]
[[package]]
name = "tsc-audio"
version = "0.1.0"
dependencies = [
"cpal",
"hound",
"opus2",
"rtrb",
"rubato",
"serde",
"serde_json",
"sonora",
"sonora-agc2",
"sonora-simd",
"thiserror 2.0.21",
"tracing",
"tsclientlib",
"tsproto-packets",
]
[[package]]
name = "tsc-core"
version = "0.1.0"
dependencies = [
"anyhow",
"futures",
"serde_json",
"thiserror 2.0.21",
"tokio",
"tokio-tungstenite 0.30.0",
"tracing",
"tsc-audio",
"tsc-gateway-proto",
"tsc-model",
"tsc-observer",
"tsc-query",
"tsc-stream",
"tsclientlib",
"tsproto-packets",
]
[[package]]
name = "tsc-gateway"
version = "0.1.0"
dependencies = [
"anyhow",
"axum",
"base64 0.22.1",
"clap",
"futures",
"rand 0.10.3",
"rusqlite",
"serde",
"serde_json",
"sha2 0.10.9",
"thiserror 2.0.21",
"tokio",
"tokio-tungstenite 0.30.0",
"toml",
"tracing",
"tracing-subscriber",
"tsc-gateway-proto",
"tsc-model",
"tsc-observer",
"tsc-query",
]
[[package]]
name = "tsc-gateway-proto"
version = "0.1.0"
dependencies = [
"base64 0.22.1",
"serde",
"serde_json",
"sha-1",
"sha2 0.10.9",
"thiserror 2.0.21",
"tsc-model",
"tsproto",
"tsproto-types",
]
[[package]]
name = "tsc-media"
version = "0.1.0"
dependencies = [
"ashpd",
"bzip2",
"dav1d",
"libvpx-native-sys",
"memmap2",
"openh264",
"pipewire",
"reqwest",
"rustix 1.1.5",
"sha2 0.10.9",
"str0m",
"thiserror 2.0.21",
"tokio",
"tracing",
"wasapi",
"windows-capture",
"x11rb",
"yuv",
]
[[package]]
name = "tsc-model"
version = "0.1.0"
dependencies = [
"serde",
"serde_json",
]
[[package]]
name = "tsc-observer"
version = "0.1.0"
dependencies = [
"thiserror 2.0.21",
"tokio",
"tracing",
"tsc-model",
"tsc-query",
]
[[package]]
name = "tsc-platform"
version = "0.1.0"
dependencies = [
"ashpd",
"dirs",
"futures-util",
"notify-rust",
"serde",
"serde_json",
"thiserror 2.0.21",
"tokio",
"tracing",
"windows 0.62.2",
"x11rb",
]
[[package]]
name = "tsc-query"
version = "0.1.0"
dependencies = [
"reqwest",
"russh",
"serde",
"serde_json",
"thiserror 2.0.21",
"tokio",
"tracing",
]
[[package]]
name = "tsc-store"
version = "0.1.0"
dependencies = [
"keyring",
"rusqlite",
"serde",
"serde_json",
"thiserror 2.0.21",
"tsclientlib",
]
[[package]]
name = "tsc-stream"
version = "0.1.0"
dependencies = [
"anyhow",
"futures",
"serde",
"serde_json",
"str0m",
"thiserror 2.0.21",
"tokio",
"tracing",
"tracing-subscriber",
"tsclientlib",
"tsproto-packets",
]
[[package]]
name = "tsc-ui"
version = "0.1.0"
dependencies = [
"anyhow",
"chrono",
"dirs",
"png",
"slint",
"slint-build",
"tokio",
"tracing",
"tracing-subscriber",
"tsc-core",
"tsc-model",
"tsc-query",
"tsc-store",
"tsclientlib",
]
[[package]]
name = "tsclientlib"
version = "0.2.0"
@@ -8812,31 +8702,6 @@ dependencies = [
"url",
]
[[package]]
name = "tsctl"
version = "0.1.0"
dependencies = [
"anyhow",
"base64 0.22.1",
"clap",
"dirs",
"futures",
"futures-util",
"serde_json",
"tokio",
"tokio-tungstenite 0.30.0",
"tracing",
"tracing-subscriber",
"tsc-audio",
"tsc-gateway-proto",
"tsc-model",
"tsc-observer",
"tsc-query",
"tsc-stream",
"tsclientlib",
"tsproto-packets",
]
[[package]]
name = "tsproto"
version = "0.2.0"
@@ -9188,6 +9053,262 @@ dependencies = [
"syn 2.0.119",
]
[[package]]
name = "voelin-android"
version = "0.1.0"
dependencies = [
"anyhow",
"jni 0.22.4",
"rustls-platform-verifier",
"slint",
"tokio",
"tracing",
"tracing-subscriber",
"voelin-core",
"voelin-media",
"voelin-model",
"voelin-platform",
"voelin-store",
"voelin-ui",
]
[[package]]
name = "voelin-audio"
version = "0.1.0"
dependencies = [
"cpal",
"hound",
"opus2",
"rtrb",
"rubato",
"serde",
"serde_json",
"sonora",
"sonora-agc2",
"sonora-simd",
"thiserror 2.0.21",
"tracing",
"tsclientlib",
"tsproto-packets",
]
[[package]]
name = "voelin-core"
version = "0.1.0"
dependencies = [
"anyhow",
"futures",
"serde_json",
"thiserror 2.0.21",
"tokio",
"tokio-tungstenite 0.30.0",
"tracing",
"tsclientlib",
"tsproto-packets",
"voelin-audio",
"voelin-gateway-proto",
"voelin-media",
"voelin-model",
"voelin-observer",
"voelin-query",
"voelin-stream",
]
[[package]]
name = "voelin-gateway"
version = "0.1.0"
dependencies = [
"anyhow",
"axum",
"base64 0.22.1",
"clap",
"futures",
"rand 0.10.3",
"rusqlite",
"serde",
"serde_json",
"sha2 0.10.9",
"thiserror 2.0.21",
"tokio",
"tokio-tungstenite 0.30.0",
"toml",
"tracing",
"tracing-subscriber",
"voelin-gateway-proto",
"voelin-model",
"voelin-observer",
"voelin-query",
]
[[package]]
name = "voelin-gateway-proto"
version = "0.1.0"
dependencies = [
"base64 0.22.1",
"serde",
"serde_json",
"sha-1",
"sha2 0.10.9",
"thiserror 2.0.21",
"tsproto",
"tsproto-types",
"voelin-model",
]
[[package]]
name = "voelin-media"
version = "0.1.0"
dependencies = [
"ashpd",
"bzip2",
"dav1d",
"libvpx-native-sys",
"memmap2",
"ndk 0.9.0",
"openh264",
"pipewire",
"reqwest",
"rustix 1.1.5",
"sha2 0.10.9",
"str0m",
"thiserror 2.0.21",
"tokio",
"tracing",
"wasapi",
"windows-capture",
"x11rb",
"yuv",
]
[[package]]
name = "voelin-model"
version = "0.1.0"
dependencies = [
"serde",
"serde_json",
]
[[package]]
name = "voelin-observer"
version = "0.1.0"
dependencies = [
"thiserror 2.0.21",
"tokio",
"tracing",
"voelin-model",
"voelin-query",
]
[[package]]
name = "voelin-platform"
version = "0.1.0"
dependencies = [
"ashpd",
"dirs",
"futures-util",
"notify-rust",
"serde",
"serde_json",
"thiserror 2.0.21",
"tokio",
"tracing",
"windows 0.62.2",
"x11rb",
]
[[package]]
name = "voelin-query"
version = "0.1.0"
dependencies = [
"reqwest",
"russh",
"serde",
"serde_json",
"thiserror 2.0.21",
"tokio",
"tracing",
]
[[package]]
name = "voelin-store"
version = "0.1.0"
dependencies = [
"keyring",
"rusqlite",
"serde",
"serde_json",
"thiserror 2.0.21",
"tsclientlib",
]
[[package]]
name = "voelin-stream"
version = "0.1.0"
dependencies = [
"anyhow",
"futures",
"serde",
"serde_json",
"str0m",
"thiserror 2.0.21",
"tokio",
"tracing",
"tracing-subscriber",
"tsclientlib",
"tsproto-packets",
]
[[package]]
name = "voelin-ui"
version = "0.1.0"
dependencies = [
"anyhow",
"chrono",
"dirs",
"png",
"serde",
"serde_json",
"slint",
"slint-build",
"tokio",
"tracing",
"tracing-subscriber",
"tsclientlib",
"voelin-audio",
"voelin-core",
"voelin-model",
"voelin-platform",
"voelin-query",
"voelin-store",
]
[[package]]
name = "voelinctl"
version = "0.1.0"
dependencies = [
"anyhow",
"base64 0.22.1",
"clap",
"dirs",
"futures",
"futures-util",
"png",
"serde_json",
"tokio",
"tokio-tungstenite 0.30.0",
"tracing",
"tracing-subscriber",
"tsclientlib",
"tsproto-packets",
"voelin-audio",
"voelin-core",
"voelin-gateway-proto",
"voelin-model",
"voelin-observer",
"voelin-query",
"voelin-stream",
]
[[package]]
name = "vtable"
version = "0.5.0"
@@ -9449,7 +9570,7 @@ version = "1.2.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "62c35be770821a214dbc362fc26908c853e776c0004294d0b10b8a6bad582f94"
dependencies = [
"jni",
"jni 0.22.4",
"log",
"ndk-context",
"objc2 0.6.4",
@@ -9894,6 +10015,15 @@ dependencies = [
"windows-link 0.2.1",
]
[[package]]
name = "windows-sys"
version = "0.45.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "75283be5efb2831d37ea142365f009c02ec203cd29a3ebecbc093d52315b66d0"
dependencies = [
"windows-targets 0.42.2",
]
[[package]]
name = "windows-sys"
version = "0.48.0"
@@ -9921,6 +10051,21 @@ dependencies = [
"windows-link 0.2.1",
]
[[package]]
name = "windows-targets"
version = "0.42.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8e5180c00cd44c9b1c88adb3693291f1cd93605ded80c250a75d472756b4d071"
dependencies = [
"windows_aarch64_gnullvm 0.42.2",
"windows_aarch64_msvc 0.42.2",
"windows_i686_gnu 0.42.2",
"windows_i686_msvc 0.42.2",
"windows_x86_64_gnu 0.42.2",
"windows_x86_64_gnullvm 0.42.2",
"windows_x86_64_msvc 0.42.2",
]
[[package]]
name = "windows-targets"
version = "0.48.5"
@@ -9979,6 +10124,12 @@ dependencies = [
"windows-link 0.2.1",
]
[[package]]
name = "windows_aarch64_gnullvm"
version = "0.42.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "597a5118570b68bc08d8d59125332c54f1ba9d9adeedeef5b99b02ba2b0698f8"
[[package]]
name = "windows_aarch64_gnullvm"
version = "0.48.5"
@@ -9991,6 +10142,12 @@ version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3"
[[package]]
name = "windows_aarch64_msvc"
version = "0.42.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e08e8864a60f06ef0d0ff4ba04124db8b0fb3be5776a5cd47641e942e58c4d43"
[[package]]
name = "windows_aarch64_msvc"
version = "0.48.5"
@@ -10003,6 +10160,12 @@ version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469"
[[package]]
name = "windows_i686_gnu"
version = "0.42.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c61d927d8da41da96a81f029489353e68739737d3beca43145c8afec9a31a84f"
[[package]]
name = "windows_i686_gnu"
version = "0.48.5"
@@ -10021,6 +10184,12 @@ version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66"
[[package]]
name = "windows_i686_msvc"
version = "0.42.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "44d840b6ec649f480a41c8d80f9c65108b92d89345dd94027bfe06ac444d1060"
[[package]]
name = "windows_i686_msvc"
version = "0.48.5"
@@ -10033,6 +10202,12 @@ version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66"
[[package]]
name = "windows_x86_64_gnu"
version = "0.42.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8de912b8b8feb55c064867cf047dda097f92d51efad5b491dfb98f6bbb70cb36"
[[package]]
name = "windows_x86_64_gnu"
version = "0.48.5"
@@ -10045,6 +10220,12 @@ version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78"
[[package]]
name = "windows_x86_64_gnullvm"
version = "0.42.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "26d41b46a36d453748aedef1486d5c7a85db22e56aff34643984ea85514e94a3"
[[package]]
name = "windows_x86_64_gnullvm"
version = "0.48.5"
@@ -10057,6 +10238,12 @@ version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d"
[[package]]
name = "windows_x86_64_msvc"
version = "0.42.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9aec5da331524158c6d1a4ac0ab1541149c0b9505fde06423b02f5ef0106b9f0"
[[package]]
name = "windows_x86_64_msvc"
version = "0.48.5"
@@ -10076,7 +10263,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a6755fa58a9f8350bd1e472d4c3fcc25f824ec358933bba33306d0b63df5978d"
dependencies = [
"ahash",
"android-activity",
"android-activity 0.6.1",
"atomic-waker",
"bitflags 2.13.2",
"block2 0.5.1",
@@ -10091,7 +10278,7 @@ dependencies = [
"js-sys",
"libc",
"memmap2",
"ndk",
"ndk 0.9.0",
"objc2 0.5.2",
"objc2-app-kit 0.2.2",
"objc2-foundation 0.2.2",
+27 -26
View File
@@ -8,19 +8,20 @@ members = [
"crates/proto/tsproto",
"crates/proto/ts-bookkeeping",
"crates/proto/tsclientlib",
"crates/tsc-audio",
"crates/tsc-core",
"crates/tsc-gateway",
"crates/tsc-gateway-proto",
"crates/tsc-media",
"crates/tsc-model",
"crates/tsc-observer",
"crates/tsc-platform",
"crates/tsc-query",
"crates/tsc-store",
"crates/tsc-stream",
"crates/tsc-ui",
"tools/tsctl",
"crates/voelin-android",
"crates/voelin-audio",
"crates/voelin-core",
"crates/voelin-gateway",
"crates/voelin-gateway-proto",
"crates/voelin-media",
"crates/voelin-model",
"crates/voelin-observer",
"crates/voelin-platform",
"crates/voelin-query",
"crates/voelin-store",
"crates/voelin-stream",
"crates/voelin-ui",
"tools/voelinctl",
]
default-members = [
"crates/proto/tsproto-types",
@@ -29,25 +30,25 @@ default-members = [
"crates/proto/tsproto",
"crates/proto/ts-bookkeeping",
"crates/proto/tsclientlib",
"crates/tsc-audio",
"crates/tsc-core",
"crates/tsc-gateway",
"crates/tsc-gateway-proto",
"crates/tsc-model",
"crates/tsc-observer",
"crates/tsc-platform",
"crates/tsc-query",
"crates/tsc-store",
"crates/tsc-stream",
"crates/tsc-ui",
"tools/tsctl",
"crates/voelin-audio",
"crates/voelin-core",
"crates/voelin-gateway",
"crates/voelin-gateway-proto",
"crates/voelin-model",
"crates/voelin-observer",
"crates/voelin-platform",
"crates/voelin-query",
"crates/voelin-store",
"crates/voelin-stream",
"crates/voelin-ui",
"tools/voelinctl",
]
[workspace.package]
edition = "2024"
rust-version = "1.94"
license = "MIT OR Apache-2.0"
repository = "https://github.com/Faumaray/teamspeak_client_rs"
repository = "https://github.com/Faumaray/Voelin"
publish = false
[workspace.lints.rust]
+57 -31
View File
@@ -1,13 +1,13 @@
# teamspeak_client_rs
# Voelin
A TeamSpeak 3 / TeamSpeak 6 compatible voice client written in Rust, for desktop
Voelin is a TeamSpeak 3 / TeamSpeak 6 compatible voice client written in Rust, for desktop
(Linux Wayland/X11, Windows, later macOS) and mobile (Android, later iOS).
It speaks the TeamSpeak client protocol itself (no official SDK). The protocol
layer is a vendored fork of [ReSpeak/tsclientlib](https://github.com/ReSpeak/tsclientlib).
> Not affiliated with or endorsed by TeamSpeak Systems GmbH. "TeamSpeak" is a
> trademark of its owner; the product name of this client is still to be decided.
> trademark of its owner.
## Goals
@@ -28,66 +28,88 @@ Done so far (milestones M0–M4 and the first part of M5 of [the plan](docs/arch
- `crates/proto/`: vendored tsclientlib, modernised (TS6 fields and stream
messages, faster off-thread Init1 puzzle, `curve25519-dalek` 4, fuzzing fixes;
see [UPSTREAM.md](crates/proto/UPSTREAM.md))
- `crates/tsc-model`: server flavor detection (TS3 / TS6) and capabilities
- `crates/tsc-audio`: Opus voice encoding, framing, resampling, WAV, jitter buffer/mixer, cpal devices
- `crates/tsc-store`: SQLite store for identities, bookmarks, settings and chat history; keyring secrets
- `crates/tsc-query`: ServerQuery client over raw TCP, SSH and HTTP WebQuery (events, rate limiting, keepalive)
- `crates/tsc-observer`: invisible presence (events or polling) and channel-chat relays over ServerQuery
- `crates/tsc-gateway` (`tsgw`) + `tsc-gateway-proto`: companion gateway for server admins. Users log in
- `crates/voelin-model`: server flavor detection (TS3 / TS6) and capabilities
- `crates/voelin-audio`: Opus voice encoding, framing, resampling, WAV, jitter buffer/mixer, cpal devices
- `crates/voelin-store`: SQLite store for identities, bookmarks, settings and chat history; keyring secrets
- `crates/voelin-query`: ServerQuery client over raw TCP, SSH and HTTP WebQuery (events, rate limiting, keepalive)
- `crates/voelin-observer`: invisible presence (events or polling) and channel-chat relays over ServerQuery
- `crates/voelin-gateway` (`tsgw`) + `voelin-gateway-proto`: companion gateway for server admins. Users log in
with their TeamSpeak identity and get presence, channel chat and history without joining voice,
limited by their server permissions ([admin guide](docs/gateway-admin.md))
- `crates/tsc-core`: client engine; sessions merge voice, gateway and query sources, route chat, run audio
- `crates/tsc-ui` (`tsc-desktop`): Slint desktop app: servers, channel tree with talking indicators,
- `crates/voelin-core`: client engine; sessions merge voice, gateway and query sources, route chat, run audio;
the media pipeline for streams (capture → VP8 + Opus → stream, stream → decoder)
- `crates/voelin-ui` (`voelin`): Slint desktop app: servers, channel tree with talking indicators,
chat tabs (own channel via voice, other channels via relay), connect / observe invisibly, mute, push-to-talk
- `crates/tsc-stream`: TeamSpeak 6 streams: stream commands and notifications, JSON signalling,
(in the window and as a global hotkey), audio settings with a level meter, per-client volume, and on
TeamSpeak 6 streams: watch in a viewer, share the screen with sound
- `crates/voelin-stream`: TeamSpeak 6 streams: stream commands and notifications, JSON signalling,
WebRTC peers (str0m) with host and STUN candidates. A live test streams VP8 + Opus between two
clients through a TS6 server
- `tools/tsctl`: headless CLI: channel tree, chat, voice send/record, raw commands, stream events,
- `tools/voelinctl`: headless CLI: channel tree, chat, voice send/record, raw commands, stream events,
`query`, `observe` (invisible presence), `relay` (channel chat without joining) and `gateway`
- `dev/`: TeamSpeak 3.13 and TeamSpeak 6 (6.0.0-beta13.1) servers; `scripts/it-smoke.sh`
checks tree, server chat, channel chat, a voice tone round-trip, invisible presence,
relay chat and the gateway on both
- `fuzz/`: cargo-fuzz targets for packets, commands and the license chain
- `android/` + `crates/voelin-android`: the Android app (the same Slint UI in a NativeActivity,
voice in a foreground service, screen sharing through MediaProjection, MediaCodec, Keystore
passwords). It builds; it has not run on a device yet ([docs/android.md](docs/android.md))
Screen sharing has its protocol and transport layer (`tsc-stream`); capture, codecs and the UI
for it are in progress. No Android build yet.
Screen sharing works between our clients through a TeamSpeak 6 server (VP8 video, Opus audio);
interop with the official TeamSpeak 6 client is not verified yet.
| Connected with voice | Observing invisibly through the gateway |
|---|---|
| ![voice](docs/screenshots/desktop-voice.png) | ![observe](docs/screenshots/desktop-observe.png) |
| **Watching a stream** | **Sharing the screen** |
| ![viewer](docs/screenshots/desktop-stream-viewer.png) | ![share](docs/screenshots/desktop-share-dialog.png) |
## Try it
```sh
# Desktop app
cargo run -p tsc-ui --bin tsc-desktop
cargo run -p voelin-ui --bin voelin
# Local servers (use REGISTRY=mirror.gcr.io if Docker Hub rate-limits you)
docker compose -f dev/docker-compose.yml up -d
cargo run -p tsctl -- connect 127.0.0.1:9987 tree # TeamSpeak 3
cargo run -p tsctl -- connect 127.0.0.1:9988 tree # TeamSpeak 6
cargo run -p tsctl -- connect 127.0.0.1:9988 --nick me repl # interactive chat
cargo run -p tsctl -- connect 127.0.0.1:9988 --nick me voice send --tone 440
cargo run -p tsctl -- connect 127.0.0.1:9988 --nick ear voice record out.wav
cargo run -p voelinctl -- connect 127.0.0.1:9987 tree # TeamSpeak 3
cargo run -p voelinctl -- connect 127.0.0.1:9988 tree # TeamSpeak 6
cargo run -p voelinctl -- connect 127.0.0.1:9988 --nick me repl # interactive chat
cargo run -p voelinctl -- connect 127.0.0.1:9988 --nick me voice send --tone 440
cargo run -p voelinctl -- connect 127.0.0.1:9988 --nick ear voice record out.wav
# ServerQuery (dev password tsc-dev-admin): invisible presence and relay chat
cargo run -p tsctl -- observe ssh 127.0.0.1:10022 --secret tsc-dev-admin --allowlisted
cargo run -p tsctl -- relay ssh 127.0.0.1:10022 --secret tsc-dev-admin --allowlisted --channel 1
# Streams (TeamSpeak 6): share the test pattern (or --source x11), watch and decode it
cargo run -p voelinctl -- connect 127.0.0.1:9988 --nick eye stream watch --save-frame shot.png &
cargo run -p voelinctl -- connect 127.0.0.1:9988 --nick me stream start --synthetic --auto-accept
# ServerQuery (dev password voelin-dev-admin): invisible presence and relay chat
cargo run -p voelinctl -- observe ssh 127.0.0.1:10022 --secret voelin-dev-admin --allowlisted
cargo run -p voelinctl -- relay ssh 127.0.0.1:10022 --secret voelin-dev-admin --allowlisted --channel 1
# Gateway: users without voice, logging in with their identity
cargo run -p tsc-gateway -- --config dev/tsgw-ts6.toml &
cargo run -p tsctl -- gateway ws://127.0.0.1:7788/v1 --identity <file> --presence --open channel:1
cargo run -p voelin-gateway -- --config dev/tsgw-ts6.toml &
cargo run -p voelinctl -- gateway ws://127.0.0.1:7788/v1 --identity <file> --presence --open channel:1
scripts/it-smoke.sh # all of the above, on both servers
```
Other commands: `tsctl identity new`, `tsctl versions`, `tsctl connect <addr> listen|chat|raw`.
`tsctl --help` lists all options.
Other commands: `voelinctl identity new`, `voelinctl versions`, `voelinctl connect <addr> listen|chat|raw`.
`voelinctl --help` lists all options.
Development switches of the desktop app (environment variables): `VOELIN_DATA_DIR` (database),
`VOELIN_AUTOCONNECT=voice|observe`, `VOELIN_SCREENSHOT=<png>` (with `VOELIN_SCREENSHOT_DELAY`),
`VOELIN_DEMO_STREAM=1` (a local test stream in the viewer, no server needed),
`VOELIN_OPEN=share|settings[:<tab>]|about|client`, `VOELIN_AUTOWATCH=1`, `VOELIN_AUTOSHARE=test-pattern`.
Ready-made packages (Linux `.tar.gz`/`.deb`/Flatpak, Windows zip and installer, Android APK,
and the `tsgw` gateway for Linux servers) come from the release workflow (version tags, or run by
hand), and `scripts/docker-build.sh` builds the same ones locally in Docker: see
[docs/building.md](docs/building.md).
Building on Linux needs the ALSA headers (`libasound2-dev`), fontconfig and xkbcommon
headers for the UI (`libfontconfig1-dev libxkbcommon-dev`), plus CMake and a C compiler for
the bundled libopus.
the bundled libopus; for streams also libvpx and PipeWire (see [docs/media.md](docs/media.md#build-requirements)).
## License
@@ -95,5 +117,9 @@ The vendored crates in `crates/proto/` are `MIT OR Apache-2.0` (upstream
`LICENSE-MIT` / `LICENSE-APACHE` are kept there). New crates are declared under
the same terms in `Cargo.toml`.
Third-party notices: the UI toolkit, Slint, is used under its royalty-free license, which
requires an attribution in the app's About page.
Third-party notices: [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md), generated from
`Cargo.lock` by `scripts/notices.sh` and shown in the app's About page. The UI toolkit,
Slint, is used under its royalty-free license, which requires an attribution in the
About page.
Security issues: see [SECURITY.md](SECURITY.md). Releases: [docs/release.md](docs/release.md).
+64
View File
@@ -0,0 +1,64 @@
# Security
## Reporting a vulnerability
Please report security problems privately through GitHub: **Security >
Report a vulnerability** on
https://github.com/Faumaray/Voelin (private vulnerability
reporting). Do not open a public issue for them. If private reporting is not
available, open an issue asking for a contact, without details.
Include what is affected (desktop app, Android app, `tsgw` gateway, `voelinctl`),
the version or commit, and how to reproduce. You should get an answer within
a week. Fixes are released as soon as they are ready and credited in the
changelog unless you prefer otherwise.
Supported versions: until 1.0, only the latest release gets fixes.
In scope: this repository's code and its packages. Problems in TeamSpeak
servers or the official clients belong to TeamSpeak Systems GmbH; problems in
dependencies to their projects (tell us too if this client is affected).
## What the client stores
Everything stays on the device; there is no telemetry and no account with
us.
| What | Where | Protection |
|---|---|---|
| Identities (TeamSpeak private keys) | SQLite database `client.db` in the data directory (`~/.local/share/voelin`, Flatpak `~/.var/app/<app id>/data/voelin`, `%APPDATA%\voelin`, Android app storage) | File permissions of the user account only; not encrypted. An identity is the account on every server that knows it: back it up, do not share the file |
| Server and ServerQuery passwords | OS keyring (Secret Service, Windows Credential Manager, Android Keystore), service `voelin` | Keyring; kept in memory for the session only when there is no keyring |
| Bookmarks, settings, chat history | `client.db` | File permissions; history stays until deleted |
| Crash reports (opt-in) | `crash-reports` in the state directory (`~/.local/state/voelin`, `%LOCALAPPDATA%\voelin`) | Local only, never uploaded. They contain the panic message and a backtrace, which may include server addresses or names; review before attaching one to an issue |
| OpenH264 (opt-in) | Downloaded from Cisco into the app's directories | Loaded only if its SHA-256 matches a known Cisco build |
## What others can see
- **Voice connections** use the TeamSpeak protocol's encryption. The server
and its admins see what any client sees: your nickname, identity, IP
address, channel and messages.
- **Streams (TeamSpeak 6)** are peer-to-peer WebRTC (DTLS-SRTP). Viewers and
streamers exchange ICE candidates, so **they learn each other's IP
addresses**, including local network addresses. Only watch and share
streams with people you are fine sharing your address with.
- **Relayed channel chat** (gateway or own ServerQuery login) is posted by a
query client as `[Nick] text`; people in that channel see it came through
a relay.
## What the gateway (`tsgw`) stores
The gateway is run by a server admin (see
[docs/gateway-admin.md](docs/gateway-admin.md)). In its SQLite database
(`history.path`, default `tsgw.db`):
| Table | Contents | Retention |
|---|---|---|
| `tokens` | SHA-256 hashes of login tokens (never the tokens), the user's unique id and database id, expiry | Removed after expiry (`auth.token_ttl_hours`, default 30 days) |
| `messages` | Relayed server and channel chat: target, time, author unique id and name, text | `history.retention_days` (default 30); disable with `history.enabled = false` |
| `audit` | Time, unique id and action of every login and post | Not pruned automatically; the admin should rotate it |
It holds no voice and no passwords of users: users log in by signing a
challenge with their identity key. The gateway's own ServerQuery credentials
(usually with admin rights) are in its config file, a password file or
`TSGW_QUERY_PASSWORD`: keep them readable only by the gateway's user. Serve
the gateway over TLS (`wss://`) only; tokens travel in its messages.
+11636
View File
File diff suppressed because it is too large. Load diff
+199
View File
@@ -0,0 +1,199 @@
# Third-party notices
<!-- Generated by scripts/notices.sh (cargo-about, about.toml, about.hbs) from
Cargo.lock. Do not edit; regenerate after changing dependencies. -->
This app is licensed under MIT OR Apache-2.0. It contains the third-party
software listed here, whose licenses require these notices.
## Slint
The user interface is built with Slint (https://slint.dev), used under the
Slint Royalty-free Desktop, Mobile, and Web Applications License 2.0
(LicenseRef-Slint-Royalty-free-2.0, full text below). As that license requires,
the About page shows the AboutSlint widget.
## OpenH264
OpenH264 Video Codec provided by Cisco Systems, Inc.
The app does not include OpenH264. Only when you enable H.264 does it download
Cisco's prebuilt OpenH264 binary from ciscobinary.openh264.org, check it
against known checksums and load it at runtime; you can disable it again at
any time. Cisco distributes that binary under the BSD-2-Clause license
(Copyright (c) 2013, Cisco Systems; text below, used by openh264-sys2) and
covers the MPEG LA H.264 patent royalties for it.
## tsclientlib
The TeamSpeak protocol implementation is a fork of tsclientlib
(https://github.com/ReSpeak/tsclientlib), licensed under MIT OR Apache-2.0:
````text
The MIT License (MIT)
Copyright (c) 2017-2020 tsclientlib contributors
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.
````
## Native libraries
- Opus (libopus), compiled into the app: BSD-3-Clause, Copyright 2001-2023
Xiph.Org and contributors; text below, used by libopus_sys.
- AWS-LC (with code from BoringSSL and OpenSSL), compiled into the app:
notices and texts below under ISC, used by aws-lc-sys.
- libvpx (VP8 and VP9): the system library on Linux, compiled into the app on
Windows. Its license and patent grant:
````text
Copyright (c) 2010, The WebM Project authors. 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 Google, nor the WebM 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.
Additional IP Rights Grant (Patents)
------------------------------------
"These implementations" means the copyrightable works that implement the WebM
codecs distributed by Google as part of the WebM Project.
Google 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, transfer, and otherwise
run, modify and propagate the contents of these implementations of WebM, where
such license applies only to those patent claims, both currently owned by
Google and acquired in the future, licensable by Google that are necessarily
infringed by these implementations of WebM. This grant does not include claims
that would be infringed only as a consequence of further modification of these
implementations. If you or your agent or exclusive licensee institute or order
or agree to the institution of patent litigation or any other patent
enforcement activity against any entity (including a cross-claim or
counterclaim in a lawsuit) alleging that any of these implementations of WebM
or any code incorporated within any of these implementations of WebM
constitute direct or contributory patent infringement, or inducement of
patent infringement, then any patent rights granted to you under this License
for these implementations of WebM shall terminate as of the date such
litigation is filed.
````
- Skia (Android app only: Slint draws with it there), compiled into the app
from rust-skia's prebuilt binaries (skia-bindings). Its license:
````text
Copyright (c) 2011 Google Inc. 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 copyright holder 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
OWNER 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.
````
The Skia build includes further libraries under their own licenses:
FreeType (FreeType License: portions of this software are copyright © The
FreeType Project, www.freetype.org, all rights reserved), libpng (PNG
Reference Library License), libjpeg-turbo (IJG License, BSD-3-Clause and
zlib License: this software is based in part on the work of the Independent
JPEG Group), zlib (zlib License), Expat (MIT), Wuffs (Apache-2.0) and the
Vulkan Memory Allocator (MIT).
Other system libraries the app uses at runtime (ALSA, PipeWire, fontconfig,
xkbcommon, the C and C++ runtimes) belong to the operating system and are not
distributed with it.
## Rust crates
Licenses of the Rust crates compiled into the apps, with the crates using
each text. Where a crate offers a choice of licenses, the one shown is the one
this app uses. Texts marked "standard text" were not included in the crate;
the crate's authors are listed as its copyright holders.
| License | Crates |
|---|---|
{{#each overview}}
| {{{name}}} | {{count}} |
{{/each}}
{{#each licenses}}
{{#if first_of_kind}}
### {{{name}}}
{{/if}}
{{#if source_path}}
Used by: {{#each used_by}}{{#unless @first}}, {{/unless}}{{{crate.name}}} {{{crate.version}}}{{/each}}
{{else}}
Standard text, used by:
{{#each used_by}}
- {{{crate.name}}} {{{crate.version}}}{{#if crate.authors}}: {{#each crate.authors}}{{#unless @first}}, {{/unless}}{{{this}}}{{/each}}{{/if}}{{#if crate.repository}} ({{{crate.repository}}}){{/if}}
{{/each}}
{{/if}}
````text
{{{text}}}
````
{{/each}}
+185
View File
@@ -0,0 +1,185 @@
# cargo-about configuration for THIRD_PARTY_NOTICES.md: scripts/notices.sh
# renders about.hbs with it (see docs/release.md). Reference:
# https://embarkstudios.github.io/cargo-about/cli/generate/config.html
#
# The accepted licenses are deny.toml's `[licenses] allow` list; their order is
# the preference when a crate offers a choice ("MIT OR Apache-2.0" shows MIT).
accepted = [
"MIT",
"Apache-2.0",
"Apache-2.0 WITH LLVM-exception",
"BSD-2-Clause",
"BSD-3-Clause",
"ISC",
"Zlib",
"Unicode-3.0",
"CDLA-Permissive-2.0",
"MPL-2.0",
"BSL-1.0",
"Unlicense",
# Slint: GPL-3.0-only OR royalty-free OR commercial. We use the royalty-free
# license, which requires the AboutSlint widget in the About page.
"LicenseRef-Slint-Royalty-free-2.0",
# libbz2-rs-sys (unpacks Cisco's OpenH264 download in voelin-media).
"bzip2-1.0.6",
]
# What the apps ship on: the desktop app on Linux (x86_64, and aarch64 for
# Flathub) and Windows, and the Android app. Crates used only on other
# platforms (macOS, iOS, wasm) are left out.
targets = [
"x86_64-unknown-linux-gnu",
"aarch64-unknown-linux-gnu",
"x86_64-pc-windows-msvc",
"aarch64-linux-android",
"armv7-linux-androideabi",
"x86_64-linux-android",
]
# Build tools (cc, cmake, bindgen, slint-build) and test-only crates are not
# part of any binary we distribute.
ignore-build-dependencies = true
ignore-dev-dependencies = true
# Our own crates (publish = false). The vendored tsclientlib crates in
# crates/proto are credited in about.hbs instead.
private = { ignore = true }
workarounds = ["chrono", "ring", "rustls"]
# Crate specific configuration must come last.
#
# Clarifications replace the license files cargo-about would find; each file
# is pinned by its SHA-256, so a changed text fails generation and gets
# reviewed. After a dependency update: `sha256sum <file>` in the new crate
# version (~/.cargo/registry/src/*/<crate>-<version>/).
# libopus_sys compiles the bundled libopus (opus/, BSD-3-Clause) into the app.
# The crate itself is MIT; LICENSE-old is the ISC license of the code it was
# derived from (audiopus_sys).
[libopus_sys.clarify]
license = "MIT AND ISC AND BSD-3-Clause"
[[libopus_sys.clarify.files]]
path = "LICENSE"
license = "MIT"
checksum = "c5512e4899a9b06c3a286bf69444ebc5314d506e437c334bfd66a2eac7bca3ef"
[[libopus_sys.clarify.files]]
path = "LICENSE-old"
license = "ISC"
checksum = "a6c8bb45880edc99bb13feb04d69fb2f0f73b565dfe209affa60414d2aa4c1a7"
[[libopus_sys.clarify.files]]
path = "opus/COPYING"
license = "BSD-3-Clause"
checksum = "01e1167d54a096d123cf6dfbbeb19587278845c6481d2d66d545669846079551"
# Only the bindings are compiled (voelin-media loads Cisco's binary at runtime),
# but without this every header of the vendored OpenH264 sources would be
# listed. upstream/LICENSE is also the license of Cisco's binary.
[openh264-sys2.clarify]
license = "BSD-2-Clause"
[[openh264-sys2.clarify.files]]
path = "upstream/LICENSE"
checksum = "dd5c1c9668512530fa5a96e4c29ac4033d70a7eeb0eed7a42fddb6dd794ebdbb"
# AWS-LC (DTLS for WebRTC through str0m): LICENSE holds the attributions of
# BoringSSL, OpenSSL and the bundled third-party code plus all license texts.
# It is shown once, under ISC; the other licenses of the expression get their
# standard texts.
[aws-lc-sys.clarify]
license = "ISC AND (Apache-2.0 OR ISC) AND Apache-2.0 AND MIT AND BSD-3-Clause AND (Apache-2.0 OR ISC OR MIT) AND (Apache-2.0 OR ISC OR MIT-0)"
[[aws-lc-sys.clarify.files]]
path = "LICENSE"
license = "ISC"
checksum = "728536b4160e051f86d7c9c388f704866b3d512cd7df97ac3516c65279523c4e"
# Slint keeps its license texts in LICENSES/, which cargo-about does not match
# to the LicenseRef without a clarification. cargo-about 0.9.2 skips clarified
# files whose `license` names the LicenseRef they are the text of (an inverted
# check in generate.rs), so the file is tagged with a distinct LicenseRef; the
# text is still shown under LicenseRef-Slint-Royalty-free-2.0. Revisit when
# updating cargo-about (scripts/notices.sh fails if the text goes missing).
[slint.clarify]
license = "GPL-3.0-only OR LicenseRef-Slint-Royalty-free-2.0 OR LicenseRef-Slint-Software-3.0"
[[slint.clarify.files]]
path = "LICENSES/LicenseRef-Slint-Royalty-free-2.0.md"
license = "LicenseRef-Slint-Royalty-free-2.0-text"
checksum = "5167f5056e850419106ab6265efbdca7cba4d99c849d1445ca0bbf6a1e2315fe"
[slint-macros.clarify]
license = "GPL-3.0-only OR LicenseRef-Slint-Royalty-free-2.0 OR LicenseRef-Slint-Software-3.0"
[[slint-macros.clarify.files]]
path = "LICENSES/LicenseRef-Slint-Royalty-free-2.0.md"
license = "LicenseRef-Slint-Royalty-free-2.0-text"
checksum = "5167f5056e850419106ab6265efbdca7cba4d99c849d1445ca0bbf6a1e2315fe"
[i-slint-common.clarify]
license = "GPL-3.0-only OR LicenseRef-Slint-Royalty-free-2.0 OR LicenseRef-Slint-Software-3.0"
[[i-slint-common.clarify.files]]
path = "LICENSES/LicenseRef-Slint-Royalty-free-2.0.md"
license = "LicenseRef-Slint-Royalty-free-2.0-text"
checksum = "5167f5056e850419106ab6265efbdca7cba4d99c849d1445ca0bbf6a1e2315fe"
[i-slint-compiler.clarify]
license = "GPL-3.0-only OR LicenseRef-Slint-Royalty-free-2.0 OR LicenseRef-Slint-Software-3.0"
[[i-slint-compiler.clarify.files]]
path = "LICENSES/LicenseRef-Slint-Royalty-free-2.0.md"
license = "LicenseRef-Slint-Royalty-free-2.0-text"
checksum = "5167f5056e850419106ab6265efbdca7cba4d99c849d1445ca0bbf6a1e2315fe"
[i-slint-core.clarify]
license = "GPL-3.0-only OR LicenseRef-Slint-Royalty-free-2.0 OR LicenseRef-Slint-Software-3.0"
[[i-slint-core.clarify.files]]
path = "LICENSES/LicenseRef-Slint-Royalty-free-2.0.md"
license = "LicenseRef-Slint-Royalty-free-2.0-text"
checksum = "5167f5056e850419106ab6265efbdca7cba4d99c849d1445ca0bbf6a1e2315fe"
[i-slint-core-macros.clarify]
license = "GPL-3.0-only OR LicenseRef-Slint-Royalty-free-2.0 OR LicenseRef-Slint-Software-3.0"
[[i-slint-core-macros.clarify.files]]
path = "LICENSES/LicenseRef-Slint-Royalty-free-2.0.md"
license = "LicenseRef-Slint-Royalty-free-2.0-text"
checksum = "5167f5056e850419106ab6265efbdca7cba4d99c849d1445ca0bbf6a1e2315fe"
[i-slint-backend-selector.clarify]
license = "GPL-3.0-only OR LicenseRef-Slint-Royalty-free-2.0 OR LicenseRef-Slint-Software-3.0"
[[i-slint-backend-selector.clarify.files]]
path = "LICENSES/LicenseRef-Slint-Royalty-free-2.0.md"
license = "LicenseRef-Slint-Royalty-free-2.0-text"
checksum = "5167f5056e850419106ab6265efbdca7cba4d99c849d1445ca0bbf6a1e2315fe"
[i-slint-backend-winit.clarify]
license = "GPL-3.0-only OR LicenseRef-Slint-Royalty-free-2.0 OR LicenseRef-Slint-Software-3.0"
[[i-slint-backend-winit.clarify.files]]
path = "LICENSES/LicenseRef-Slint-Royalty-free-2.0.md"
license = "LicenseRef-Slint-Royalty-free-2.0-text"
checksum = "5167f5056e850419106ab6265efbdca7cba4d99c849d1445ca0bbf6a1e2315fe"
# Android (voelin-android).
[i-slint-backend-android-activity.clarify]
license = "GPL-3.0-only OR LicenseRef-Slint-Royalty-free-2.0 OR LicenseRef-Slint-Software-3.0"
[[i-slint-backend-android-activity.clarify.files]]
path = "LICENSES/LicenseRef-Slint-Royalty-free-2.0.md"
license = "LicenseRef-Slint-Royalty-free-2.0-text"
checksum = "5167f5056e850419106ab6265efbdca7cba4d99c849d1445ca0bbf6a1e2315fe"
[i-slint-renderer-software.clarify]
license = "GPL-3.0-only OR LicenseRef-Slint-Royalty-free-2.0 OR LicenseRef-Slint-Software-3.0"
[[i-slint-renderer-software.clarify.files]]
path = "LICENSES/LicenseRef-Slint-Royalty-free-2.0.md"
license = "LicenseRef-Slint-Royalty-free-2.0-text"
checksum = "5167f5056e850419106ab6265efbdca7cba4d99c849d1445ca0bbf6a1e2315fe"
[i-slint-renderer-femtovg.clarify]
license = "GPL-3.0-only OR LicenseRef-Slint-Royalty-free-2.0 OR LicenseRef-Slint-Software-3.0"
[[i-slint-renderer-femtovg.clarify.files]]
path = "LICENSES/LicenseRef-Slint-Royalty-free-2.0.md"
license = "LicenseRef-Slint-Royalty-free-2.0-text"
checksum = "5167f5056e850419106ab6265efbdca7cba4d99c849d1445ca0bbf6a1e2315fe"
[i-slint-renderer-skia.clarify]
license = "GPL-3.0-only OR LicenseRef-Slint-Royalty-free-2.0 OR LicenseRef-Slint-Software-3.0"
[[i-slint-renderer-skia.clarify.files]]
path = "LICENSES/LicenseRef-Slint-Royalty-free-2.0.md"
license = "LicenseRef-Slint-Royalty-free-2.0-text"
checksum = "5167f5056e850419106ab6265efbdca7cba4d99c849d1445ca0bbf6a1e2315fe"
+6
View File
@@ -0,0 +1,6 @@
.gradle/
.kotlin/
build/
local.properties
*.jks
*.keystore
+129
View File
@@ -0,0 +1,129 @@
import org.jetbrains.kotlin.gradle.dsl.JvmTarget
plugins {
id("com.android.application")
id("org.jetbrains.kotlin.android")
}
/** The Cargo workspace the native library comes from. */
val workspace: File = rootDir.parentFile
/** `version` of crates/voelin-android, which is the app's version (docs/release.md). */
val crateVersion: String = workspace.resolve("crates/voelin-android/Cargo.toml").readLines()
.first { it.startsWith("version = ") }
.substringAfter('"').substringBefore('"')
/** The version of `crate` in Cargo.lock. */
fun lockedVersion(crate: String): String {
val lines = workspace.resolve("Cargo.lock").readLines()
val at = lines.indexOfFirst { it == "name = \"$crate\"" }
require(at >= 0) { "$crate is not in Cargo.lock" }
return lines[at + 1].substringAfter('"').substringBefore('"')
}
/**
* A release signing setting: a Gradle property (e.g. in
* ~/.gradle/gradle.properties) or an environment variable (CI secrets).
* Never stored in the repository.
*/
fun signing(property: String, env: String): String? =
providers.gradleProperty(property).orElse(providers.environmentVariable(env)).orNull
val releaseStoreFile = signing("voelin.signing.storeFile", "VOELIN_SIGNING_STORE_FILE")
android {
namespace = "io.github.faumaray.voelin"
compileSdk = 36
ndkVersion = "27.3.13750724"
defaultConfig {
// The desktop app id (packaging/README.md); it cannot change after
// the first upload to Google Play.
applicationId = "io.github.faumaray.Voelin"
minSdk = 29
targetSdk = 36
versionName = crateVersion
// major * 1000000 + minor * 1000 + patch (docs/release.md).
versionCode = crateVersion.split('.').map(String::toInt)
.let { (major, minor, patch) -> major * 1_000_000 + minor * 1_000 + patch }
}
signingConfigs {
if (releaseStoreFile != null) {
create("release") {
storeFile = file(releaseStoreFile)
storePassword = signing("voelin.signing.storePassword", "VOELIN_SIGNING_STORE_PASSWORD")
keyAlias = signing("voelin.signing.keyAlias", "VOELIN_SIGNING_KEY_ALIAS")
keyPassword = signing("voelin.signing.keyPassword", "VOELIN_SIGNING_KEY_PASSWORD")
}
}
}
buildTypes {
release {
isMinifyEnabled = true
proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro")
// Unsigned without the signing settings.
signingConfig = signingConfigs.findByName("release")
}
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
}
packaging {
// Stored uncompressed and page-aligned, loaded straight from the APK.
jniLibs.useLegacyPackaging = false
}
}
kotlin {
compilerOptions {
jvmTarget.set(JvmTarget.JVM_17)
}
}
dependencies {
// Must be the version of the rustls-platform-verifier-android crate.
implementation("org.rustls:rustls-platform-verifier:${lockedVersion("rustls-platform-verifier-android")}")
}
// libvoelin_android.so, built with cargo-ndk into build/rust/<build type>/<abi>/
// before the JNI libraries are merged. -Pvoelin.skipCargo=true uses what is
// there (e.g. built by CI in an earlier step).
val abis = providers.gradleProperty("voelin.abis").getOrElse("arm64-v8a,x86_64")
.split(',').map(String::trim).filter(String::isNotEmpty)
val skipCargo = providers.gradleProperty("voelin.skipCargo").map(String::toBoolean).getOrElse(false)
for ((buildType, release) in listOf("debug" to false, "release" to true)) {
val out = layout.buildDirectory.dir("rust/$buildType")
val name = buildType.replaceFirstChar(Char::uppercase)
val cargo = tasks.register<Exec>("cargoBuild$name") {
group = "build"
description = "Builds the Rust library for $abis with cargo-ndk ($buildType)."
workingDir = workspace
val command = mutableListOf("cargo", "ndk", "--platform", "29", "-o", out.get().asFile.path)
abis.forEach { command += listOf("-t", it) }
command += listOf("build", "-p", "voelin-android")
if (release) command += "--release"
commandLine(command)
val ndk = android.ndkDirectory.path
environment("ANDROID_NDK_HOME", ndk)
// CMake (the bundled libopus) finds the NDK through this one.
environment("ANDROID_NDK_ROOT", ndk)
environment("ANDROID_HOME", android.sdkDirectory.path)
// Slint compiles its Java helper against this.
environment(
"ANDROID_JAR",
android.sdkDirectory.resolve("platforms/android-${android.compileSdk}/android.jar").path,
)
}
android.sourceSets.getByName(buildType).jniLibs.srcDir(out)
if (!skipCargo) {
tasks.configureEach {
if (this.name == "merge${name}JniLibFolders") dependsOn(cargo)
}
}
}
+7
View File
@@ -0,0 +1,7 @@
# Called from Rust through JNI by name.
-keep class io.github.faumaray.voelin.Bridge { *; }
-keep class io.github.faumaray.voelin.Native { *; }
-keep class io.github.faumaray.voelin.VoelinApp { *; }
# rustls-platform-verifier's Kotlin component, also called from Rust.
-keep class org.rustls.platformverifier.** { *; }
+62
View File
@@ -0,0 +1,62 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<!-- Voice, and capturing what the device plays while sharing the screen. -->
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_MICROPHONE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PROJECTION" />
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<!-- Slint renders with OpenGL ES. -->
<uses-feature android:glEsVersion="0x00020000" android:required="true" />
<!--
allowBackup=false: the database holds the TeamSpeak identity (a
private key) and the Keystore key of the saved passwords cannot be
restored on another device anyway.
-->
<application
android:name=".VoelinApp"
android:allowBackup="false"
android:hasCode="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/Theme.Voelin">
<!--
The Rust UI runs in this NativeActivity (android.app.lib_name).
Configuration changes (rotation, keyboard, dark mode) are handled
by the native side instead of recreating the activity.
-->
<activity
android:name=".MainActivity"
android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|keyboard|keyboardHidden|navigation|uiMode|density|fontScale|locale|layoutDirection"
android:exported="true"
android:launchMode="singleTask"
android:windowSoftInputMode="adjustResize">
<meta-data
android:name="android.app.lib_name"
android:value="voelin_android" />
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<!-- Keeps the microphone and the connection while in the background. -->
<service
android:name=".VoiceService"
android:exported="false"
android:foregroundServiceType="microphone" />
<!-- Holds the MediaProjection while the screen is shared. -->
<service
android:name=".ScreenCaptureService"
android:exported="false"
android:foregroundServiceType="mediaProjection" />
</application>
</manifest>
@@ -0,0 +1,77 @@
package io.github.faumaray.voelin
import android.Manifest
import android.content.Context
import android.content.pm.PackageManager
import android.os.Build
/**
* What the Rust library (crates/voelin-android/src/bridge.rs) calls, from any
* thread. Keep the names and signatures in step with it.
*/
object Bridge {
private val app: VoelinApp get() = VoelinApp.instance
@JvmStatic
fun context(): Context = app
/** Ask for the microphone (voice) and notification (services) permissions. */
@JvmStatic
fun requestPermissions() {
val activity = MainActivity.current?.get() ?: return
val wanted = buildList {
add(Manifest.permission.RECORD_AUDIO)
if (Build.VERSION.SDK_INT >= 33) add(Manifest.permission.POST_NOTIFICATIONS)
}.filter { activity.checkSelfPermission(it) != PackageManager.PERMISSION_GRANTED }
if (wanted.isNotEmpty()) {
activity.runOnUiThread { activity.requestPermissions(wanted.toTypedArray(), 1) }
}
}
/**
* Run the voice service with this notification text (`muted`: the action
* offers Unmute); null stops it.
*/
@JvmStatic
fun setVoiceNotification(text: String?, muted: Boolean) {
if (text == null) VoiceService.stop(app) else VoiceService.start(app, text, muted)
}
/** Ask the user to share the screen; the answer goes to Native.onScreenCaptureResult. */
@JvmStatic
fun requestScreenCapture(fps: Int, maxSize: Int) {
val activity = MainActivity.current?.get()
if (activity == null) {
Native.onScreenCaptureResult(false, "the app is not in the foreground")
return
}
activity.runOnUiThread { activity.requestScreenCapture(fps, maxSize) }
}
@JvmStatic
fun stopScreenCapture() {
ScreenCaptureService.stop(app)
}
/** Capture what the device plays; false without a running screen capture. */
@JvmStatic
fun startSystemAudio(): Boolean = ScreenCaptureService.startAudio()
@JvmStatic
fun stopSystemAudio() {
ScreenCaptureService.stopAudio()
}
@JvmStatic
fun secretGet(key: String): String? = SecretStore.get(app, key)
@JvmStatic
fun secretSet(key: String, value: String) {
SecretStore.set(app, key, value)
}
@JvmStatic
fun secretDelete(key: String) {
SecretStore.delete(app, key)
}
}
@@ -0,0 +1,67 @@
package io.github.faumaray.voelin
import android.app.NativeActivity
import android.content.Intent
import android.media.projection.MediaProjectionManager
import android.os.Bundle
import java.lang.ref.WeakReference
/**
* The window: a NativeActivity running `android_main` of libvoelin_android.so
* (the Slint UI). Kotlin only handles what needs an Activity: permission
* prompts and the screen-capture consent dialog.
*/
class MainActivity : NativeActivity() {
private var captureFps = 30
private var captureMaxSize = 1920
override fun onCreate(savedInstanceState: Bundle?) {
current = WeakReference(this)
super.onCreate(savedInstanceState)
}
override fun onDestroy() {
if (current?.get() === this) current = null
super.onDestroy()
}
/**
* Back leaves the app like Home instead of finishing the activity, so the
* window (and its state) stays while voice goes on in the background.
*/
@Deprecated("Deprecated in Java")
override fun onBackPressed() {
moveTaskToBack(true)
}
/** Show the system's "start recording or casting?" dialog. */
fun requestScreenCapture(fps: Int, maxSize: Int) {
captureFps = fps
captureMaxSize = maxSize
val manager = getSystemService(MediaProjectionManager::class.java)
@Suppress("DEPRECATION")
startActivityForResult(manager.createScreenCaptureIntent(), REQUEST_SCREEN_CAPTURE)
}
@Deprecated("Deprecated in Java")
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
@Suppress("DEPRECATION")
super.onActivityResult(requestCode, resultCode, data)
if (requestCode != REQUEST_SCREEN_CAPTURE) return
if (resultCode == RESULT_OK && data != null) {
// The service reports the outcome to Native.onScreenCaptureResult.
ScreenCaptureService.start(this, resultCode, data, captureFps, captureMaxSize)
} else {
Native.onScreenCaptureResult(false, null)
}
}
companion object {
private const val REQUEST_SCREEN_CAPTURE = 1001
/** The activity in front, if any. */
@Volatile
var current: WeakReference<MainActivity>? = null
private set
}
}
@@ -0,0 +1,45 @@
package io.github.faumaray.voelin
import java.nio.ByteBuffer
/** Callbacks into the Rust library (crates/voelin-android/src/bridge.rs). */
object Native {
init {
// Already loaded by the NativeActivity; this registers it for JNI
// lookups from this class loader.
System.loadLibrary("voelin_android")
}
/** The user answered the screen-capture dialog (`error`: why it failed). */
@JvmStatic
external fun onScreenCaptureResult(granted: Boolean, error: String?)
/** An RGBA_8888 frame. Returns false when frames are no longer wanted. */
@JvmStatic
external fun onScreenFrame(
pixels: ByteBuffer,
width: Int,
height: Int,
rowStride: Int,
timestampNs: Long,
): Boolean
/** The projection ended (by the app, the user or the system). */
@JvmStatic
external fun onScreenCaptureStopped()
/**
* `count` interleaved 48 kHz float samples of what the device plays.
* Returns false when audio is no longer wanted.
*/
@JvmStatic
external fun onSystemAudio(samples: FloatArray, count: Int, channels: Int, timestampNs: Long): Boolean
/** "Disconnect" in the voice notification. */
@JvmStatic
external fun onDisconnectVoice()
/** "Mute" / "Unmute" in the voice notification. */
@JvmStatic
external fun onToggleMute()
}
@@ -0,0 +1,61 @@
package io.github.faumaray.voelin
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
/** Notification channels and the notifications of the foreground services. */
object Notifications {
const val CHANNEL_VOICE = "voice"
const val CHANNEL_SCREEN = "screen"
fun createChannels(context: Context) {
val manager = context.getSystemService(NotificationManager::class.java)
manager.createNotificationChannel(
NotificationChannel(
CHANNEL_VOICE,
context.getString(R.string.channel_voice),
NotificationManager.IMPORTANCE_LOW,
),
)
manager.createNotificationChannel(
NotificationChannel(
CHANNEL_SCREEN,
context.getString(R.string.channel_screen),
NotificationManager.IMPORTANCE_LOW,
),
)
}
/** Tapping a notification brings the app back. */
private fun openApp(context: Context): PendingIntent = PendingIntent.getActivity(
context,
0,
Intent(context, MainActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT),
PendingIntent.FLAG_IMMUTABLE,
)
/** An ongoing notification with `actions` (title, intent). */
fun ongoing(
context: Context,
channel: String,
text: String,
vararg actions: Pair<String, PendingIntent>,
): Notification {
val builder = Notification.Builder(context, channel)
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle(context.getString(R.string.app_name))
.setContentText(text)
.setContentIntent(openApp(context))
.setOngoing(true)
.setOnlyAlertOnce(true)
.setCategory(Notification.CATEGORY_CALL)
for ((title, intent) in actions) {
builder.addAction(Notification.Action.Builder(null, title, intent).build())
}
return builder.build()
}
}
@@ -0,0 +1,257 @@
package io.github.faumaray.voelin
import android.Manifest
import android.app.PendingIntent
import android.app.Service
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.content.pm.ServiceInfo
import android.graphics.PixelFormat
import android.hardware.display.DisplayManager
import android.hardware.display.VirtualDisplay
import android.media.AudioAttributes
import android.media.AudioFormat
import android.media.AudioPlaybackCaptureConfiguration
import android.media.AudioRecord
import android.media.ImageReader
import android.media.projection.MediaProjection
import android.media.projection.MediaProjectionManager
import android.os.Build
import android.os.Handler
import android.os.HandlerThread
import android.os.IBinder
import android.os.Looper
import android.util.Log
import android.view.Display
import android.view.Surface
import kotlin.concurrent.thread
import kotlin.math.max
import kotlin.math.roundToInt
/**
* Screen sharing: holds the MediaProjection (a `mediaProjection` foreground
* service, as Android requires), mirrors the display into an ImageReader and
* hands each RGBA frame to Native.onScreenFrame; optionally captures what the
* device plays (AudioPlaybackCapture) for Native.onSystemAudio.
*/
class ScreenCaptureService : Service() {
private var projection: MediaProjection? = null
private var display: VirtualDisplay? = null
private var reader: ImageReader? = null
private var worker: HandlerThread? = null
@Volatile
private var audioRunning = false
private var audioThread: Thread? = null
private val main = Handler(Looper.getMainLooper())
override fun onBind(intent: Intent?): IBinder? = null
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
if (intent == null || intent.action == ACTION_STOP) {
stopSelf()
return START_NOT_STICKY
}
if (projection != null) return START_NOT_STICKY
val stop = PendingIntent.getService(
this,
0,
Intent(this, ScreenCaptureService::class.java).setAction(ACTION_STOP),
PendingIntent.FLAG_IMMUTABLE,
)
val notification = Notifications.ongoing(
this,
Notifications.CHANNEL_SCREEN,
getString(R.string.screen_sharing),
getString(R.string.stop_sharing) to stop,
)
try {
// Must be in the foreground before getMediaProjection (Android 14).
startForeground(ID, notification, ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PROJECTION)
val data = if (Build.VERSION.SDK_INT >= 33) {
intent.getParcelableExtra(EXTRA_DATA, Intent::class.java)
} else {
@Suppress("DEPRECATION")
intent.getParcelableExtra(EXTRA_DATA)
} ?: throw IllegalStateException("no projection data")
val manager = getSystemService(MediaProjectionManager::class.java)
val projection = manager.getMediaProjection(intent.getIntExtra(EXTRA_RESULT, 0), data)
?: throw IllegalStateException("the projection was refused")
this.projection = projection
instance = this
startVideo(projection, intent.getIntExtra(EXTRA_FPS, 30), intent.getIntExtra(EXTRA_MAX_SIZE, 1920))
Native.onScreenCaptureResult(true, null)
} catch (e: Exception) {
Log.w(TAG, "screen capture failed", e)
Native.onScreenCaptureResult(false, e.message ?: e.toString())
stopSelf()
}
return START_NOT_STICKY
}
private fun startVideo(projection: MediaProjection, fps: Int, maxSize: Int) {
val worker = HandlerThread("voelin-screen").also { it.start() }
this.worker = worker
val handler = Handler(worker.looper)
// The user or the system can end the projection (status bar chip,
// screen lock); registered before the virtual display (Android 14).
projection.registerCallback(object : MediaProjection.Callback() {
override fun onStop() {
main.post { stopSelf() }
}
}, handler)
val metrics = resources.displayMetrics
val screen = getSystemService(DisplayManager::class.java).getDisplay(Display.DEFAULT_DISPLAY)
val mode = screen.mode
// The mode is in the display's natural orientation; match the current
// one. (Rotating while sharing letterboxes the picture.)
val rotated = screen.rotation == Surface.ROTATION_90 || screen.rotation == Surface.ROTATION_270
val (fullWidth, fullHeight) = if (rotated) {
mode.physicalHeight to mode.physicalWidth
} else {
mode.physicalWidth to mode.physicalHeight
}
val scale = minOf(1.0, maxSize.toDouble() / max(fullWidth, fullHeight))
// Even sizes, as video encoders want.
val width = ((fullWidth * scale).roundToInt() / 2 * 2).coerceAtLeast(2)
val height = ((fullHeight * scale).roundToInt() / 2 * 2).coerceAtLeast(2)
val reader = ImageReader.newInstance(width, height, PixelFormat.RGBA_8888, 3)
this.reader = reader
val interval = 1_000_000_000L / fps.coerceIn(1, 60)
var last = 0L
reader.setOnImageAvailableListener({ r ->
val image = r.acquireLatestImage() ?: return@setOnImageAvailableListener
try {
// The display renders at its own rate; pass on at most `fps`.
if (image.timestamp - last < interval) return@setOnImageAvailableListener
last = image.timestamp
val plane = image.planes[0]
val wanted = Native.onScreenFrame(plane.buffer, image.width, image.height, plane.rowStride, image.timestamp)
if (!wanted) main.post { stopSelf() }
} finally {
image.close()
}
}, handler)
display = projection.createVirtualDisplay(
"voelin-screen",
width,
height,
metrics.densityDpi,
DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR,
reader.surface,
null,
handler,
)
}
/** Capture media, game and unknown-usage playback as 48 kHz stereo float. */
private fun startAudioCapture(): Boolean {
val projection = projection ?: return false
if (audioRunning) return true
if (checkSelfPermission(Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
return false
}
val config = AudioPlaybackCaptureConfiguration.Builder(projection)
.addMatchingUsage(AudioAttributes.USAGE_MEDIA)
.addMatchingUsage(AudioAttributes.USAGE_GAME)
.addMatchingUsage(AudioAttributes.USAGE_UNKNOWN)
.build()
val format = AudioFormat.Builder()
.setEncoding(AudioFormat.ENCODING_PCM_FLOAT)
.setSampleRate(SAMPLE_RATE)
.setChannelMask(AudioFormat.CHANNEL_IN_STEREO)
.build()
val minimum = AudioRecord.getMinBufferSize(SAMPLE_RATE, AudioFormat.CHANNEL_IN_STEREO, AudioFormat.ENCODING_PCM_FLOAT)
val record = try {
AudioRecord.Builder()
.setAudioFormat(format)
.setAudioPlaybackCaptureConfig(config)
// A tenth of a second.
.setBufferSizeInBytes(max(minimum, SAMPLE_RATE / 10 * 2 * 4))
.build()
} catch (e: Exception) {
Log.w(TAG, "system audio capture unavailable", e)
return false
}
audioRunning = true
record.startRecording()
audioThread = thread(name = "voelin-system-audio") {
// 10 ms of stereo.
val buffer = FloatArray(SAMPLE_RATE / 100 * 2)
try {
while (audioRunning) {
val read = record.read(buffer, 0, buffer.size, AudioRecord.READ_BLOCKING)
if (read < 0) break
if (read > 0 && !Native.onSystemAudio(buffer, read, 2, System.nanoTime())) break
}
} finally {
audioRunning = false
record.stop()
record.release()
}
}
return true
}
private fun stopAudioCapture() {
audioRunning = false
audioThread?.join(500)
audioThread = null
}
override fun onDestroy() {
if (instance === this) instance = null
stopAudioCapture()
display?.release()
display = null
reader?.close()
reader = null
projection?.stop()
projection = null
worker?.quitSafely()
worker = null
Native.onScreenCaptureStopped()
super.onDestroy()
}
companion object {
private const val TAG = "ScreenCaptureService"
private const val ID = 2
private const val SAMPLE_RATE = 48_000
private const val ACTION_STOP = "io.github.faumaray.voelin.STOP_SHARING"
private const val EXTRA_RESULT = "result"
private const val EXTRA_DATA = "data"
private const val EXTRA_FPS = "fps"
private const val EXTRA_MAX_SIZE = "max_size"
@Volatile
private var instance: ScreenCaptureService? = null
/** Start capturing with the consent the user just gave. */
fun start(context: Context, resultCode: Int, data: Intent, fps: Int, maxSize: Int) {
val intent = Intent(context, ScreenCaptureService::class.java)
.putExtra(EXTRA_RESULT, resultCode)
.putExtra(EXTRA_DATA, data)
.putExtra(EXTRA_FPS, fps)
.putExtra(EXTRA_MAX_SIZE, maxSize)
context.startForegroundService(intent)
}
fun stop(context: Context) {
context.stopService(Intent(context, ScreenCaptureService::class.java))
}
fun startAudio(): Boolean {
val service = instance ?: return false
return service.startAudioCapture()
}
fun stopAudio() {
instance?.stopAudioCapture()
}
}
}
@@ -0,0 +1,81 @@
package io.github.faumaray.voelin
import android.content.Context
import android.security.keystore.KeyGenParameterSpec
import android.security.keystore.KeyProperties
import android.util.Base64
import android.util.Log
import java.security.KeyStore
import javax.crypto.Cipher
import javax.crypto.KeyGenerator
import javax.crypto.SecretKey
import javax.crypto.spec.GCMParameterSpec
/**
* Saved passwords (server, query), for the Rust side's `Secrets`.
*
* Each value is encrypted with AES-256-GCM under a key that never leaves the
* Android Keystore (hardware-backed where available); the key name is the
* associated data, so a value cannot be moved to another key. Only the
* ciphertext is stored, in private preferences excluded from backups.
*/
object SecretStore {
private const val TAG = "SecretStore"
private const val KEYSTORE = "AndroidKeyStore"
private const val KEY_ALIAS = "voelin-secrets"
private const val PREFS = "secrets"
private const val TRANSFORMATION = "AES/GCM/NoPadding"
private const val IV_BYTES = 12
private const val TAG_BITS = 128
private fun key(): SecretKey {
val keyStore = KeyStore.getInstance(KEYSTORE).apply { load(null) }
(keyStore.getKey(KEY_ALIAS, null) as? SecretKey)?.let { return it }
val generator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, KEYSTORE)
generator.init(
KeyGenParameterSpec.Builder(
KEY_ALIAS,
KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT,
)
.setBlockModes(KeyProperties.BLOCK_MODE_GCM)
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
.setKeySize(256)
.build(),
)
return generator.generateKey()
}
private fun prefs(context: Context) = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
/** The value, or null if none is saved or it cannot be decrypted. */
@Synchronized
fun get(context: Context, name: String): String? {
val stored = prefs(context).getString(name, null) ?: return null
return try {
val bytes = Base64.decode(stored, Base64.NO_WRAP)
val cipher = Cipher.getInstance(TRANSFORMATION)
cipher.init(Cipher.DECRYPT_MODE, key(), GCMParameterSpec(TAG_BITS, bytes, 0, IV_BYTES))
cipher.updateAAD(name.toByteArray())
String(cipher.doFinal(bytes, IV_BYTES, bytes.size - IV_BYTES), Charsets.UTF_8)
} catch (e: Exception) {
// E.g. the key was lost (the device's lock screen was reset).
Log.w(TAG, "cannot decrypt $name", e)
null
}
}
@Synchronized
fun set(context: Context, name: String, value: String) {
val cipher = Cipher.getInstance(TRANSFORMATION)
cipher.init(Cipher.ENCRYPT_MODE, key())
cipher.updateAAD(name.toByteArray())
val sealed = cipher.iv + cipher.doFinal(value.toByteArray(Charsets.UTF_8))
check(cipher.iv.size == IV_BYTES)
prefs(context).edit().putString(name, Base64.encodeToString(sealed, Base64.NO_WRAP)).commit()
}
@Synchronized
fun delete(context: Context, name: String) {
prefs(context).edit().remove(name).commit()
}
}
@@ -0,0 +1,17 @@
package io.github.faumaray.voelin
import android.app.Application
/** The process's application object; the Rust side reaches Android through it. */
class VoelinApp : Application() {
override fun onCreate() {
super.onCreate()
instance = this
Notifications.createChannels(this)
}
companion object {
lateinit var instance: VoelinApp
private set
}
}
@@ -0,0 +1,110 @@
package io.github.faumaray.voelin
import android.app.Notification
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.Service
import android.content.Context
import android.content.Intent
import android.content.pm.ServiceInfo
import android.os.Build
import android.os.IBinder
import android.util.Log
/**
* Foreground service while a voice connection exists: Android keeps the
* process, the network and (type microphone) the microphone of an app in
* the background only this way. The Rust side starts, updates and stops it.
*/
class VoiceService : Service() {
override fun onBind(intent: Intent?): IBinder? = null
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
when (intent?.action) {
ACTION_DISCONNECT -> {
Native.onDisconnectVoice()
return START_NOT_STICKY
}
ACTION_TOGGLE_MUTE -> {
Native.onToggleMute()
return START_NOT_STICKY
}
}
val text = intent?.getStringExtra(EXTRA_TEXT) ?: getString(R.string.voice_connected)
val muted = intent?.getBooleanExtra(EXTRA_MUTED, false) ?: false
try {
if (Build.VERSION.SDK_INT >= 30) {
startForeground(ID, notification(this, text, muted), ServiceInfo.FOREGROUND_SERVICE_TYPE_MICROPHONE)
} else {
startForeground(ID, notification(this, text, muted))
}
running = this
} catch (e: RuntimeException) {
// E.g. no microphone permission (Android 14 refuses the type):
// voice then works only while the app is in front.
Log.w(TAG, "voice service cannot run in the foreground", e)
stopSelf()
}
return START_NOT_STICKY
}
override fun onDestroy() {
if (running === this) running = null
super.onDestroy()
}
companion object {
private const val TAG = "VoiceService"
private const val ID = 1
private const val EXTRA_TEXT = "text"
private const val EXTRA_MUTED = "muted"
private const val ACTION_DISCONNECT = "io.github.faumaray.voelin.DISCONNECT"
private const val ACTION_TOGGLE_MUTE = "io.github.faumaray.voelin.TOGGLE_MUTE"
@Volatile
private var running: VoiceService? = null
private fun action(context: Context, action: String, request: Int): PendingIntent =
PendingIntent.getService(
context,
request,
Intent(context, VoiceService::class.java).setAction(action),
PendingIntent.FLAG_IMMUTABLE,
)
private fun notification(context: Context, text: String, muted: Boolean): Notification =
Notifications.ongoing(
context,
Notifications.CHANNEL_VOICE,
text,
context.getString(if (muted) R.string.unmute else R.string.mute) to
action(context, ACTION_TOGGLE_MUTE, 1),
context.getString(R.string.disconnect) to action(context, ACTION_DISCONNECT, 0),
)
/** Start the service, or update its notification when it runs. */
fun start(context: Context, text: String, muted: Boolean) {
val service = running
if (service != null) {
service.getSystemService(NotificationManager::class.java)
.notify(ID, notification(service, text, muted))
return
}
try {
context.startForegroundService(
Intent(context, VoiceService::class.java)
.putExtra(EXTRA_TEXT, text)
.putExtra(EXTRA_MUTED, muted),
)
} catch (e: RuntimeException) {
// Not allowed from the background (Android 12+). Voice is
// connected from the UI, so this should not happen.
Log.w(TAG, "cannot start the voice service", e)
}
}
fun stop(context: Context) {
context.stopService(Intent(context, VoiceService::class.java))
}
}
}
@@ -0,0 +1,26 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
Placeholder icon (packaging/linux/io.github.faumaray.Voelin.svg): a
speech bubble with sound waves, sized for the adaptive icon's safe zone.
-->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="108dp"
android:height="108dp"
android:viewportWidth="128"
android:viewportHeight="128">
<group
android:pivotX="64"
android:pivotY="64"
android:scaleX="0.8"
android:scaleY="0.8"
android:translateY="-5">
<path
android:fillColor="#FFFFFFFF"
android:pathData="M36,40h56a8,8 0,0 1,8 8v28a8,8 0,0 1,-8 8H60l-16,14v-14h-8a8,8 0,0 1,-8 -8V48a8,8 0,0 1,8 -8z" />
<path
android:pathData="M52,56v12M64,50v24M76,56v12"
android:strokeWidth="5"
android:strokeColor="#FF238636"
android:strokeLineCap="round" />
</group>
</vector>
@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Monochrome speech bubble with sound waves (status bar, themed icon). -->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="128"
android:viewportHeight="128">
<path
android:fillColor="#FFFFFFFF"
android:fillType="evenOdd"
android:pathData="M36,40h56a8,8 0,0 1,8 8v28a8,8 0,0 1,-8 8H60l-16,14v-14h-8a8,8 0,0 1,-8 -8V48a8,8 0,0 1,8 -8z M49.5,56a2.5,2.5 0,0 1,5 0v12a2.5,2.5 0,0 1,-5 0z M61.5,50a2.5,2.5 0,0 1,5 0v24a2.5,2.5 0,0 1,-5 0z M73.5,56a2.5,2.5 0,0 1,5 0v12a2.5,2.5 0,0 1,-5 0z" />
</vector>
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@color/ic_launcher_background" />
<foreground android:drawable="@drawable/ic_launcher_foreground" />
<monochrome android:drawable="@drawable/ic_notification" />
</adaptive-icon>
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="window_background">#FF1C1C1C</color>
<!-- The placeholder icon's green (packaging/linux/*.svg). -->
<color name="ic_launcher_background">#FF238636</color>
</resources>
@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">Voelin</string>
<string name="channel_voice">Voice connection</string>
<string name="channel_screen">Screen sharing</string>
<string name="voice_connected">Connected to voice</string>
<string name="disconnect">Disconnect</string>
<string name="mute">Mute</string>
<string name="unmute">Unmute</string>
<string name="screen_sharing">Sharing your screen</string>
<string name="stop_sharing">Stop sharing</string>
</resources>
@@ -0,0 +1,7 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!-- The Slint UI draws the whole window. -->
<style name="Theme.Voelin" parent="@android:style/Theme.DeviceDefault.NoActionBar">
<item name="android:windowBackground">@color/window_background</item>
</style>
</resources>
+4
View File
@@ -0,0 +1,4 @@
plugins {
id("com.android.application") version "8.13.2" apply false
id("org.jetbrains.kotlin.android") version "2.3.21" apply false
}
+7
View File
@@ -0,0 +1,7 @@
org.gradle.jvmargs=-Xmx2g -Dfile.encoding=UTF-8
android.useAndroidX=false
android.nonTransitiveRClass=true
kotlin.code.style=official
# ABIs the Rust library is built for (cargo-ndk names), e.g. only
# -Pvoelin.abis=arm64-v8a for a phone.
voelin.abis=arm64-v8a,x86_64
Binary file not shown.
+8
View File
@@ -0,0 +1,8 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionSha256Sum=bd71102213493060956ec229d946beee57158dbd89d0e62b91bca0fa2c5f3531
distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.3-bin.zip
networkTimeout=60000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
Vendored Executable
+251
View File
@@ -0,0 +1,251 @@
#!/bin/sh
#
# Copyright © 2015-2021 the original authors.
#
# 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
#
# https://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.
#
# SPDX-License-Identifier: Apache-2.0
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
CLASSPATH="\\\"\\\""
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
if ! command -v java >/dev/null 2>&1
then
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Collect all arguments for the java command:
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# and any embedded shellness will be escaped.
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# treated as '${Hostname}' itself on the command line.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
-jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"
+94
View File
@@ -0,0 +1,94 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@rem SPDX-License-Identifier: Apache-2.0
@rem
@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:execute
@rem Setup the command line
set CLASSPATH=
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %*
:end
@rem End local scope for the variables with windows NT shell
if %ERRORLEVEL% equ 0 goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
set EXIT_CODE=%ERRORLEVEL%
if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega
+24
View File
@@ -0,0 +1,24 @@
pluginManagement {
repositories {
google()
mavenCentral()
gradlePluginPortal()
}
}
dependencyResolutionManagement {
repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
repositories {
google()
mavenCentral()
// The Kotlin half of rustls-platform-verifier (the Rust code checks
// TLS certificates against the Android trust store through it).
maven {
url = uri("https://raw.githubusercontent.com/rustls/rustls-platform-verifier/maven-archive/android-release-support/maven/")
content { includeGroup("org.rustls") }
}
}
}
rootProject.name = "voelin"
include(":app")
-37
View File
@@ -1,37 +0,0 @@
[package]
name = "tsc-core"
version = "0.1.0"
description = "Client engine: server sessions merging voice, gateway and query sources; the API the UI drives."
edition.workspace = true
rust-version.workspace = true
license.workspace = true
repository.workspace = true
publish.workspace = true
[features]
default = ["audio-device"]
# Capture and play audio through the system's devices.
audio-device = ["tsc-audio/device"]
[dependencies]
anyhow = "1"
futures = "0.3"
serde_json = "1"
thiserror = "2"
tokio = { version = "1", features = ["macros", "rt-multi-thread", "sync", "time"] }
tokio-tungstenite = "0.30"
tracing = "0.1"
tsc-audio = { path = "../tsc-audio", default-features = false }
tsc-gateway-proto = { path = "../tsc-gateway-proto" }
tsc-model = { path = "../tsc-model" }
tsc-observer = { path = "../tsc-observer" }
tsc-query = { path = "../tsc-query" }
tsc-stream = { path = "../tsc-stream" }
tsclientlib = { path = "../proto/tsclientlib" }
tsproto-packets = { path = "../proto/tsproto-packets" }
[dev-dependencies]
tokio = { version = "1", features = ["macros", "rt-multi-thread", "test-util"] }
[lints]
workspace = true
-38
View File
@@ -1,38 +0,0 @@
[package]
name = "tsc-ui"
version = "0.1.0"
description = "Slint user interface and the desktop binary."
edition.workspace = true
rust-version.workspace = true
license.workspace = true
repository.workspace = true
publish.workspace = true
[lib]
name = "tsc_ui"
path = "src/lib.rs"
[[bin]]
name = "tsc-desktop"
path = "src/main.rs"
[dependencies]
anyhow = "1.0.104"
chrono = { version = "0.4.45", default-features = false, features = ["clock"] }
dirs = "6"
png = "0.18"
slint = { version = "1.18", features = ["renderer-software"] }
tokio = { version = "1.53.1", features = ["rt-multi-thread", "macros", "time", "sync"] }
tracing = "0.1.44"
tracing-subscriber = { version = "0.3.23", features = ["env-filter"] }
tsc-core = { path = "../tsc-core" }
tsc-model = { path = "../tsc-model" }
tsc-query = { path = "../tsc-query" }
tsc-store = { path = "../tsc-store", features = ["keyring"] }
tsclientlib = { path = "../proto/tsclientlib" }
[build-dependencies]
slint-build = "1.18"
[lints]
workspace = true
-780
View File
@@ -1,780 +0,0 @@
//! Application state on the UI thread, wired to the engine.
use std::cell::RefCell;
use std::collections::{HashMap, HashSet};
use std::rc::Rc;
use std::sync::Arc;
use anyhow::{Context, Result};
use slint::{ComponentHandle, ModelRc, SharedString, VecModel};
use tokio::runtime::Runtime;
use tracing::warn;
use tsc_core::{
Command, Engine, Event, ObserveState, SessionState, Source, VoiceOptions, VoiceState,
};
use tsc_model::{ChannelId, ChatMessage, ChatTarget, Presence, TreeRow, tree_rows};
use tsc_store::{Bookmark, MemorySecrets, QueryConfig, QueryTransport, Secrets, Store};
slint::include_modules!();
/// Secrets in the OS keyring, or in memory when there is none (headless
/// Linux without a Secret Service).
struct FallbackSecrets {
keyring: tsc_store::KeyringSecrets,
memory: MemorySecrets,
}
impl Secrets for FallbackSecrets {
fn get(&self, key: &str) -> tsc_store::Result<Option<String>> {
match self.memory.get(key)? {
Some(v) => Ok(Some(v)),
None => Ok(self.keyring.get(key).unwrap_or(None)),
}
}
fn set(&self, key: &str, value: &str) -> tsc_store::Result<()> {
if let Err(error) = self.keyring.set(key, value) {
warn!(%error, "keyring unavailable, keeping the secret for this session only");
return self.memory.set(key, value);
}
Ok(())
}
fn delete(&self, key: &str) -> tsc_store::Result<()> {
let _ = self.keyring.delete(key);
self.memory.delete(key)
}
}
struct Tab {
target: ChatTarget,
title: String,
lines: Vec<ChatLine>,
unread: i32,
}
/// What we know about one server session.
struct SessionView {
state: SessionState,
presence: Arc<Presence>,
collapsed: HashSet<ChannelId>,
talking: HashSet<u16>,
tabs: Vec<Tab>,
current_tab: usize,
/// The own channel's tab was focused for this voice connection.
focused_own_channel: bool,
}
impl Default for SessionView {
fn default() -> Self {
Self {
state: SessionState::default(),
presence: Arc::default(),
collapsed: HashSet::new(),
talking: HashSet::new(),
tabs: vec![Tab {
target: ChatTarget::Server,
title: "Server".into(),
lines: Vec::new(),
unread: 0,
}],
current_tab: 0,
focused_own_channel: false,
}
}
}
struct App {
ui: slint::Weak<MainWindow>,
store: Store,
secrets: Box<dyn Secrets>,
engine: Engine,
identity: tsclientlib::Identity,
bookmarks: Vec<Bookmark>,
current: Option<i64>,
sessions: HashMap<i64, SessionView>,
status: String,
}
thread_local! {
static APP: RefCell<Option<App>> = const { RefCell::new(None) };
}
fn with_app<R>(f: impl FnOnce(&mut App) -> R) -> Option<R> {
APP.with(|app| app.borrow_mut().as_mut().map(f))
}
/// Start options for [`run`].
#[derive(Clone, Debug, Default)]
pub struct RunOptions {
/// Where the client database lives. Default: `TSC_DATA_DIR`, else
/// `<data dir>/tsc`. Mobile platforms pass their app storage directory.
pub data_dir: Option<std::path::PathBuf>,
}
/// Run the app on the current thread until the window closes. The Slint
/// platform must be set up before (the default backend on desktop).
pub fn run(options: RunOptions) -> Result<()> {
let runtime = Runtime::new()?;
let engine = runtime.block_on(async { Engine::start() });
// Development switches: TSC_DATA_DIR isolates the database,
// TSC_AUTOCONNECT=voice|observe connects the first bookmark on start,
// TSC_SCREENSHOT=<png> saves the window after TSC_SCREENSHOT_DELAY seconds and exits.
let dir = match (options.data_dir, std::env::var_os("TSC_DATA_DIR")) {
(Some(dir), _) => dir,
(None, Some(dir)) => dir.into(),
(None, None) => dirs::data_dir().unwrap_or_else(|| ".".into()).join("tsc"),
};
let store =
Store::open(&dir.join("client.db")).context("failed to open the client database")?;
let identity = match store.identities()?.first() {
Some(entry) => store.identity(entry.id)?,
None => {
// Creating an identity takes a moment (security level 8).
let identity = tsclientlib::Identity::create();
store.add_identity("Default", &identity)?;
identity
}
};
let ui = MainWindow::new()?;
let bookmarks = store.bookmarks()?;
let app = App {
ui: ui.as_weak(),
store,
secrets: Box::new(FallbackSecrets {
keyring: tsc_store::KeyringSecrets::new("tsc-client"),
memory: MemorySecrets::default(),
}),
engine: engine.clone(),
identity,
current: bookmarks.first().map(|b| b.id),
bookmarks,
sessions: HashMap::new(),
status: "Ready".into(),
};
APP.with(|a| *a.borrow_mut() = Some(app));
wire_callbacks(&ui);
with_app(|app| app.refresh_all());
// Engine events -> UI thread.
let mut events = engine.subscribe();
runtime.spawn(async move {
loop {
match events.recv().await {
Ok(event) => {
let _ = slint::invoke_from_event_loop(move || {
with_app(|app| app.handle_event(event));
});
}
Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => continue,
Err(_) => break,
}
}
});
match std::env::var("TSC_AUTOCONNECT").as_deref() {
Ok("voice") => {
with_app(|app| app.connect_voice());
}
Ok("observe") => {
with_app(|app| app.toggle_observe());
}
_ => {}
}
let _screenshot_timer = std::env::var_os("TSC_SCREENSHOT").map(|path| {
let delay =
std::env::var("TSC_SCREENSHOT_DELAY").ok().and_then(|d| d.parse().ok()).unwrap_or(4);
let weak = ui.as_weak();
let timer = slint::Timer::default();
timer.start(
slint::TimerMode::SingleShot,
std::time::Duration::from_secs(delay),
move || {
if let Some(ui) = weak.upgrade() {
if let Err(e) = save_screenshot(&ui, std::path::Path::new(&path)) {
eprintln!("screenshot failed: {e}");
}
let _ = ui.hide();
}
},
);
timer
});
ui.run()?;
APP.with(|a| a.borrow_mut().take());
runtime.shutdown_timeout(std::time::Duration::from_secs(2));
Ok(())
}
fn wire_callbacks(ui: &MainWindow) {
let bridge = ui.global::<Bridge>();
bridge.on_select_server(|id| {
with_app(|app| {
app.current = Some(id as i64);
app.refresh_all();
});
});
bridge.on_connect_voice(|| {
with_app(|app| app.connect_voice());
});
bridge.on_disconnect_voice(|| {
with_app(|app| app.command(|session| Command::DisconnectVoice { session }));
});
bridge.on_toggle_observe(|| {
with_app(|app| app.toggle_observe());
});
bridge.on_join_channel(|cid| {
with_app(|app| {
app.command(|session| Command::MoveToChannel {
session,
channel: cid as ChannelId,
password: None,
})
});
});
bridge.on_open_channel_chat(|cid| {
with_app(|app| app.open_chat(ChatTarget::Channel(cid as ChannelId), true));
});
bridge.on_toggle_collapse(|cid| {
with_app(|app| {
if let Some(view) = app.view_mut() {
let cid = cid as ChannelId;
if !view.collapsed.remove(&cid) {
view.collapsed.insert(cid);
}
}
app.refresh_tree();
});
});
bridge.on_select_tab(|i| {
with_app(|app| {
if let Some(view) = app.view_mut() {
view.current_tab = i as usize;
if let Some(tab) = view.tabs.get_mut(i as usize) {
tab.unread = 0;
}
}
app.refresh_chat();
});
});
bridge.on_close_tab(|i| {
with_app(|app| app.close_tab(i as usize));
});
bridge.on_send_message(|text| {
with_app(|app| app.send_message(text.to_string()));
});
bridge.on_set_input_muted(|muted| {
with_app(|app| app.command(|session| Command::SetInputMuted { session, muted }));
});
bridge.on_set_output_muted(|muted| {
with_app(|app| app.command(|session| Command::SetOutputMuted { session, muted }));
});
bridge.on_push_to_talk(|on| {
with_app(|app| app.command(|session| Command::SetTransmitting { session, on }));
});
bridge.on_edit_bookmark(|id| with_app(|app| app.bookmark_form(id as i64)).unwrap_or_default());
bridge.on_save_bookmark(|form| {
with_app(|app| app.save_bookmark(form));
});
bridge.on_delete_bookmark(|id| {
with_app(|app| app.delete_bookmark(id as i64));
});
}
fn save_screenshot(ui: &MainWindow, path: &std::path::Path) -> Result<()> {
let image = ui.window().take_snapshot()?;
let file = std::io::BufWriter::new(std::fs::File::create(path)?);
let mut encoder = png::Encoder::new(file, image.width(), image.height());
encoder.set_color(png::ColorType::Rgba);
encoder.set_depth(png::BitDepth::Eight);
encoder.write_header()?.write_image_data(image.as_bytes())?;
Ok(())
}
fn time_of(ts_ms: i64) -> String {
chrono::DateTime::from_timestamp_millis(ts_ms)
.map(|t| t.with_timezone(&chrono::Local).format("%H:%M").to_string())
.unwrap_or_default()
}
fn model<T: Clone + 'static>(items: Vec<T>) -> ModelRc<T> {
ModelRc::from(Rc::new(VecModel::from(items)))
}
impl App {
fn view_mut(&mut self) -> Option<&mut SessionView> {
let id = self.current?;
Some(self.sessions.entry(id).or_default())
}
fn bookmark(&self, id: i64) -> Option<&Bookmark> {
self.bookmarks.iter().find(|b| b.id == id)
}
fn command(&self, f: impl FnOnce(u64) -> Command) {
if let Some(id) = self.current {
self.engine.send(f(id as u64));
}
}
fn set_status(&mut self, text: impl Into<String>) {
self.status = text.into();
if let Some(ui) = self.ui.upgrade() {
ui.global::<Bridge>().set_status_text(self.status.clone().into());
}
}
fn connect_voice(&mut self) {
let Some(b) = self.current.and_then(|id| self.bookmark(id)).cloned() else { return };
let mut options = VoiceOptions::new(&b.address, &b.nickname);
options.identity = Some(self.identity.clone());
options.server_password = self.secrets.get(&b.server_password_key()).ok().flatten();
options.channel = b.default_channel.clone();
options.audio = true;
self.engine
.send(Command::ConnectVoice { session: b.id as u64, options: Box::new(options) });
self.set_status(format!("Connecting to {}…", b.address));
}
fn toggle_observe(&mut self) {
let Some(b) = self.current.and_then(|id| self.bookmark(id)).cloned() else { return };
let session = b.id as u64;
let observing =
self.sessions.get(&b.id).is_some_and(|v| v.state.observe != ObserveState::Off);
if observing {
self.engine.send(Command::StopObserving { session });
return;
}
if let Some(url) = &b.gateway_url {
self.engine.send(Command::ObserveGateway {
session,
url: url.clone(),
identity: Box::new(self.identity.clone()),
});
} else if let Some(q) = &b.query {
let secret = self.secrets.get(&b.query_password_key()).ok().flatten();
let transport = match q.transport {
QueryTransport::Raw => tsc_query::Transport::Raw,
QueryTransport::Ssh => tsc_query::Transport::Ssh,
QueryTransport::Http => tsc_query::Transport::Http,
};
let connect = tsc_query::Connect {
transport,
addr: format!("{}:{}", q.host, q.port),
user: q.user.clone(),
secret,
server_port: q.server_port,
server_id: None,
line: Default::default(),
};
self.engine.send(Command::ObserveQuery { session, connect: Box::new(connect) });
}
self.set_status("Observing invisibly…");
}
fn open_chat(&mut self, target: ChatTarget, focus: bool) {
let Some(id) = self.current else { return };
let title = match &target {
ChatTarget::Channel(cid) => {
let name = self
.sessions
.get(&id)
.and_then(|v| v.presence.channels.get(cid).map(|c| c.name.clone()));
format!("#{}", name.unwrap_or_else(|| cid.to_string()))
}
ChatTarget::Server => "Server".into(),
ChatTarget::Private(uid) => format!("@{uid}"),
};
let view = self.sessions.entry(id).or_default();
let index = match view.tabs.iter().position(|t| t.target == target) {
Some(i) => i,
None => {
view.tabs.push(Tab { target: target.clone(), title, lines: Vec::new(), unread: 0 });
self.engine.send(Command::OpenChat { session: id as u64, target });
view.tabs.len() - 1
}
};
if focus {
view.current_tab = index;
view.tabs[index].unread = 0;
}
self.refresh_chat();
}
fn close_tab(&mut self, index: usize) {
let Some(id) = self.current else { return };
let view = self.sessions.entry(id).or_default();
if index == 0 || index >= view.tabs.len() {
return;
}
let tab = view.tabs.remove(index);
view.current_tab = view.current_tab.min(view.tabs.len() - 1);
self.engine.send(Command::CloseChat { session: id as u64, target: tab.target });
self.refresh_chat();
}
fn send_message(&mut self, text: String) {
let Some(id) = self.current else { return };
let Some(view) = self.sessions.get(&id) else { return };
let target = view.tabs[view.current_tab].target.clone();
self.engine.send(Command::SendChat { session: id as u64, target, text });
}
fn bookmark_form(&self, id: i64) -> BookmarkForm {
let Some(b) = self.bookmark(id) else {
return BookmarkForm {
id: -1,
nickname: std::env::var("USER").unwrap_or_default().into(),
query_transport: "none".into(),
query_user: "serveradmin".into(),
..Default::default()
};
};
let secret = |key: String| -> SharedString {
self.secrets.get(&key).ok().flatten().unwrap_or_default().into()
};
let (transport, addr, user) = match &b.query {
Some(q) => (
match q.transport {
QueryTransport::Raw => "raw",
QueryTransport::Ssh => "ssh",
QueryTransport::Http => "http",
},
format!("{}:{}", q.host, q.port),
q.user.clone(),
),
None => ("none", String::new(), "serveradmin".to_string()),
};
BookmarkForm {
id: b.id as i32,
name: b.name.clone().into(),
address: b.address.clone().into(),
nickname: b.nickname.clone().into(),
server_password: secret(b.server_password_key()),
gateway_url: b.gateway_url.clone().unwrap_or_default().into(),
query_transport: transport.into(),
query_addr: addr.into(),
query_user: user.into(),
query_password: secret(b.query_password_key()),
}
}
fn save_bookmark(&mut self, form: BookmarkForm) {
let query = match form.query_transport.as_str() {
"none" | "" => None,
t => {
let (host, port) = form
.query_addr
.rsplit_once(':')
.map_or((form.query_addr.to_string(), None), |(h, p)| {
(h.to_string(), p.parse().ok())
});
let transport = match t {
"raw" => QueryTransport::Raw,
"http" => QueryTransport::Http,
_ => QueryTransport::Ssh,
};
let default_port = match transport {
QueryTransport::Raw => 10011,
QueryTransport::Ssh => 10022,
QueryTransport::Http => 10080,
};
Some(QueryConfig {
transport,
host,
port: port.unwrap_or(default_port),
user: form.query_user.to_string(),
server_port: None,
})
}
};
let mut bookmark = Bookmark {
id: form.id as i64,
name: if form.name.is_empty() {
form.address.to_string()
} else {
form.name.to_string()
},
address: form.address.to_string(),
nickname: form.nickname.to_string(),
identity: None,
default_channel: None,
gateway_url: Some(form.gateway_url.to_string()).filter(|u| !u.is_empty()),
query,
client_version: None,
};
let result = if bookmark.id < 0 {
self.store.add_bookmark(&bookmark).map(|id| bookmark.id = id)
} else {
self.store.update_bookmark(&bookmark)
};
if let Err(e) = result {
self.set_status(format!("Could not save: {e}"));
return;
}
for (key, value) in [
(bookmark.server_password_key(), &form.server_password),
(bookmark.query_password_key(), &form.query_password),
] {
let result = if value.is_empty() {
self.secrets.delete(&key)
} else {
self.secrets.set(&key, value)
};
if let Err(e) = result {
warn!(%e, "could not store secret");
}
}
self.current = Some(bookmark.id);
self.bookmarks = self.store.bookmarks().unwrap_or_default();
self.refresh_all();
}
fn delete_bookmark(&mut self, id: i64) {
self.engine.send(Command::CloseSession { session: id as u64 });
if let Some(b) = self.bookmark(id).cloned() {
let _ = self.secrets.delete(&b.server_password_key());
let _ = self.secrets.delete(&b.query_password_key());
}
let _ = self.store.delete_bookmark(id);
self.sessions.remove(&id);
self.bookmarks = self.store.bookmarks().unwrap_or_default();
self.current = self.bookmarks.first().map(|b| b.id);
self.refresh_all();
}
fn handle_event(&mut self, event: Event) {
match event {
Event::State { session, state } => {
let id = session as i64;
let view = self.sessions.entry(id).or_default();
let was_voice = view.state.voice;
view.state = state.clone();
if state.voice != VoiceState::Connected {
view.focused_own_channel = false;
}
let focus = !view.focused_own_channel;
if state.voice == VoiceState::Connected && was_voice != VoiceState::Connected {
self.set_status("Connected");
}
if self.current == Some(id) {
// The voice channel's chat is always at hand, and focused
// once per connection.
if let (Some(cid), VoiceState::Connected) = (state.own_channel, state.voice) {
self.open_chat(ChatTarget::Channel(cid), focus);
self.sessions.entry(id).or_default().focused_own_channel = true;
}
}
self.refresh_servers();
self.refresh_toolbar();
}
Event::ServerInfo { session, name, flavor, .. } => {
if self.current == Some(session as i64) {
let kind = match flavor {
tsc_model::ServerFlavor::Ts3(v) => format!("TeamSpeak 3 {v}"),
tsc_model::ServerFlavor::Ts6(v) => format!("TeamSpeak 6 {v}"),
tsc_model::ServerFlavor::Unknown(v) => v,
};
self.set_status(format!("Connected to {name} ({kind})"));
}
}
Event::Presence { session, presence } => {
self.sessions.entry(session as i64).or_default().presence = presence;
if self.current == Some(session as i64) {
self.refresh_tree();
self.refresh_chat();
}
}
Event::Talking { session, client, talking } => {
let view = self.sessions.entry(session as i64).or_default();
if talking {
view.talking.insert(client);
} else {
view.talking.remove(&client);
}
if self.current == Some(session as i64) {
self.refresh_tree();
}
}
Event::Chat { session, message } => self.add_message(session as i64, message),
Event::Error { message, .. } => self.set_status(message),
// Stream events: the streams panel is not wired yet.
_ => {}
}
}
fn add_message(&mut self, id: i64, message: ChatMessage) {
let current = self.current == Some(id);
let view = self.sessions.entry(id).or_default();
let index = match view.tabs.iter().position(|t| t.target == message.target) {
Some(i) => i,
None => {
let title = match &message.target {
ChatTarget::Channel(cid) => format!(
"#{}",
view.presence
.channels
.get(cid)
.map(|c| c.name.clone())
.unwrap_or_else(|| cid.to_string())
),
ChatTarget::Private(_) => format!("@{}", message.author_name),
ChatTarget::Server => "Server".into(),
};
view.tabs.push(Tab {
target: message.target.clone(),
title,
lines: Vec::new(),
unread: 0,
});
view.tabs.len() - 1
}
};
let tab = &mut view.tabs[index];
tab.lines.push(ChatLine {
author: message.author_name.into(),
text: message.text.into(),
time: time_of(message.ts_ms).into(),
relayed: message.via_relay,
});
if !(current && view.current_tab == index) {
tab.unread += 1;
}
if current {
self.refresh_chat();
}
}
fn refresh_all(&mut self) {
self.refresh_servers();
self.refresh_toolbar();
self.refresh_tree();
self.refresh_chat();
}
fn refresh_servers(&self) {
let Some(ui) = self.ui.upgrade() else { return };
let bridge = ui.global::<Bridge>();
let items = self
.bookmarks
.iter()
.map(|b| {
let state = self.sessions.get(&b.id).map(|v| v.state.clone()).unwrap_or_default();
let status = match (state.voice, state.observe) {
(VoiceState::Connected, _) => "connected",
(VoiceState::Connecting, _) | (_, ObserveState::Connecting) => "connecting",
(_, ObserveState::Observing) => "observing",
_ => "offline",
};
ServerItem {
id: b.id as i32,
name: b.name.clone().into(),
address: b.address.clone().into(),
status: status.into(),
}
})
.collect();
bridge.set_servers(model(items));
bridge.set_current_server(self.current.map_or(-1, |id| id as i32));
}
fn refresh_toolbar(&self) {
let Some(ui) = self.ui.upgrade() else { return };
let bridge = ui.global::<Bridge>();
let bookmark = self.current.and_then(|id| self.bookmark(id));
let state = self
.current
.and_then(|id| self.sessions.get(&id))
.map(|v| v.state.clone())
.unwrap_or_default();
bridge.set_server_title(
bookmark.map_or("No server selected".into(), |b| b.name.clone()).into(),
);
bridge.set_voice_connected(state.voice == VoiceState::Connected);
bridge.set_voice_connecting(state.voice == VoiceState::Connecting);
bridge.set_observing(state.observe != ObserveState::Off);
bridge.set_can_observe(
bookmark.is_some_and(|b| b.gateway_url.is_some() || b.query.is_some()),
);
bridge.set_input_muted(state.input_muted);
bridge.set_output_muted(state.output_muted);
bridge.set_transmitting(state.transmitting);
bridge.set_presence_source(
match state.presence_source {
Some(Source::Voice) => "live (voice)",
Some(Source::Gateway) => "invisible (gateway)",
Some(Source::Query) => "invisible (query)",
None => "",
}
.into(),
);
bridge.set_status_text(self.status.clone().into());
}
fn refresh_tree(&self) {
let Some(ui) = self.ui.upgrade() else { return };
let Some(view) = self.current.and_then(|id| self.sessions.get(&id)) else {
ui.global::<Bridge>().set_tree(model(Vec::new()));
return;
};
let own_channel = view.state.own_channel;
let rows = tree_rows(&view.presence, &|cid| view.collapsed.contains(&cid))
.into_iter()
.map(|row| match row {
TreeRow::Channel { depth, channel } => TreeItem {
is_channel: true,
depth: depth as i32,
id: channel.id as i32,
name: channel.name.clone().into(),
own: own_channel == Some(channel.id),
locked: channel.has_password,
collapsed: view.collapsed.contains(&channel.id),
..Default::default()
},
TreeRow::Client { depth, client } => TreeItem {
is_channel: false,
depth: depth as i32,
id: client.id as i32,
name: client.nickname.clone().into(),
own: false,
talking: view.talking.contains(&client.id) || client.talking == Some(true),
muted: client.input_muted,
sound_off: client.output_muted,
away: client.away.is_some(),
streaming: client.streaming == Some(true),
..Default::default()
},
})
.collect();
ui.global::<Bridge>().set_tree(model(rows));
}
fn refresh_chat(&self) {
let Some(ui) = self.ui.upgrade() else { return };
let bridge = ui.global::<Bridge>();
let Some(view) = self.current.and_then(|id| self.sessions.get(&id)) else {
bridge.set_tabs(model(vec![ChatTab { title: "Server".into(), ..Default::default() }]));
bridge.set_messages(model(Vec::new()));
return;
};
let tabs = view
.tabs
.iter()
.map(|t| ChatTab {
title: t.title.clone().into(),
kind: matches!(t.target, ChatTarget::Channel(_)) as i32,
id: match t.target {
ChatTarget::Channel(cid) => cid as i32,
_ => 0,
},
unread: t.unread,
})
.collect();
bridge.set_tabs(model(tabs));
bridge.set_current_tab(view.current_tab as i32);
bridge.set_messages(model(view.tabs[view.current_tab].lines.clone()));
}
}
-5
View File
@@ -1,5 +0,0 @@
//! Slint user interface shared by the desktop binary and the mobile apps.
mod app;
pub use app::{RunOptions, run};
-537
View File
@@ -1,537 +0,0 @@
import { Button, LineEdit, ListView, ComboBox, AboutSlint, VerticalBox, HorizontalBox, ScrollView } from "std-widgets.slint";
export struct ServerItem {
id: int,
name: string,
address: string,
// "offline", "connecting", "observing" or "connected"
status: string,
}
export struct TreeItem {
is-channel: bool,
depth: int,
id: int,
name: string,
own: bool,
talking: bool,
muted: bool,
sound-off: bool,
away: bool,
streaming: bool,
locked: bool,
collapsed: bool,
}
export struct ChatTab {
title: string,
// 0 = server chat, 1 = channel chat
kind: int,
id: int,
unread: int,
}
export struct ChatLine {
author: string,
text: string,
time: string,
relayed: bool,
}
export struct BookmarkForm {
id: int,
name: string,
address: string,
nickname: string,
server-password: string,
gateway-url: string,
query-transport: string,
query-addr: string,
query-user: string,
query-password: string,
}
export global Bridge {
in property <[ServerItem]> servers;
in-out property <int> current-server: -1;
in property <[TreeItem]> tree;
in property <[ChatTab]> tabs;
in-out property <int> current-tab: 0;
in property <[ChatLine]> messages;
in property <string> status-text;
in property <string> server-title: "No server selected";
in property <bool> voice-connected;
in property <bool> voice-connecting;
in property <bool> observing;
in property <bool> can-observe;
in property <bool> input-muted;
in property <bool> output-muted;
in property <bool> transmitting;
in property <string> presence-source;
callback select-server(int);
callback connect-voice();
callback disconnect-voice();
callback toggle-observe();
callback join-channel(int);
callback open-channel-chat(int);
callback toggle-collapse(int);
callback select-tab(int);
callback close-tab(int);
callback send-message(string);
callback set-input-muted(bool);
callback set-output-muted(bool);
callback push-to-talk(bool);
callback edit-bookmark(int) -> BookmarkForm;
callback save-bookmark(BookmarkForm);
callback delete-bookmark(int);
}
component StatusDot inherits Rectangle {
in property <string> status;
width: 10px;
height: 10px;
border-radius: 5px;
background: status == "connected" ? #3fb950 : status == "observing" ? #58a6ff : status == "connecting" ? #d29922 : #6e7681;
}
component Field inherits HorizontalLayout {
in property <string> label;
in-out property <string> value;
in property <string> placeholder;
in property <InputType> input-type: InputType.text;
spacing: 8px;
Text {
text: label;
width: 130px;
vertical-alignment: center;
}
LineEdit {
text <=> value;
placeholder-text: placeholder;
input-type: input-type;
}
}
component BookmarkEditor inherits Rectangle {
in-out property <BookmarkForm> form;
callback done();
background: #000000a0;
TouchArea { }
Rectangle {
width: min(parent.width - 32px, 520px);
height: min(parent.height - 32px, 520px);
background: #1f2328;
border-radius: 8px;
VerticalBox {
Text {
text: form.id < 0 ? "Add server" : "Edit server";
font-size: 18px;
font-weight: 700;
}
ScrollView {
VerticalLayout {
spacing: 6px;
Field { label: "Name"; value <=> form.name; placeholder: "My server"; }
Field { label: "Address"; value <=> form.address; placeholder: "ts.example.org:9987"; }
Field { label: "Nickname"; value <=> form.nickname; }
Field { label: "Server password"; value <=> form.server-password; input-type: InputType.password; }
Text {
text: "Invisible presence and chat without joining (optional)";
font-weight: 600;
}
Field { label: "Gateway URL"; value <=> form.gateway-url; placeholder: "wss://gw.example.org/v1"; }
HorizontalLayout {
spacing: 8px;
Text {
text: "Query transport";
width: 130px;
vertical-alignment: center;
}
ComboBox {
model: ["none", "ssh", "raw", "http"];
current-value <=> form.query-transport;
}
}
Field { label: "Query address"; value <=> form.query-addr; placeholder: "ts.example.org:10022"; }
Field { label: "Query login"; value <=> form.query-user; }
Field { label: "Query password"; value <=> form.query-password; input-type: InputType.password; }
}
}
HorizontalLayout {
alignment: end;
spacing: 8px;
if form.id >= 0: Button {
text: "Delete";
clicked => {
Bridge.delete-bookmark(form.id);
done();
}
}
Button {
text: "Cancel";
clicked => { done(); }
}
Button {
text: "Save";
primary: true;
enabled: form.address != "" && form.nickname != "";
clicked => {
Bridge.save-bookmark(form);
done();
}
}
}
}
}
}
component ServerList inherits Rectangle {
callback add();
callback edit(int);
background: #161b22;
VerticalBox {
HorizontalLayout {
Text {
text: "Servers";
font-weight: 700;
vertical-alignment: center;
}
Button {
text: "+";
width: 32px;
clicked => { add(); }
}
}
ListView {
for server[i] in Bridge.servers: Rectangle {
height: 48px;
border-radius: 6px;
background: Bridge.current-server == server.id ? #30363d : area.has-hover ? #21262d : transparent;
area := TouchArea {
clicked => { Bridge.select-server(server.id); }
double-clicked => { edit(server.id); }
}
HorizontalLayout {
padding: 6px;
spacing: 8px;
StatusDot {
status: server.status;
y: (parent.height - self.height) / 2;
}
VerticalLayout {
Text {
text: server.name;
font-weight: 600;
overflow: elide;
}
Text {
text: server.address;
font-size: 11px;
color: #8b949e;
overflow: elide;
}
}
}
}
}
}
}
component ChannelTree inherits Rectangle {
background: #0d1117;
ListView {
for row in Bridge.tree: Rectangle {
height: 26px;
background: row-area.has-hover ? #161b22 : transparent;
row-area := TouchArea {
double-clicked => {
if (row.is-channel) {
Bridge.join-channel(row.id);
}
}
clicked => {
if (row.is-channel) {
Bridge.open-channel-chat(row.id);
}
}
}
HorizontalLayout {
padding-left: 8px + row.depth * 18px;
padding-right: 8px;
spacing: 6px;
if row.is-channel: Text {
text: row.collapsed ? "▸" : "▾";
vertical-alignment: center;
TouchArea {
clicked => { Bridge.toggle-collapse(row.id); }
}
}
if !row.is-channel: Rectangle {
width: 10px;
height: 10px;
y: (parent.height - self.height) / 2;
border-radius: 5px;
background: row.talking ? #3fb950 : #30363d;
}
Text {
text: (row.is-channel ? "# " : "") + row.name;
horizontal-stretch: 1;
horizontal-alignment: left;
vertical-alignment: center;
font-weight: row.is-channel || row.own ? 600 : 400;
color: row.away ? #8b949e : row.own ? #58a6ff : #e6edf3;
overflow: elide;
}
if row.locked: Text { text: "password"; font-size: 10px; color: #d29922; vertical-alignment: center; }
if row.muted: Text { text: "mic off"; font-size: 10px; color: #f85149; vertical-alignment: center; }
if row.sound-off: Text { text: "sound off"; font-size: 10px; color: #f85149; vertical-alignment: center; }
if row.streaming: Text { text: "LIVE"; font-size: 10px; color: #a371f7; vertical-alignment: center; }
if row.away: Text { text: "away"; font-size: 10px; color: #8b949e; vertical-alignment: center; }
}
}
}
}
component ChatPanel inherits Rectangle {
background: #0d1117;
VerticalLayout {
HorizontalLayout {
height: 34px;
spacing: 2px;
for tab[i] in Bridge.tabs: Rectangle {
width: tab-text.preferred-width + 28px;
background: Bridge.current-tab == i ? #30363d : tab-area.has-hover ? #21262d : #161b22;
tab-area := TouchArea {
clicked => { Bridge.select-tab(i); }
}
HorizontalLayout {
padding-left: 10px;
padding-right: 6px;
spacing: 4px;
tab-text := Text {
text: tab.title + (tab.unread > 0 ? " (" + tab.unread + ")" : "");
vertical-alignment: center;
font-weight: tab.unread > 0 ? 700 : 400;
}
if tab.kind == 1: Text {
text: "×";
vertical-alignment: center;
TouchArea {
clicked => { Bridge.close-tab(i); }
}
}
}
}
Rectangle { }
}
ListView {
for line in Bridge.messages: VerticalLayout {
padding: 6px;
HorizontalLayout {
spacing: 8px;
Text {
text: line.author;
font-weight: 700;
color: line.relayed ? #58a6ff : #e6edf3;
}
Text {
text: line.time + (line.relayed ? " via relay" : "");
font-size: 11px;
color: #8b949e;
vertical-alignment: center;
}
}
Text {
text: line.text;
wrap: word-wrap;
}
}
}
HorizontalLayout {
padding: 6px;
spacing: 6px;
input := LineEdit {
placeholder-text: "Message";
accepted(text) => {
if (text != "") {
Bridge.send-message(text);
self.text = "";
}
}
}
Button {
text: "Send";
clicked => {
if (input.text != "") {
Bridge.send-message(input.text);
input.text = "";
}
}
}
}
}
}
export component MainWindow inherits Window {
title: "TS Client";
preferred-width: 1200px;
preferred-height: 760px;
min-width: 360px;
min-height: 480px;
background: #0d1117;
default-font-size: 13px;
property <bool> editing: false;
property <bool> show-about: false;
property <BookmarkForm> form;
// Phones and narrow windows show one pane at a time. Set from a change
// handler: a binding on `width` would loop through the layout.
property <bool> narrow: false;
changed width => { narrow = self.width < 800px; }
init => { narrow = self.width < 800px; }
property <int> pane: 1;
VerticalLayout {
// Toolbar
Rectangle {
height: 48px;
background: #161b22;
HorizontalLayout {
padding: 6px;
spacing: 6px;
if narrow: Button {
text: pane == 0 ? "Tree" : pane == 1 ? "Chat" : "Servers";
clicked => { pane = mod(pane + 1, 3); }
}
Text {
text: Bridge.server-title;
font-size: 15px;
font-weight: 700;
vertical-alignment: center;
overflow: elide;
}
Rectangle { }
Button {
text: Bridge.voice-connected ? "Disconnect" : Bridge.voice-connecting ? "Connecting…" : "Connect";
enabled: Bridge.current-server >= 0 && !Bridge.voice-connecting;
primary: !Bridge.voice-connected;
clicked => {
if (Bridge.voice-connected) {
Bridge.disconnect-voice();
} else {
Bridge.connect-voice();
}
}
}
Button {
text: Bridge.observing ? "Stop observing" : "Observe (invisible)";
enabled: Bridge.can-observe;
clicked => { Bridge.toggle-observe(); }
}
Button {
text: Bridge.input-muted ? "Mic: off" : "Mic: on";
enabled: Bridge.voice-connected;
clicked => { Bridge.set-input-muted(!Bridge.input-muted); }
}
Button {
text: Bridge.output-muted ? "Sound: off" : "Sound: on";
enabled: Bridge.voice-connected;
clicked => { Bridge.set-output-muted(!Bridge.output-muted); }
}
ptt := Rectangle {
width: 110px;
border-radius: 4px;
background: Bridge.transmitting ? #238636 : ptt-area.has-hover ? #30363d : #21262d;
opacity: Bridge.voice-connected ? 1.0 : 0.4;
Text {
text: Bridge.transmitting ? "Talking…" : "Hold to talk";
}
ptt-area := TouchArea {
enabled: Bridge.voice-connected;
pointer-event(e) => {
if (e.kind == PointerEventKind.down) {
Bridge.push-to-talk(true);
} else if (e.kind == PointerEventKind.up || e.kind == PointerEventKind.cancel) {
Bridge.push-to-talk(false);
}
}
}
}
Button {
text: "About";
clicked => { show-about = true; }
}
}
}
HorizontalLayout {
if !narrow || pane == 2: ServerList {
// Fixed width beside the other panes, all the space alone.
min-width: narrow ? 0px : 230px;
max-width: narrow ? 100000px : 230px;
horizontal-stretch: narrow ? 1 : 0;
add => {
form = Bridge.edit-bookmark(-1);
editing = true;
}
edit(id) => {
form = Bridge.edit-bookmark(id);
editing = true;
}
}
if !narrow || pane == 0: ChannelTree {
min-width: narrow ? 0px : 360px;
max-width: narrow ? 100000px : 360px;
horizontal-stretch: narrow ? 1 : 0;
}
if !narrow || pane == 1: ChatPanel { }
}
// Status bar
Rectangle {
height: 26px;
background: #161b22;
HorizontalLayout {
padding-left: 8px;
padding-right: 8px;
Text {
text: Bridge.status-text;
color: #8b949e;
vertical-alignment: center;
overflow: elide;
}
Rectangle { }
Text {
text: Bridge.presence-source;
color: #58a6ff;
vertical-alignment: center;
}
}
}
}
if editing: BookmarkEditor {
form <=> form;
done => { editing = false; }
}
if show-about: Rectangle {
background: #000000c0;
TouchArea {
clicked => { show-about = false; }
}
VerticalBox {
alignment: center;
Text {
text: "Unofficial TeamSpeak 3/6 compatible client. Not affiliated with TeamSpeak Systems GmbH.";
horizontal-alignment: center;
wrap: word-wrap;
}
AboutSlint { }
Text {
text: "Third-party licenses: see THIRD_PARTY_NOTICES. Click to close.";
horizontal-alignment: center;
color: #8b949e;
}
}
}
}
+37
View File
@@ -0,0 +1,37 @@
[package]
name = "voelin-android"
version = "0.1.0"
description = "Android app library: native activity entry point, engine kept for the whole process, JNI bridge to the Kotlin services (voice, screen share), Android Keystore secrets."
edition.workspace = true
rust-version.workspace = true
license.workspace = true
repository.workspace = true
publish.workspace = true
[lib]
name = "voelin_android"
# cdylib: libvoelin_android.so, loaded by the app's NativeActivity. rlib: tests
# and type checks on the host.
crate-type = ["cdylib", "rlib"]
[dependencies]
tokio = { version = "1.53.1", features = ["rt-multi-thread", "macros", "sync", "time"] }
tracing = "0.1.44"
voelin-core = { path = "../voelin-core" }
[target.'cfg(target_os = "android")'.dependencies]
anyhow = "1.0.104"
jni = "0.22.4"
rustls-platform-verifier = "0.7.1"
slint = { version = "1.18", default-features = false, features = ["std", "compat-1-2", "backend-android-activity-06"] }
tracing-subscriber = { version = "0.3.23", features = ["env-filter"] }
voelin-media = { path = "../voelin-media", default-features = false }
voelin-platform = { path = "../voelin-platform", default-features = false }
voelin-store = { path = "../voelin-store" }
voelin-ui = { path = "../voelin-ui" }
[dev-dependencies]
voelin-model = { path = "../voelin-model" }
[lints]
workspace = true
+150
View File
@@ -0,0 +1,150 @@
//! `android_main`: the activity's native thread.
//!
//! android-activity calls it on a new thread for every activity instance
//! (the process can outlive activities while voice runs in the service).
//! Process-wide setup happens once; the window is built per activity.
use std::path::Path;
use std::sync::{Mutex, Once, OnceLock, PoisonError};
use anyhow::Context as _;
use slint::android::AndroidApp;
use tracing::{error, info, warn};
use voelin_core::Command;
use crate::foreground::Foreground;
use crate::host::EngineHost;
use crate::{bridge, capture, egl, secrets};
/// Store setting (`bool`): the user's opt-in to local crash reports.
pub const CRASH_REPORTS_SETTING: &str = "crash_reports";
static HOST: OnceLock<EngineHost> = OnceLock::new();
static FOREGROUND: Mutex<Option<Foreground>> = Mutex::new(None);
fn host() -> anyhow::Result<&'static EngineHost> {
if let Some(host) = HOST.get() {
return Ok(host);
}
let host = EngineHost::start().context("starting the engine runtime")?;
Ok(HOST.get_or_init(|| host))
}
fn with_foreground<R>(f: impl FnOnce(&mut Foreground) -> R) -> R {
let mut guard = FOREGROUND.lock().unwrap_or_else(PoisonError::into_inner);
f(guard.get_or_insert_with(Foreground::default))
}
/// The entry point android-activity looks up in this library.
#[allow(unsafe_code)] // an exported symbol
#[unsafe(no_mangle)]
fn android_main(app: AndroidApp) {
init_logging();
info!("android_main");
if let Err(e) = run(app) {
error!("{e:#}");
}
info!("android_main done");
}
fn init_logging() {
// android-activity forwards stderr to logcat (tag RustStdoutStderr).
let filter = tracing_subscriber::EnvFilter::try_from_default_env()
.unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("info"));
let _ = tracing_subscriber::fmt()
.with_env_filter(filter)
.with_ansi(false)
.without_time()
.with_writer(std::io::stderr)
.try_init();
}
fn run(app: AndroidApp) -> anyhow::Result<()> {
let data_dir = app.internal_data_path().context("the app has no internal storage path")?;
install_crash_reports(&data_dir);
jni::JavaVM::singleton()?.attach_current_thread(|env| -> jni::errors::Result<()> {
bridge::init(env)?;
// reqwest (HTTPS queries, tsclientlib) verifies certificates with
// the system's trust store through rustls-platform-verifier.
let context = bridge::context(env)?;
rustls_platform_verifier::android::init_with_env(env, context)?;
Ok(())
})?;
let host = host()?;
static PROCESS: Once = Once::new();
PROCESS.call_once(|| {
// Before Slint creates the first window surface.
egl::reserve_skia_extension_slots();
capture::register();
watch_voice(host);
});
if let Err(e) = bridge::request_permissions() {
warn!("requesting permissions: {e}");
}
slint::android::init(app).context("Slint Android backend")?;
let attached = host.attach();
voelin_ui::run(voelin_ui::RunOptions {
data_dir: Some(data_dir),
secrets: Some(Box::new(secrets::KeystoreSecrets)),
engine: Some(voelin_ui::HostedEngine {
engine: attached.engine,
runtime: attached.runtime,
events: attached.events,
}),
})
}
/// Local crash reports in `<files dir>/crash-reports`, recorded only if the
/// user opted in (off by default).
fn install_crash_reports(data_dir: &Path) {
voelin_platform::crash::set_app_version(env!("CARGO_PKG_VERSION"));
let enabled = voelin_store::Store::open(&data_dir.join("client.db"))
.ok()
.and_then(|store| store.setting::<bool>(CRASH_REPORTS_SETTING).ok().flatten())
.unwrap_or(false);
voelin_platform::crash::install(data_dir.join(voelin_platform::crash::DIR_NAME), enabled);
}
/// Keep the voice foreground service in step with the voice connections.
fn watch_voice(host: &'static EngineHost) {
let mut events = host.engine().subscribe();
host.runtime().spawn(async move {
loop {
match events.recv().await {
Ok(event) => {
if let Some(notice) = with_foreground(|f| f.update(&event))
&& let Err(e) = bridge::set_voice_notification(notice.as_ref())
{
warn!("voice service: {e}");
}
}
Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => continue,
Err(tokio::sync::broadcast::error::RecvError::Closed) => break,
}
}
});
}
/// "Disconnect" in the voice notification.
pub fn disconnect_voice() {
let Some(host) = HOST.get() else {
return;
};
for session in with_foreground(|f| f.voice_sessions()) {
host.engine().send(Command::DisconnectVoice { session });
}
}
/// "Mute" / "Unmute" in the voice notification: mute every voice session,
/// or unmute them all when all are muted.
pub fn toggle_mute() {
let Some(host) = HOST.get() else {
return;
};
let (sessions, muted) =
with_foreground(|f| (f.voice_sessions(), f.notice().is_some_and(|n| n.muted)));
for session in sessions {
host.engine().send(Command::SetInputMuted { session, muted: !muted });
}
}
+273
View File
@@ -0,0 +1,273 @@
//! JNI glue with the app's Kotlin side (`android/app/src/main/java/...`).
//!
//! - Rust → Kotlin: static methods of `io.github.faumaray.voelin.Bridge`, called
//! from any thread (the class is looked up once on the `android_main`
//! thread, whose class loader sees the app's classes).
//! - Kotlin → Rust: the `external` methods of `io.github.faumaray.voelin.Native`,
//! exported below with `native_method!` (panics and errors become Java
//! exceptions instead of crossing the FFI boundary).
use std::sync::OnceLock;
use jni::errors::{Error, Result};
use jni::objects::{JByteBuffer, JClass, JFloatArray, JObject, JString, JValue};
use jni::refs::{Global, Reference as _};
use jni::sys::{jboolean, jint, jlong};
use jni::{Env, JavaVM, jni_sig, jni_str, native_method};
use crate::foreground::VoiceNotice;
static BRIDGE: OnceLock<Global<JClass<'static>>> = OnceLock::new();
/// Look up `Bridge` (on the `android_main` thread).
pub fn init(env: &mut Env) -> Result<()> {
if BRIDGE.get().is_none() {
let class = env.load_class(jni_str!("io.github.faumaray.voelin.Bridge"))?;
let _ = BRIDGE.set(env.new_global_ref(class)?);
}
Ok(())
}
/// Run `f` with an attached thread and the `Bridge` class.
fn with_bridge<T>(f: impl FnOnce(&mut Env, &Global<JClass<'static>>) -> Result<T>) -> Result<T> {
let class = BRIDGE
.get()
.ok_or_else(|| Error::ClassNotFound { name: "io.github.faumaray.voelin.Bridge".into() })?;
JavaVM::singleton()?.attach_current_thread(|env| f(env, class))
}
/// The application `Context`, as a local reference of `env`'s frame.
pub fn context<'local>(env: &mut Env<'local>) -> Result<JObject<'local>> {
let class = BRIDGE
.get()
.ok_or_else(|| Error::ClassNotFound { name: "io.github.faumaray.voelin.Bridge".into() })?;
env.call_static_method(
class,
jni_str!("context"),
jni_sig!(() -> android.content.Context),
&[],
)?
.l()
}
/// Ask for the microphone and notification permissions if not granted yet.
pub fn request_permissions() -> Result<()> {
with_bridge(|env, class| {
env.call_static_method(class, jni_str!("requestPermissions"), jni_sig!(() -> void), &[])?;
Ok(())
})
}
/// Show or update the voice service's notification; `None` stops the service.
pub fn set_voice_notification(notice: Option<&VoiceNotice>) -> Result<()> {
with_bridge(|env, class| {
let (text, muted) = match notice {
Some(n) => (JObject::from(env.new_string(&n.text)?), n.muted),
None => (JObject::null(), false),
};
env.call_static_method(
class,
jni_str!("setVoiceNotification"),
jni_sig!((text: java.lang.String, muted: jboolean) -> void),
&[JValue::Object(&text), JValue::Bool(muted)],
)?;
Ok(())
})
}
/// Ask the user to share the screen. The answer comes back through
/// `Native.onScreenCaptureResult`.
pub fn request_screen_capture(fps: u32, max_size: u32) -> Result<()> {
with_bridge(|env, class| {
env.call_static_method(
class,
jni_str!("requestScreenCapture"),
jni_sig!((fps: jint, max_size: jint) -> void),
&[JValue::Int(fps as jint), JValue::Int(max_size as jint)],
)?;
Ok(())
})
}
pub fn stop_screen_capture() -> Result<()> {
with_bridge(|env, class| {
env.call_static_method(class, jni_str!("stopScreenCapture"), jni_sig!(() -> void), &[])?;
Ok(())
})
}
/// Capture what the device plays; `false` without a running screen capture.
pub fn start_system_audio() -> Result<bool> {
with_bridge(|env, class| {
env.call_static_method(class, jni_str!("startSystemAudio"), jni_sig!(() -> jboolean), &[])?
.z()
})
}
pub fn stop_system_audio() -> Result<()> {
with_bridge(|env, class| {
env.call_static_method(class, jni_str!("stopSystemAudio"), jni_sig!(() -> void), &[])?;
Ok(())
})
}
pub fn secret_get(key: &str) -> Result<Option<String>> {
with_bridge(|env, class| {
let key = JObject::from(env.new_string(key)?);
let value = env
.call_static_method(
class,
jni_str!("secretGet"),
jni_sig!((key: java.lang.String) -> java.lang.String),
&[JValue::Object(&key)],
)?
.l()?;
if value.is_null() {
return Ok(None);
}
let value = env.cast_local::<JString>(value)?;
Ok(Some(value.try_to_string(env)?))
})
}
pub fn secret_set(key: &str, value: &str) -> Result<()> {
with_bridge(|env, class| {
let key = JObject::from(env.new_string(key)?);
let value = JObject::from(env.new_string(value)?);
env.call_static_method(
class,
jni_str!("secretSet"),
jni_sig!((key: java.lang.String, value: java.lang.String) -> void),
&[JValue::Object(&key), JValue::Object(&value)],
)?;
Ok(())
})
}
pub fn secret_delete(key: &str) -> Result<()> {
with_bridge(|env, class| {
let key = JObject::from(env.new_string(key)?);
env.call_static_method(
class,
jni_str!("secretDelete"),
jni_sig!((key: java.lang.String) -> void),
&[JValue::Object(&key)],
)?;
Ok(())
})
}
// Native methods of `Native` (Kotlin `object` with `@JvmStatic external`).
const _: jni::NativeMethod = native_method! {
java_type = "io.github.faumaray.voelin.Native",
static extern fn on_screen_capture_result(granted: jboolean, error: JString),
};
fn on_screen_capture_result<'local>(
env: &mut Env<'local>,
_class: JClass<'local>,
granted: jboolean,
error: JString<'local>,
) -> Result<()> {
let error = if error.is_null() { None } else { Some(error.try_to_string(env)?) };
crate::capture::on_result(granted, error);
Ok(())
}
const _: jni::NativeMethod = native_method! {
java_type = "io.github.faumaray.voelin.Native",
static extern fn on_screen_frame(
pixels: JByteBuffer,
width: jint,
height: jint,
row_stride: jint,
timestamp_ns: jlong,
) -> jboolean,
};
/// An RGBA frame from the `ImageReader`. Returns `false` when frames are no
/// longer wanted (the service then stops capturing).
fn on_screen_frame<'local>(
env: &mut Env<'local>,
_class: JClass<'local>,
pixels: JByteBuffer<'local>,
width: jint,
height: jint,
row_stride: jint,
timestamp_ns: jlong,
) -> Result<jboolean> {
if !crate::capture::wants_frames() {
return Ok(false);
}
let address = env.get_direct_buffer_address(&pixels)?;
let capacity = env.get_direct_buffer_capacity(&pixels)?;
if address.is_null() {
return Err(Error::NullPtr("screen frame buffer"));
}
// SAFETY: a direct buffer's memory is `capacity` bytes at `address`, and
// the `Image` it belongs to stays open until this call returns.
#[allow(unsafe_code)]
let bytes = unsafe { std::slice::from_raw_parts(address, capacity) }.to_vec();
Ok(crate::capture::on_frame(
bytes,
width.max(0) as u32,
height.max(0) as u32,
row_stride.max(0) as usize,
timestamp_ns,
))
}
const _: jni::NativeMethod = native_method! {
java_type = "io.github.faumaray.voelin.Native",
static extern fn on_screen_capture_stopped(),
};
fn on_screen_capture_stopped<'local>(_env: &mut Env<'local>, _class: JClass<'local>) -> Result<()> {
crate::capture::on_stopped();
Ok(())
}
const _: jni::NativeMethod = native_method! {
java_type = "io.github.faumaray.voelin.Native",
static extern fn on_system_audio(samples: jfloat[], count: jint, channels: jint, timestamp_ns: jlong) -> jboolean,
};
/// Interleaved 48 kHz float samples of what the device plays.
fn on_system_audio<'local>(
env: &mut Env<'local>,
_class: JClass<'local>,
samples: JFloatArray<'local>,
count: jint,
channels: jint,
timestamp_ns: jlong,
) -> Result<jboolean> {
if !crate::capture::wants_audio() {
return Ok(false);
}
let mut buffer = vec![0f32; count.max(0) as usize];
samples.get_region(env, 0, &mut buffer)?;
Ok(crate::capture::on_audio(buffer, channels.clamp(1, 8) as u16, timestamp_ns))
}
const _: jni::NativeMethod = native_method! {
java_type = "io.github.faumaray.voelin.Native",
static extern fn on_disconnect_voice(),
};
/// "Disconnect" in the voice notification.
fn on_disconnect_voice<'local>(_env: &mut Env<'local>, _class: JClass<'local>) -> Result<()> {
crate::app::disconnect_voice();
Ok(())
}
const _: jni::NativeMethod = native_method! {
java_type = "io.github.faumaray.voelin.Native",
static extern fn on_toggle_mute(),
};
/// "Mute" / "Unmute" in the voice notification.
fn on_toggle_mute<'local>(_env: &mut Env<'local>, _class: JClass<'local>) -> Result<()> {
crate::app::toggle_mute();
Ok(())
}
+216
View File
@@ -0,0 +1,216 @@
//! Screen and system-audio capture through MediaProjection.
//!
//! Registered as `voelin_media` capture providers, so stream code captures with
//! `voelin_media::capture::default_screen_capture()` as on desktop. Starting
//! asks the Kotlin side for the user's consent; on consent it runs
//! `ScreenCaptureService` (a `mediaProjection` foreground service) whose
//! `ImageReader` hands RGBA frames to [`on_frame`]. System audio
//! (`AudioPlaybackCapture`, 48 kHz float) needs that running projection.
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
use std::time::Duration;
use tokio::sync::oneshot;
use tracing::warn;
use voelin_media::capture::external::{self, AudioProvider, ScreenProvider};
use voelin_media::capture::{BoxFuture, CaptureOptions, CaptureSource, SourceId};
use voelin_media::{AudioBuffer, Error, FrameSender, Result, VideoFrame};
use crate::bridge;
const SCREEN: &str = "mediaprojection";
const AUDIO: &str = "playbackcapture";
/// Longest side of captured frames (the service scales the display down).
const MAX_SIZE: u32 = 1920;
#[derive(Default)]
struct State {
frames: Option<FrameSender<VideoFrame>>,
/// Answer for the pending `start`.
pending: Option<oneshot::Sender<Result<()>>>,
audio: Option<FrameSender<AudioBuffer>>,
/// Clock origin of frame and audio timestamps (both `CLOCK_MONOTONIC`
/// nanoseconds: `Image.timestamp`, `System.nanoTime`), so they stay in sync.
origin_ns: Option<i64>,
}
static STATE: Mutex<Option<State>> = Mutex::new(None);
fn with_state<R>(f: impl FnOnce(&mut State) -> R) -> R {
let mut guard: MutexGuard<'_, Option<State>> =
STATE.lock().unwrap_or_else(PoisonError::into_inner);
f(guard.get_or_insert_with(State::default))
}
/// Make MediaProjection the default screen and audio capture.
pub fn register() {
external::set_screen_provider(Some(Arc::new(Projection)));
external::set_audio_provider(Some(Arc::new(PlaybackAudio)));
}
fn since(first: &mut Option<i64>, now_ns: i64) -> Duration {
let first = *first.get_or_insert(now_ns);
Duration::from_nanos(u64::try_from(now_ns - first).unwrap_or(0))
}
struct Projection;
impl ScreenProvider for Projection {
fn name(&self) -> &'static str {
SCREEN
}
fn sources(&self) -> Vec<CaptureSource> {
vec![CaptureSource {
// The system dialog picks (whole screen, or one app on Android 14+).
id: SourceId::Portal,
name: "Screen".into(),
width: 0,
height: 0,
primary: true,
}]
}
fn start(
&self,
_source: &SourceId,
options: &CaptureOptions,
frames: FrameSender<VideoFrame>,
) -> BoxFuture<'static, Result<()>> {
let (tx, rx) = oneshot::channel();
with_state(|s| {
if let Some(previous) = s.pending.replace(tx) {
let _ = previous.send(Err(Error::Cancelled));
}
s.frames = Some(frames);
s.origin_ns = None;
});
if let Err(e) = bridge::request_screen_capture(options.fps.clamp(1, 60), MAX_SIZE) {
with_state(|s| {
s.pending = None;
s.frames = None;
});
let error = Error::CaptureUnavailable { backend: SCREEN, reason: e.to_string() };
return Box::pin(async move { Err(error) });
}
Box::pin(async move { rx.await.unwrap_or(Err(Error::Cancelled)) })
}
fn stop(&self) {
on_stopped();
if let Err(e) = bridge::stop_screen_capture() {
warn!("stopping screen capture: {e}");
}
}
}
struct PlaybackAudio;
impl AudioProvider for PlaybackAudio {
fn name(&self) -> &'static str {
AUDIO
}
fn start(&self, buffers: FrameSender<AudioBuffer>) -> Result<()> {
with_state(|s| {
s.audio = Some(buffers);
});
let started = bridge::start_system_audio();
match started {
Ok(true) => Ok(()),
Ok(false) | Err(_) => {
with_state(|s| s.audio = None);
let reason = match started {
Err(e) => e.to_string(),
_ => "needs a running screen capture (and the microphone permission)".into(),
};
Err(Error::CaptureUnavailable { backend: AUDIO, reason })
}
}
}
fn stop(&self) {
with_state(|s| s.audio = None);
if let Err(e) = bridge::stop_system_audio() {
warn!("stopping system audio: {e}");
}
}
}
/// The user answered the consent dialog (or the service failed to start).
pub fn on_result(granted: bool, error: Option<String>) {
with_state(|s| {
let result = match (granted, error) {
(true, _) => Ok(()),
(false, None) => Err(Error::Cancelled),
(false, Some(message)) => Err(Error::Capture { backend: SCREEN, message }),
};
if result.is_err() {
s.frames = None;
}
if let Some(pending) = s.pending.take() {
let _ = pending.send(result);
}
});
}
pub fn wants_frames() -> bool {
with_state(|s| s.frames.as_ref().is_some_and(|f| !f.is_closed()))
}
/// A captured RGBA frame. Returns `false` once nobody wants frames.
pub fn on_frame(
pixels: Vec<u8>,
width: u32,
height: u32,
stride: usize,
timestamp_ns: i64,
) -> bool {
with_state(|s| {
let timestamp = since(&mut s.origin_ns, timestamp_ns);
let Some(frames) = &s.frames else {
return false;
};
match VideoFrame::from_rgba(width, height, stride, pixels) {
Ok(frame) => {
if !frames.send(frame.with_timestamp(timestamp)) {
s.frames = None;
return false;
}
}
Err(e) => warn!("dropping a screen frame: {e}"),
}
true
})
}
/// The projection ended (stopped by us, the user, or the system): the
/// consumers see their channels close.
pub fn on_stopped() {
with_state(|s| {
s.frames = None;
s.audio = None;
if let Some(pending) = s.pending.take() {
let _ = pending.send(Err(Error::Cancelled));
}
});
}
pub fn wants_audio() -> bool {
with_state(|s| s.audio.as_ref().is_some_and(|a| !a.is_closed()))
}
/// Captured playback audio. Returns `false` once nobody wants it.
pub fn on_audio(samples: Vec<f32>, channels: u16, timestamp_ns: i64) -> bool {
with_state(|s| {
let timestamp = since(&mut s.origin_ns, timestamp_ns);
let Some(audio) = &s.audio else {
return false;
};
if !audio.send(AudioBuffer { samples, channels, timestamp }) {
s.audio = None;
return false;
}
true
})
}
+135
View File
@@ -0,0 +1,135 @@
//! Keep EGL extension slots for Skia (Mesa-based Android, e.g. Waydroid).
//!
//! Android's libEGL gives each GL function it has no built-in entry point for
//! one of a fixed number of "extension slots" (256) the first time
//! `eglGetProcAddress` looks it up. Slint's Skia OpenGL surface first loads
//! glow's whole function table, desktop GL included, and only then lets Skia
//! assemble its GLES interface. Vendor drivers return nothing for desktop-only
//! names, but Mesa returns an entry point for every name, so under Mesa glow
//! uses up all slots. Skia then gets nothing for the extension functions it
//! needs, e.g. `glTextureBarrierNV` when the driver advertises
//! `GL_NV_texture_barrier`, and the app cannot draw ("Could not create Skia
//! Direct Context from GL interface", with "no more slots for
//! eglGetProcAddress" before it in logcat).
//!
//! Looking Skia's extension functions up once, before Slint creates its
//! surface, gives them slots first; libEGL remembers them, and the lookups
//! that later fail are glow's desktop-only ones, which nothing here uses.
use std::ffi::{CStr, c_char, c_void};
use tracing::info;
#[link(name = "EGL")]
#[allow(unsafe_code)] // FFI declaration
unsafe extern "C" {
fn eglGetProcAddress(procname: *const c_char) -> *const c_void;
}
/// Every extension function (name with a vendor suffix) that Skia's GLES
/// interface can look up: `GET_PROC_SUFFIX` in Skia m153's
/// `src/gpu/ganesh/gl/GrGLAssembleGLESInterfaceAutogen.cpp` (the version
/// skia-safe 0.153 builds). Core GLES functions have built-in entry points and
/// need no slot. Update the list when skia-safe moves to a new Skia milestone.
const SKIA_GLES_EXTENSION_FUNCTIONS: &[&CStr] = &[
c"glBeginQueryEXT",
c"glBindFragDataLocationEXT",
c"glBindFragDataLocationIndexedEXT",
c"glBindUniformLocationCHROMIUM",
c"glBindVertexArrayOES",
c"glBlendBarrierKHR",
c"glBlendBarrierNV",
c"glBlitFramebufferANGLE",
c"glBlitFramebufferCHROMIUM",
c"glBlitFramebufferNV",
c"glClearTexImageEXT",
c"glClearTexSubImageEXT",
c"glClientWaitSyncAPPLE",
c"glCopyBufferSubDataNV",
c"glDebugMessageCallbackKHR",
c"glDebugMessageControlKHR",
c"glDebugMessageInsertKHR",
c"glDeleteFencesNV",
c"glDeleteQueriesEXT",
c"glDeleteSyncAPPLE",
c"glDeleteVertexArraysOES",
c"glDiscardFramebufferEXT",
c"glDrawArraysInstancedANGLE",
c"glDrawArraysInstancedBaseInstanceANGLE",
c"glDrawArraysInstancedBaseInstanceEXT",
c"glDrawArraysInstancedEXT",
c"glDrawElementsInstancedANGLE",
c"glDrawElementsInstancedBaseVertexBaseInstanceANGLE",
c"glDrawElementsInstancedBaseVertexBaseInstanceEXT",
c"glDrawElementsInstancedEXT",
c"glEndQueryEXT",
c"glEndTilingQCOM",
c"glFenceSyncAPPLE",
c"glFinishFenceNV",
c"glFlushMappedBufferRangeEXT",
c"glFramebufferTexture2DMultisampleEXT",
c"glFramebufferTexture2DMultisampleIMG",
c"glGenFencesNV",
c"glGenQueriesEXT",
c"glGenVertexArraysOES",
c"glGetDebugMessageLogKHR",
c"glGetProgramBinaryOES",
c"glGetQueryObjecti64vEXT",
c"glGetQueryObjectui64vEXT",
c"glGetQueryObjectuivEXT",
c"glGetQueryivEXT",
c"glInsertEventMarkerEXT",
c"glIsSyncAPPLE",
c"glMapBufferOES",
c"glMapBufferRangeEXT",
c"glMapBufferSubDataCHROMIUM",
c"glMapTexSubImage2DCHROMIUM",
c"glMultiDrawArraysIndirectEXT",
c"glMultiDrawArraysInstancedBaseInstanceANGLE",
c"glMultiDrawElementsIndirectEXT",
c"glMultiDrawElementsInstancedBaseVertexBaseInstanceANGLE",
c"glObjectLabelKHR",
c"glPatchParameteriOES",
c"glPopDebugGroupKHR",
c"glPopGroupMarkerEXT",
c"glProgramBinaryOES",
c"glPushDebugGroupKHR",
c"glPushGroupMarkerEXT",
c"glQueryCounterEXT",
c"glRenderbufferStorageMultisampleANGLE",
c"glRenderbufferStorageMultisampleCHROMIUM",
c"glResolveMultisampleFramebufferAPPLE",
c"glSetFenceNV",
c"glStartTilingQCOM",
c"glTestFenceNV",
c"glTexBufferEXT",
c"glTexBufferOES",
c"glTexBufferRangeEXT",
c"glTexBufferRangeOES",
c"glTexStorage2DEXT",
c"glTextureBarrierNV",
c"glUnmapBufferOES",
c"glUnmapBufferSubDataCHROMIUM",
c"glUnmapTexSubImage2DCHROMIUM",
c"glVertexAttribDivisorANGLE",
c"glVertexAttribDivisorEXT",
c"glWaitSyncAPPLE",
c"glWindowRectanglesEXT",
];
/// Look up [`SKIA_GLES_EXTENSION_FUNCTIONS`] so libEGL keeps their slots.
/// Call once per process, before the first window is shown.
pub fn reserve_skia_extension_slots() {
let found = SKIA_GLES_EXTENSION_FUNCTIONS.iter().filter(|name| resolves(name)).count();
info!(
"EGL: {found} of {} Skia extension functions resolved ahead of Slint's surface",
SKIA_GLES_EXTENSION_FUNCTIONS.len()
);
}
#[allow(unsafe_code)] // the FFI call
fn resolves(name: &CStr) -> bool {
// SAFETY: `name` is NUL-terminated; eglGetProcAddress may be the first EGL
// call of the process and only returns an address, which is not used.
!unsafe { eglGetProcAddress(name.as_ptr()) }.is_null()
}
+132
View File
@@ -0,0 +1,132 @@
//! When the app needs its voice foreground service.
//!
//! Android keeps the microphone and the process of a backgrounded app only
//! while a foreground service with a visible notification runs. The service
//! runs while any session has a voice connection (connecting or connected);
//! its notification names the servers and offers Mute and Disconnect.
use std::collections::BTreeMap;
use voelin_core::{Event, SessionId, VoiceState};
/// What the voice notification shows.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct VoiceNotice {
pub text: String,
/// The microphone is muted in every voice session (the action unmutes).
pub muted: bool,
}
#[derive(Default)]
pub struct Foreground {
sessions: BTreeMap<SessionId, Session>,
}
#[derive(Default)]
struct Session {
name: Option<String>,
voice: VoiceState,
muted: bool,
}
impl Foreground {
/// Apply `event`. Returns the new notification when it changed:
/// `Some(None)` means the service should stop.
pub fn update(&mut self, event: &Event) -> Option<Option<VoiceNotice>> {
let before = self.notice();
match event {
Event::State { session, state } => {
let s = self.sessions.entry(*session).or_default();
s.voice = state.voice;
s.muted = state.input_muted;
}
Event::ServerInfo { session, name, .. } => {
self.sessions.entry(*session).or_default().name = Some(name.clone());
}
_ => return None,
}
let after = self.notice();
(after != before).then_some(after)
}
fn active(&self) -> impl Iterator<Item = (&SessionId, &Session)> {
self.sessions.iter().filter(|(_, s)| s.voice != VoiceState::Disconnected)
}
/// Sessions with a voice connection (for the notification's actions).
pub fn voice_sessions(&self) -> Vec<SessionId> {
self.active().map(|(id, _)| *id).collect()
}
/// The notification, `None` without voice.
pub fn notice(&self) -> Option<VoiceNotice> {
let active: Vec<&Session> = self.active().map(|(_, s)| s).collect();
if active.is_empty() {
return None;
}
let names: Vec<&str> =
active.iter().map(|s| s.name.as_deref().unwrap_or("a server")).collect();
let names = names.join(", ");
let text = if active.iter().all(|s| s.voice == VoiceState::Connecting) {
format!("Connecting to {names}")
} else {
format!("In voice on {names}")
};
Some(VoiceNotice { text, muted: active.iter().all(|s| s.muted) })
}
}
#[cfg(test)]
mod tests {
use voelin_core::SessionState;
use voelin_model::{Capabilities, ServerFlavor};
use super::*;
fn voice(session: SessionId, voice: VoiceState, input_muted: bool) -> Event {
Event::State {
session,
state: SessionState { voice, input_muted, ..SessionState::default() },
}
}
fn notice(text: &str, muted: bool) -> Option<Option<VoiceNotice>> {
Some(Some(VoiceNotice { text: text.into(), muted }))
}
#[test]
fn service_follows_voice_connections() {
let mut fg = Foreground::default();
assert_eq!(fg.update(&voice(1, VoiceState::Disconnected, false)), None);
assert_eq!(
fg.update(&voice(1, VoiceState::Connecting, false)),
notice("Connecting to a server", false)
);
let info = Event::ServerInfo {
session: 1,
name: "Home".into(),
flavor: ServerFlavor::Unknown(String::new()),
capabilities: Capabilities::default(),
};
assert_eq!(fg.update(&info), notice("Connecting to Home", false));
assert_eq!(
fg.update(&voice(1, VoiceState::Connected, false)),
notice("In voice on Home", false)
);
assert_eq!(fg.update(&voice(1, VoiceState::Connected, false)), None, "no change");
assert_eq!(
fg.update(&voice(1, VoiceState::Connected, true)),
notice("In voice on Home", true)
);
// A second session that is not muted: the action mutes both.
assert_eq!(
fg.update(&voice(2, VoiceState::Connecting, false)),
notice("In voice on Home, a server", false)
);
assert_eq!(fg.voice_sessions(), [1, 2]);
assert_eq!(fg.update(&Event::Error { session: 1, message: "x".into() }), None);
fg.update(&voice(2, VoiceState::Disconnected, false));
assert_eq!(fg.update(&voice(1, VoiceState::Disconnected, true)), Some(None));
assert!(fg.voice_sessions().is_empty());
}
}
+314
View File
@@ -0,0 +1,314 @@
//! The engine for the whole process.
//!
//! Android destroys and recreates the activity (and so the window and its
//! thread) while a voice call goes on in a foreground service. The engine
//! therefore lives here, on its own runtime, for as long as the process; a
//! new window [attaches](EngineHost::attach) and first receives events that
//! rebuild the current state ([`Replay`]), then the live ones.
use std::collections::{BTreeMap, VecDeque};
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
use tokio::runtime::{Handle, Runtime};
use tokio::sync::{broadcast, mpsc};
use voelin_core::{Engine, Event, SessionId, StreamState, WatchState};
/// Chat messages per session a new window gets back.
pub const CHAT_BACKLOG: usize = 300;
/// The latest state-bearing events per session.
#[derive(Default)]
pub struct Replay {
sessions: BTreeMap<SessionId, SessionReplay>,
}
#[derive(Default)]
struct SessionReplay {
server_info: Option<Event>,
state: Option<Event>,
presence: Option<Event>,
streams: Option<Event>,
own_stream: Option<Event>,
viewers: Option<Event>,
watching: BTreeMap<String, Event>,
chat: VecDeque<Event>,
}
impl Replay {
/// Remember what `event` changes.
pub fn record(&mut self, event: &Event) {
let session = match event {
Event::State { session, .. }
| Event::ServerInfo { session, .. }
| Event::Presence { session, .. }
| Event::Chat { session, .. }
| Event::StreamsChanged { session, .. }
| Event::StreamState { session, .. }
| Event::StreamViewers { session, .. }
| Event::WatchState { session, .. } => *session,
// Transient: talking flags, errors, requests, keyframe requests.
_ => return,
};
let s = self.sessions.entry(session).or_default();
let slot = Some(event.clone());
match event {
Event::State { .. } => s.state = slot,
Event::ServerInfo { .. } => s.server_info = slot,
Event::Presence { .. } => s.presence = slot,
Event::StreamsChanged { .. } => s.streams = slot,
Event::StreamViewers { .. } => s.viewers = slot,
Event::StreamState { state, .. } => {
if matches!(state, StreamState::Ended(_)) {
s.own_stream = None;
s.viewers = None;
} else {
s.own_stream = slot;
}
}
Event::WatchState { stream_id, state, .. } => {
if matches!(state, WatchState::Ended(_)) {
s.watching.remove(stream_id);
} else {
s.watching.insert(stream_id.clone(), event.clone());
}
}
Event::Chat { .. } => {
if s.chat.len() == CHAT_BACKLOG {
s.chat.pop_front();
}
s.chat.push_back(event.clone());
}
_ => {}
}
}
/// Events that rebuild the recorded state, per session: server info,
/// state, presence, chat, then streams.
pub fn events(&self) -> Vec<Event> {
let mut out = Vec::new();
for s in self.sessions.values() {
out.extend(s.server_info.iter().cloned());
out.extend(s.state.iter().cloned());
out.extend(s.presence.iter().cloned());
out.extend(s.chat.iter().cloned());
out.extend(s.streams.iter().cloned());
out.extend(s.own_stream.iter().cloned());
out.extend(s.viewers.iter().cloned());
out.extend(s.watching.values().cloned());
}
out
}
}
/// Events of one source, recorded and passed on to the attached window.
#[derive(Clone, Default)]
pub struct Fanout {
shared: Arc<Mutex<FanoutState>>,
}
#[derive(Default)]
struct FanoutState {
replay: Replay,
window: Option<mpsc::UnboundedSender<Event>>,
}
impl Fanout {
fn lock(&self) -> MutexGuard<'_, FanoutState> {
self.shared.lock().unwrap_or_else(PoisonError::into_inner)
}
/// Record `event` and pass it to the window, if one is attached.
pub fn publish(&self, event: Event) {
let mut state = self.lock();
state.replay.record(&event);
if let Some(window) = &state.window
&& window.send(event).is_err()
{
state.window = None;
}
}
/// Receive events from now on, starting with the replay. A previously
/// attached window stops receiving (its channel closes).
pub fn attach(&self) -> mpsc::UnboundedReceiver<Event> {
let (tx, rx) = mpsc::unbounded_channel();
let mut state = self.lock();
for event in state.replay.events() {
let _ = tx.send(event);
}
state.window = Some(tx);
rx
}
/// Forward `source` until it closes; then the window's channel closes.
pub async fn pump(self, mut source: broadcast::Receiver<Event>) {
loop {
match source.recv().await {
Ok(event) => self.publish(event),
Err(broadcast::error::RecvError::Lagged(n)) => {
tracing::warn!(missed = n, "engine events lagged");
}
Err(broadcast::error::RecvError::Closed) => break,
}
}
self.lock().window = None;
}
}
/// The process's engine, runtime and event fan-out.
pub struct EngineHost {
runtime: Runtime,
engine: Engine,
fanout: Fanout,
}
/// What a window needs: see `voelin_ui::HostedEngine`.
pub struct Attached {
pub engine: Engine,
pub runtime: Handle,
pub events: mpsc::UnboundedReceiver<Event>,
}
impl EngineHost {
pub fn start() -> std::io::Result<Self> {
let runtime = tokio::runtime::Builder::new_multi_thread()
.enable_all()
.thread_name("voelin-engine")
.build()?;
let engine = runtime.block_on(async { Engine::start() });
let fanout = Fanout::default();
runtime.spawn(fanout.clone().pump(engine.subscribe()));
Ok(Self { runtime, engine, fanout })
}
pub fn engine(&self) -> &Engine {
&self.engine
}
pub fn runtime(&self) -> &Handle {
self.runtime.handle()
}
/// Hand the engine to a new window.
pub fn attach(&self) -> Attached {
Attached {
engine: self.engine.clone(),
runtime: self.runtime.handle().clone(),
events: self.fanout.attach(),
}
}
}
#[cfg(test)]
mod tests {
use std::sync::Arc as StdArc;
use voelin_core::{SessionState, VoiceState};
use voelin_model::{ChatMessage, ChatTarget, Presence};
use super::*;
fn state(session: SessionId, voice: VoiceState) -> Event {
Event::State { session, state: SessionState { voice, ..SessionState::default() } }
}
fn chat(session: SessionId, text: &str) -> Event {
Event::Chat {
session,
message: ChatMessage {
target: ChatTarget::Server,
author_name: "a".into(),
author_uid: None,
author_id: None,
text: text.into(),
ts_ms: 0,
via_relay: false,
},
}
}
fn describe(events: &[Event]) -> Vec<String> {
events
.iter()
.map(|e| match e {
Event::State { session, state } => format!("{session} state {:?}", state.voice),
Event::Presence { session, .. } => format!("{session} presence"),
Event::Chat { session, message } => format!("{session} chat {}", message.text),
Event::WatchState { session, stream_id, .. } => {
format!("{session} watch {stream_id}")
}
other => format!("{other:?}"),
})
.collect()
}
#[test]
fn replay_keeps_the_latest_state_and_the_chat_backlog() {
let mut replay = Replay::default();
replay.record(&state(2, VoiceState::Connecting));
replay.record(&Event::Presence { session: 2, presence: StdArc::new(Presence::default()) });
replay.record(&state(2, VoiceState::Connected));
replay.record(&Event::Talking { session: 2, client: 5, talking: true });
replay.record(&Event::Error { session: 2, message: "x".into() });
for i in 0..CHAT_BACKLOG + 2 {
replay.record(&chat(1, &i.to_string()));
}
replay.record(&Event::WatchState {
session: 2,
stream_id: "s1".into(),
state: WatchState::Connected,
});
replay.record(&Event::WatchState {
session: 2,
stream_id: "s2".into(),
state: WatchState::Requested,
});
replay.record(&Event::WatchState {
session: 2,
stream_id: "s2".into(),
state: WatchState::Ended(voelin_core::stream::EndReason::Local),
});
let events = describe(&replay.events());
assert_eq!(events.len(), CHAT_BACKLOG + 3);
assert_eq!(events[0], "1 chat 2", "the oldest messages are dropped");
assert_eq!(events[CHAT_BACKLOG - 1], format!("1 chat {}", CHAT_BACKLOG + 1));
assert_eq!(
events[CHAT_BACKLOG..],
["2 state Connected", "2 presence", "2 watch s1"].map(String::from)
);
}
#[tokio::test]
async fn a_new_window_gets_the_replay_then_live_events() {
let (tx, rx) = broadcast::channel(16);
let fanout = Fanout::default();
let pump = tokio::spawn(fanout.clone().pump(rx));
tx.send(state(1, VoiceState::Connected)).unwrap();
tx.send(chat(1, "before")).unwrap();
tokio::task::yield_now().await;
while fanout.lock().replay.events().len() < 2 {
tokio::task::yield_now().await;
}
let mut first = fanout.attach();
assert_eq!(describe(&[first.recv().await.unwrap()]), ["1 state Connected"]);
assert_eq!(describe(&[first.recv().await.unwrap()]), ["1 chat before"]);
tx.send(chat(1, "live")).unwrap();
assert_eq!(describe(&[first.recv().await.unwrap()]), ["1 chat live"]);
// The activity is recreated: the old window's channel ends.
let mut second = fanout.attach();
assert!(first.recv().await.is_none());
let mut replayed = Vec::new();
for _ in 0..3 {
replayed.push(second.recv().await.unwrap());
}
assert_eq!(describe(&replayed), ["1 state Connected", "1 chat before", "1 chat live"]);
drop(tx);
pump.await.unwrap();
assert!(second.recv().await.is_none(), "the source closed");
}
}
+34
View File
@@ -0,0 +1,34 @@
//! The Android app's native library (`libvoelin_android.so`).
//!
//! The APK (`android/`) starts a `NativeActivity` subclass that loads this
//! library; `android_main` then runs the shared Slint UI (`voelin_ui`) on
//! Slint's Android backend. The pieces around it:
//!
//! - [`host`]: one engine per process, so voice survives the activity being
//! destroyed and recreated; a new window gets the current state replayed
//! - [`foreground`]: when the voice foreground service must run (Android
//! only lets a service with a notification keep the microphone in the
//! background)
//! - `bridge` (Android): JNI calls into the Kotlin side (`Bridge`) and the
//! native methods it calls back (`Native`)
//! - `capture` (Android): screen and system-audio capture through
//! MediaProjection, registered as `voelin_media` capture providers
//! - `secrets` (Android): passwords encrypted with an Android Keystore key
//! - `egl` (Android): keeps EGL extension slots for Skia, without which the
//! UI cannot draw on Mesa-based Android (Waydroid)
//!
//! Only [`host`] and [`foreground`] build on other platforms, for tests.
pub mod foreground;
pub mod host;
#[cfg(target_os = "android")]
mod app;
#[cfg(target_os = "android")]
mod bridge;
#[cfg(target_os = "android")]
mod capture;
#[cfg(target_os = "android")]
mod egl;
#[cfg(target_os = "android")]
mod secrets;
+29
View File
@@ -0,0 +1,29 @@
//! Passwords in the Android Keystore.
//!
//! The Kotlin `SecretStore` encrypts each value with an AES-GCM key that
//! lives in the Android Keystore (hardware-backed where the device has it)
//! and keeps the ciphertext in the app's private preferences.
use voelin_store::{Error, Result, Secrets};
use crate::bridge;
pub struct KeystoreSecrets;
fn error(e: jni::errors::Error) -> Error {
Error::Secrets(format!("Android Keystore: {e}"))
}
impl Secrets for KeystoreSecrets {
fn get(&self, key: &str) -> Result<Option<String>> {
bridge::secret_get(key).map_err(error)
}
fn set(&self, key: &str, value: &str) -> Result<()> {
bridge::secret_set(key, value).map_err(error)
}
fn delete(&self, key: &str) -> Result<()> {
bridge::secret_delete(key).map_err(error)
}
}
@@ -1,5 +1,5 @@
[package]
name = "tsc-audio"
name = "voelin-audio"
version = "0.1.0"
description = "Voice pipeline: Opus encoding, framing, resampling, jitter buffer/mixer and audio devices."
edition.workspace = true
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -1,5 +1,5 @@
//! All user audio settings in one serde struct, e.g. for
//! `tsc_store::Store::set_setting("audio", &settings)`. Missing fields take
//! `voelin_store::Store::set_setting("audio", &settings)`. Missing fields take
//! their defaults, so stored settings survive new options.
use serde::{Deserialize, Serialize};
File renamed without changes.
@@ -52,7 +52,7 @@ mod tests {
#[test]
fn roundtrip() {
let path = std::env::temp_dir().join(format!("tsc-audio-{}.wav", std::process::id()));
let path = std::env::temp_dir().join(format!("voelin-audio-{}.wav", std::process::id()));
let clip = Clip { samples: vec![0.0, 0.5, -0.5, 0.25], channels: 2, rate: 48_000 };
write(&path, &clip).unwrap();
let back = read(&path).unwrap();
@@ -7,10 +7,10 @@
//! loss. Every 30 s it sends a loud marker frame instead of the quiet one;
//! the latency is the time from generating a marker to it leaving the mixer.
use tsc_audio::pcm::{FRAME_SAMPLES, SAMPLE_RATE, energy, sine, white_noise};
use tsc_audio::{Mixer, VoiceCodec, VoiceEncoder};
use tsclientlib::ClientId;
use tsproto_packets::packets::{AudioData, CodecType, Direction, InAudioBuf, OutAudio};
use voelin_audio::pcm::{FRAME_SAMPLES, SAMPLE_RATE, energy, sine, white_noise};
use voelin_audio::{Mixer, VoiceCodec, VoiceEncoder};
/// The receiver pulls 10 ms at a time, like a playback loop.
const PULL: usize = SAMPLE_RATE as usize / 100;
+46
View File
@@ -0,0 +1,46 @@
[package]
name = "voelin-core"
version = "0.1.0"
description = "Client engine: server sessions merging voice, gateway and query sources; the API the UI drives."
edition.workspace = true
rust-version.workspace = true
license.workspace = true
repository.workspace = true
publish.workspace = true
[features]
default = ["audio-device"]
# Capture and play audio through the system's devices.
audio-device = ["voelin-audio/device"]
# The `media` module: capture and video codecs for streams, with whatever
# voelin-media backends are enabled (e.g. MediaCodec and a registered capture
# source on Android).
media = ["dep:voelin-media"]
# `media` with voelin-media's desktop backends: libvpx, OpenH264 loaded at
# runtime, X11 and PipeWire on Linux. Not for Android (libvpx does not
# cross-compile there).
media-desktop = ["media", "voelin-media/default"]
[dependencies]
anyhow = "1"
futures = "0.3"
serde_json = "1"
thiserror = "2"
tokio = { version = "1", features = ["macros", "rt-multi-thread", "sync", "time"] }
tokio-tungstenite = "0.30"
tracing = "0.1"
voelin-audio = { path = "../voelin-audio", default-features = false }
voelin-gateway-proto = { path = "../voelin-gateway-proto" }
voelin-media = { path = "../voelin-media", default-features = false, features = ["str0m"], optional = true }
voelin-model = { path = "../voelin-model" }
voelin-observer = { path = "../voelin-observer" }
voelin-query = { path = "../voelin-query" }
voelin-stream = { path = "../voelin-stream" }
tsclientlib = { path = "../proto/tsclientlib" }
tsproto-packets = { path = "../proto/tsproto-packets" }
[dev-dependencies]
tokio = { version = "1", features = ["macros", "rt-multi-thread", "test-util"] }
[lints]
workspace = true
@@ -8,18 +8,20 @@
//! independent part is [`Pipeline`]; the thread loop only moves samples
//! between it and the devices, reopening devices that go away.
use std::collections::VecDeque;
use std::collections::{HashMap, VecDeque};
use std::sync::Arc;
use std::sync::mpsc as std_mpsc;
use std::thread;
use std::time::{Duration, Instant};
use tokio::sync::mpsc;
use tracing::{debug, warn};
use tsc_audio::pcm::{self, FRAME_SAMPLES};
use tsc_audio::settings::TransmitMode;
use tsc_audio::{AudioSettings, Framer, Mixer, Processor, Vad, VoiceCodec, VoiceEncoder};
use tsclientlib::ClientId;
use tsproto_packets::packets::{AudioData, InAudioBuf, OutPacket};
use tsproto_packets::packets::{AudioData, CodecType, Direction, InAudioBuf, OutAudio, OutPacket};
use voelin_audio::pcm::{self, FRAME_SAMPLES};
use voelin_audio::settings::TransmitMode;
use voelin_audio::vad::SILENCE_DB;
use voelin_audio::{AudioSettings, Framer, Mixer, Processor, Vad, VoiceCodec, VoiceEncoder};
pub(crate) enum AudioIn {
Packet(InAudioBuf),
@@ -27,24 +29,46 @@ pub(crate) enum AudioIn {
InputMuted(bool),
OutputMuted(bool),
/// Devices, processing, voice activation and transmit mode.
#[allow(dead_code, reason = "sent once the session exposes audio settings")]
Settings(Box<AudioSettings>),
/// Playback volume of one client, linear (1 = unchanged, up to 4).
#[allow(dead_code, reason = "sent once the session exposes client volumes")]
ClientVolume {
client: ClientId,
volume: f32,
},
#[allow(dead_code, reason = "sent once the session exposes client volumes")]
ClientMuted {
client: ClientId,
muted: bool,
},
/// The client left; client ids are reused, so forget its volume.
#[allow(dead_code, reason = "sent once the session exposes client volumes")]
ClientLeft(ClientId),
/// An Opus frame (48 kHz) of a watched stream; `time` is its RTP time
/// on the 48 kHz clock.
StreamAudio {
stream: String,
time: u64,
data: Arc<[u8]>,
},
/// Playback volume of a watched stream, linear like client volumes.
StreamVolume {
stream: String,
volume: f32,
},
/// We stopped watching the stream: forget its queue and volume.
StreamEnded(String),
}
/// What the audio thread reports.
#[derive(Clone, Debug, PartialEq)]
pub(crate) enum AudioEvent {
/// A problem, e.g. a missing device.
Error(String),
/// Loudest microphone level (dBFS, after processing) since the last
/// report, and whether voice is being sent. About every
/// [`LEVEL_INTERVAL`] while the microphone delivers audio.
Level { db: f32, sending: bool },
}
#[derive(Clone)]
pub(crate) struct AudioHandle {
tx: std_mpsc::Sender<AudioIn>,
}
@@ -53,6 +77,13 @@ impl AudioHandle {
pub fn send(&self, msg: AudioIn) {
let _ = self.tx.send(msg);
}
/// A handle without a thread, to see what would reach it.
#[cfg(test)]
pub fn channel() -> (Self, std_mpsc::Receiver<AudioIn>) {
let (tx, rx) = std_mpsc::channel();
(Self { tx }, rx)
}
}
/// With voice activation, also send this many 20 ms frames from before the
@@ -68,25 +99,33 @@ const PLAYBACK_CAPACITY_MS: u32 = 200;
const DEVICE_LATENCY_MS: u32 = 20;
/// How long the loop sleeps between rounds.
const TICK: Duration = Duration::from_millis(5);
/// How often the microphone level is reported (for a meter).
pub(crate) const LEVEL_INTERVAL: Duration = Duration::from_millis(100);
/// Samples of one 20 ms Opus frame at 48 kHz: the unit of stream packet ids.
const OPUS_FRAME: u64 = 960;
/// Start the audio thread. Encoded packets go to `outgoing`; problems (e.g.
/// no device) are reported through `errors`.
/// no device) and the microphone level are reported through `events`.
pub(crate) fn spawn(
outgoing: mpsc::UnboundedSender<OutPacket>,
errors: mpsc::UnboundedSender<String>,
voice_activation: bool,
events: mpsc::UnboundedSender<AudioEvent>,
settings: AudioSettings,
) -> AudioHandle {
let transmit =
if voice_activation { TransmitMode::VoiceActivation } else { TransmitMode::PushToTalk };
let settings = AudioSettings { transmit, ..Default::default() };
let (tx, rx) = std_mpsc::channel();
thread::Builder::new()
.name("tsc-audio".into())
.spawn(move || run(rx, outgoing, errors, settings))
.name("voelin-audio".into())
.spawn(move || run(rx, outgoing, events, settings))
.expect("spawn audio thread");
AudioHandle { tx }
}
/// Audio of a watched stream in the mixer, under a made-up client id.
struct StreamAudio {
client: ClientId,
/// RTP time and packet id of the last packet.
last: Option<(u64, u64)>,
}
/// Everything between the devices and the connection.
struct Pipeline {
settings: AudioSettings,
@@ -101,13 +140,18 @@ struct Pipeline {
input_muted: bool,
output_muted: bool,
was_sending: bool,
/// Loudest level since the last report; `None` without microphone audio.
level_peak: Option<f32>,
/// Watched streams whose audio plays through the mixer.
streams: HashMap<String, StreamAudio>,
stream_volumes: HashMap<String, f32>,
/// Processed microphone audio, for tests.
#[cfg(test)]
tap: Vec<f32>,
}
impl Pipeline {
fn new(settings: AudioSettings) -> tsc_audio::Result<Self> {
fn new(settings: AudioSettings) -> voelin_audio::Result<Self> {
let settings = sanitize(settings);
Ok(Self {
encoder: VoiceEncoder::new(VoiceCodec::Voice)?,
@@ -121,6 +165,9 @@ impl Pipeline {
input_muted: false,
output_muted: false,
was_sending: false,
level_peak: None,
streams: HashMap::new(),
stream_volumes: HashMap::new(),
settings,
#[cfg(test)]
tap: Vec::new(),
@@ -154,9 +201,73 @@ impl Pipeline {
AudioIn::ClientVolume { client, volume } => self.mixer.set_volume(client, volume),
AudioIn::ClientMuted { client, muted } => self.mixer.set_muted(client, muted),
AudioIn::ClientLeft(client) => self.mixer.forget(client),
AudioIn::StreamAudio { stream, time, data } => self.stream_packet(stream, time, &data),
AudioIn::StreamVolume { stream, volume } => {
if let Some(s) = self.streams.get(&stream) {
self.mixer.set_volume(s.client, volume);
}
self.stream_volumes.insert(stream, volume);
}
AudioIn::StreamEnded(stream) => {
if let Some(s) = self.streams.remove(&stream) {
self.mixer.forget(s.client);
}
self.stream_volumes.remove(&stream);
}
}
}
/// Queue an Opus frame of a stream in the mixer, as if a client with a
/// made-up id (counting down from `u16::MAX`, where real ids are rare)
/// talked. The jitter buffer orders packets by id: one id per 20 ms of
/// RTP time, at least one per packet (shorter frames).
fn stream_packet(&mut self, stream: String, time: u64, data: &[u8]) {
let client = match self.streams.get(&stream) {
Some(s) => s.client,
None => {
let used: Vec<ClientId> = self.streams.values().map(|s| s.client).collect();
let Some(client) = (0..=u16::MAX).rev().map(ClientId).find(|c| !used.contains(c))
else {
return;
};
self.mixer.forget(client);
let volume = self.stream_volumes.get(&stream).copied().unwrap_or(1.0);
self.mixer.set_volume(client, volume);
self.streams.insert(stream.clone(), StreamAudio { client, last: None });
client
}
};
let entry = self.streams.get_mut(&stream).expect("inserted above");
let id = match entry.last {
None => time / OPUS_FRAME,
// Duplicate or reordered: the depacketizer delivers in order.
Some((last_time, _)) if time <= last_time => return,
Some((last_time, last_id)) => {
last_id + ((time - last_time + OPUS_FRAME / 2) / OPUS_FRAME).max(1)
}
};
entry.last = Some((time, id));
let packet = OutAudio::new(&AudioData::S2C {
id: id as u16,
codec: CodecType::OpusMusic,
from: client.0,
data,
});
match InAudioBuf::try_new(Direction::S2C, packet.into_vec()) {
Ok(packet) => {
if let Err(error) = self.mixer.handle_packet(client, packet) {
debug!(%error, "dropped stream audio packet");
}
}
Err(error) => debug!(?error, "stream audio packet"),
}
}
/// The loudest microphone level since the last call, if any audio came in.
fn take_level(&mut self) -> Option<f32> {
self.level_peak.take()
}
/// Microphone audio in (mono, 48 kHz, any length); voice packets out.
/// `delay_ms` is the playback-to-capture delay hint for the echo canceller.
fn capture(&mut self, samples: &[f32], delay_ms: u32, send: &mut impl FnMut(OutPacket)) {
@@ -175,6 +286,8 @@ impl Pipeline {
fn transmit(&mut self, frame: Vec<f32>, send: &mut impl FnMut(OutPacket)) {
// Always analysed, so the detector's state is current when needed.
let voice = self.vad.process(&frame);
let level = self.vad.level_db().max(SILENCE_DB);
self.level_peak = Some(self.level_peak.map_or(level, |peak| peak.max(level)));
let wanted = match self.settings.transmit {
TransmitMode::PushToTalk => self.ptt,
TransmitMode::VoiceActivation => voice,
@@ -232,18 +345,21 @@ fn sanitize(mut settings: AudioSettings) -> AudioSettings {
fn run(
rx: std_mpsc::Receiver<AudioIn>,
outgoing: mpsc::UnboundedSender<OutPacket>,
errors: mpsc::UnboundedSender<String>,
events: mpsc::UnboundedSender<AudioEvent>,
settings: AudioSettings,
) {
let error = |message: String| {
let _ = events.send(AudioEvent::Error(message));
};
#[cfg(feature = "audio-device")]
let mut devices = devices::Devices::new(&settings);
#[cfg(not(feature = "audio-device"))]
let _ = errors.send("built without audio device support".to_string());
error("built without audio device support".to_string());
let mut pipeline = match Pipeline::new(settings) {
Ok(p) => p,
Err(e) => {
let _ = errors.send(e.to_string());
error(e.to_string());
return;
}
};
@@ -253,6 +369,7 @@ fn run(
// Without speakers the mixer is drained at real time, so queues do not
// fill up and talkers still end.
let mut idle_clock = Instant::now();
let mut level_clock = Instant::now();
loop {
// Control messages and incoming voice.
@@ -271,7 +388,7 @@ fn run(
}
#[cfg(feature = "audio-device")]
let playing = devices.step(&mut pipeline, &mut send, &errors);
let playing = devices.step(&mut pipeline, &mut send, &error);
#[cfg(not(feature = "audio-device"))]
let playing = {
// No microphone: nothing to process, but keep the path alive.
@@ -289,19 +406,25 @@ fn run(
}
}
if level_clock.elapsed() >= LEVEL_INTERVAL {
level_clock = Instant::now();
if let Some(db) = pipeline.take_level() {
let _ = events.send(AudioEvent::Level { db, sending: pipeline.was_sending });
}
}
thread::sleep(TICK);
}
}
#[cfg(feature = "audio-device")]
mod devices {
use tokio::sync::mpsc;
use tracing::debug;
use tsc_audio::AudioSettings;
use tsc_audio::device::{Capture, DeviceEvent, Managed, Playback};
use tsc_audio::pcm::{self, FRAME_SAMPLES, SAMPLE_RATE};
use tsc_audio::resample::Linear;
use tsproto_packets::packets::OutPacket;
use voelin_audio::AudioSettings;
use voelin_audio::device::{Capture, DeviceEvent, Managed, Playback};
use voelin_audio::pcm::{self, FRAME_SAMPLES, SAMPLE_RATE};
use voelin_audio::resample::Linear;
use super::{DEVICE_LATENCY_MS, PLAYBACK_CAPACITY_MS, Pipeline};
@@ -324,7 +447,7 @@ mod devices {
&mut slot.as_mut().expect("just set").1
}
fn report(errors: &mpsc::UnboundedSender<String>, what: &str, event: DeviceEvent) {
fn report(error: &impl Fn(String), what: &str, event: DeviceEvent) {
let message = match event {
DeviceEvent::Opened { name, fallback: false } => {
debug!(%name, "{what} opened");
@@ -336,7 +459,7 @@ mod devices {
DeviceEvent::Lost { name } => format!("{what} disconnected: {name}"),
DeviceEvent::Unavailable(e) => format!("no {what}: {e}"),
};
let _ = errors.send(message);
error(message);
}
impl Devices {
@@ -362,13 +485,13 @@ mod devices {
&mut self,
pipeline: &mut Pipeline,
send: &mut impl FnMut(OutPacket),
errors: &mpsc::UnboundedSender<String>,
error: &impl Fn(String),
) -> bool {
if let Some(event) = self.playback.poll() {
report(errors, "speakers", event);
report(error, "speakers", event);
}
if let Some(event) = self.capture.poll() {
report(errors, "microphone", event);
report(error, "microphone", event);
}
// Mixer → speakers, keeping the configured amount queued.
@@ -408,9 +531,8 @@ mod devices {
#[cfg(test)]
mod tests {
use tsc_audio::pcm::{SAMPLE_RATE, energy, sine, white_noise};
use tsc_audio::{ProcessingSettings, VadSettings};
use tsproto_packets::packets::{CodecType, Direction, OutAudio};
use voelin_audio::pcm::{SAMPLE_RATE, energy, sine, white_noise};
use voelin_audio::{ProcessingSettings, VadSettings};
use super::*;
@@ -529,6 +651,52 @@ mod tests {
assert!(attenuation >= 10.0, "echo attenuated by {attenuation:.1} dB");
}
/// Stream audio (stereo Opus with RTP times) plays through the mixer at
/// its own volume and is forgotten when the stream ends.
#[test]
fn stream_audio_with_volume() {
let mut p = pipeline(TransmitMode::PushToTalk);
let mut encoder = VoiceEncoder::new(VoiceCodec::Music).unwrap();
let tone = pcm::from_mono(&sine(600.0, 1.0, 0.4), 2);
// A random RTP start, as WebRTC senders use.
let start = 7_777_000u64;
let mut play = |p: &mut Pipeline, stream: &str| -> f32 {
let mut out = Vec::new();
for (i, frame) in tone.chunks_exact(FRAME_SAMPLES * 2).enumerate() {
let data: Arc<[u8]> = encoder.encode_to_bytes(frame).unwrap().into();
let time = start + i as u64 * OPUS_FRAME;
p.handle(AudioIn::StreamAudio { stream: stream.into(), time, data: data.clone() });
// A duplicate is ignored.
p.handle(AudioIn::StreamAudio { stream: stream.into(), time, data });
out.extend(p.playback_frame());
}
energy(&out[out.len() / 2..])
};
let full = play(&mut p, "a");
assert!(full > 1e-3, "stream audio must be audible");
p.handle(AudioIn::StreamVolume { stream: "b".into(), volume: 0.5 });
let half = play(&mut p, "b");
let ratio_db = 10.0 * (half / full).log10();
assert!((ratio_db + 6.0).abs() < 1.0, "volume 0.5 gave {ratio_db} dB");
let mut clients: Vec<u16> = p.streams.values().map(|s| s.client.0).collect();
clients.sort_unstable();
assert_eq!(clients, [u16::MAX - 1, u16::MAX]);
p.handle(AudioIn::StreamEnded("b".into()));
assert_eq!(p.streams.len(), 1);
assert!(!p.stream_volumes.contains_key("b"));
}
#[test]
fn level_is_reported() {
let mut p = pipeline(TransmitMode::PushToTalk);
assert_eq!(p.take_level(), None, "no microphone audio yet");
// A sine of amplitude 0.3 has an RMS level of about -13.5 dBFS.
capture(&mut p, &sine(440.0, 0.1, 0.3));
let level = p.take_level().unwrap();
assert!((level + 13.5).abs() < 1.0, "{level}");
assert_eq!(p.take_level(), None);
}
#[test]
fn settings_are_sanitized() {
let mut p = pipeline(TransmitMode::PushToTalk);
@@ -5,8 +5,8 @@ use tokio::sync::mpsc;
use tokio_tungstenite::tungstenite::Message;
use tokio_tungstenite::tungstenite::client::IntoClientRequest;
use tracing::info;
use tsc_gateway_proto::{ClientMsg, Envelope, ServerMsg, sign_challenge};
use tsc_model::{ChatMessage, ChatTarget, Presence};
use voelin_gateway_proto::{ClientMsg, Envelope, ServerMsg, sign_challenge};
use voelin_model::{ChatMessage, ChatTarget, Presence};
pub(crate) enum GatewayCmd {
OpenChat(ChatTarget),
@@ -41,7 +41,9 @@ async fn run_inner(
events: &mpsc::UnboundedSender<GatewayEvent>,
) -> anyhow::Result<()> {
let mut request = url.into_client_request()?;
request.headers_mut().insert("Sec-WebSocket-Protocol", tsc_gateway_proto::SUBPROTOCOL.parse()?);
request
.headers_mut()
.insert("Sec-WebSocket-Protocol", voelin_gateway_proto::SUBPROTOCOL.parse()?);
let (mut ws, _) = tokio_tungstenite::connect_async(request).await?;
let mut next_id = 1u64;
let mut presence = Presence::default();
@@ -98,10 +100,10 @@ async fn run_inner(
let _ = events.send(GatewayEvent::Error(format!("{code:?}: {message}")));
if matches!(
code,
tsc_gateway_proto::ErrorCode::AuthFailed
| tsc_gateway_proto::ErrorCode::UnknownIdentity
| tsc_gateway_proto::ErrorCode::LevelTooLow
| tsc_gateway_proto::ErrorCode::Banned
voelin_gateway_proto::ErrorCode::AuthFailed
| voelin_gateway_proto::ErrorCode::UnknownIdentity
| voelin_gateway_proto::ErrorCode::LevelTooLow
| voelin_gateway_proto::ErrorCode::Banned
) {
anyhow::bail!("gateway refused login: {message}");
}
@@ -13,10 +13,15 @@
//!
//! On TeamSpeak 6 servers the voice connection also carries streams (screen
//! sharing): see the `*Stream*` commands and events, and
//! [`Engine::subscribe_frames`] for the frames of watched streams.
//! [`Engine::subscribe_frames`] for the frames of watched streams. The audio
//! of watched streams plays through the session's speakers by itself
//! ([`Command::SetStreamVolume`]); capture, encoding and decoding of video
//! are in [`media`] (feature `media`).
mod audio;
mod gateway;
#[cfg(feature = "media")]
pub mod media;
mod query;
mod route;
mod session;
@@ -27,11 +32,14 @@ use std::collections::HashMap;
use std::sync::Arc;
use tokio::sync::{broadcast, mpsc};
use tsc_model::{Capabilities, ChannelId, ChatMessage, ChatTarget, Presence, ServerFlavor};
pub use voelin_audio::settings::TransmitMode;
pub use voelin_audio::{AudioSettings, ProcessingSettings, VadSettings};
use voelin_model::{Capabilities, ChannelId, ChatMessage, ChatTarget, Presence, ServerFlavor};
use crate::audio::{AudioEvent, AudioHandle, AudioIn};
pub use route::{ChatRoute, Dedup, route_chat};
pub use stream::{StreamFrame, StreamSink, StreamState, WatchState};
use tsc_stream::{EncodedFrame, StreamInfo, StreamSetup, ViewerInfo};
use voelin_stream::{EncodedFrame, StreamInfo, StreamSetup, ViewerInfo};
pub use voice::VoiceOptions;
pub type SessionId = u64;
@@ -55,7 +63,7 @@ pub enum Command {
/// Invisible presence and relay chat with own ServerQuery credentials.
ObserveQuery {
session: SessionId,
connect: Box<tsc_query::Connect>,
connect: Box<voelin_query::Connect>,
},
StopObserving {
session: SessionId,
@@ -86,11 +94,33 @@ pub enum Command {
session: SessionId,
muted: bool,
},
/// Push-to-talk state (or "always transmit" when voice activation is off).
/// Push-to-talk key or button held (only counts with
/// [`TransmitMode::PushToTalk`]).
SetTransmitting {
session: SessionId,
on: bool,
},
/// Audio settings of all sessions (devices, processing, transmit mode),
/// also used by sessions started later.
SetAudioSettings(Box<AudioSettings>),
/// Playback volume of one client, linear (1 = unchanged, up to 4).
/// Local only; forgotten when the client leaves.
SetClientVolume {
session: SessionId,
client: u16,
volume: f32,
},
/// Do not play one client (local only).
SetClientMuted {
session: SessionId,
client: u16,
muted: bool,
},
/// Open the microphone without a session to show its level
/// ([`Event::InputLevel`] with `session: None`), e.g. in the settings.
TestMicrophone {
on: bool,
},
/// Start streaming in our channel (TeamSpeak 6 only). Progress comes as
/// [`Event::StreamState`]; frames go in through the sink of
/// [`StreamState::Live`] or [`Command::SendStreamFrame`].
@@ -134,6 +164,13 @@ pub enum Command {
session: SessionId,
stream_id: String,
},
/// Playback volume of a watched stream's audio, linear (1 = unchanged,
/// up to 4).
SetStreamVolume {
session: SessionId,
stream_id: String,
volume: f32,
},
/// Close everything of a session.
CloseSession {
session: SessionId,
@@ -172,6 +209,8 @@ pub struct SessionState {
pub presence_source: Option<Source>,
/// Our own channel while voice-connected.
pub own_channel: Option<ChannelId>,
/// Our own client id while voice-connected.
pub own_client: Option<u16>,
pub input_muted: bool,
pub output_muted: bool,
pub transmitting: bool,
@@ -205,6 +244,20 @@ pub enum Event {
client: u16,
talking: bool,
},
/// Microphone level for a meter, about ten times a second while the
/// microphone is open: of a voice session, or of
/// [`Command::TestMicrophone`] (`session: None`). `level_db` is the
/// loudest 10 ms (dBFS, after processing) since the last report;
/// `sending` whether voice is transmitted.
InputLevel {
session: Option<SessionId>,
level_db: f32,
sending: bool,
},
/// A problem with the microphone test (e.g. no device).
MicrophoneTestError {
message: String,
},
Error {
session: SessionId,
message: String,
@@ -248,6 +301,7 @@ pub struct Engine {
commands: mpsc::UnboundedSender<Command>,
events: broadcast::Sender<Event>,
frames: broadcast::Sender<StreamFrame>,
runtime: tokio::runtime::Handle,
}
impl Engine {
@@ -258,7 +312,13 @@ impl Engine {
// About a minute of one watched stream.
let (frames, _) = broadcast::channel(4096);
tokio::spawn(run(rx, events.clone(), frames.clone()));
Self { commands, events, frames }
Self { commands, events, frames, runtime: tokio::runtime::Handle::current() }
}
/// The runtime the engine runs on, for helpers started from other
/// threads (e.g. `media::Viewer` from a UI thread).
pub fn runtime(&self) -> &tokio::runtime::Handle {
&self.runtime
}
pub fn send(&self, command: Command) {
@@ -281,8 +341,26 @@ async fn run(
frames: broadcast::Sender<StreamFrame>,
) {
let mut sessions: HashMap<SessionId, session::SessionHandle> = HashMap::new();
let mut settings = AudioSettings::default();
let mut mic_test: Option<AudioHandle> = None;
while let Some(command) = commands.recv().await {
let id = command_session(&command);
let id = match command {
Command::SetAudioSettings(new) => {
settings = (*new).clone();
for s in sessions.values() {
s.send(Command::SetAudioSettings(new.clone()));
}
if let Some(test) = &mic_test {
test.send(AudioIn::Settings(new));
}
continue;
}
Command::TestMicrophone { on } => {
mic_test = on.then(|| test_microphone(&settings, &events));
continue;
}
ref command => command_session(command),
};
if matches!(command, Command::CloseSession { .. }) {
if let Some(s) = sessions.remove(&id) {
s.send(command);
@@ -291,11 +369,33 @@ async fn run(
}
sessions
.entry(id)
.or_insert_with(|| session::SessionHandle::spawn(id, events.clone(), frames.clone()))
.or_insert_with(|| {
session::SessionHandle::spawn(id, events.clone(), frames.clone(), settings.clone())
})
.send(command);
}
}
/// An audio thread whose packets go nowhere, for its level.
fn test_microphone(settings: &AudioSettings, events: &broadcast::Sender<Event>) -> AudioHandle {
let (packets, _) = mpsc::unbounded_channel();
let (audio_tx, mut audio_rx) = mpsc::unbounded_channel();
let handle = audio::spawn(packets, audio_tx, settings.clone());
let events = events.clone();
tokio::spawn(async move {
while let Some(event) = audio_rx.recv().await {
let _ = events.send(match event {
AudioEvent::Level { db, sending } => {
Event::InputLevel { session: None, level_db: db, sending }
}
AudioEvent::Error(message) => Event::MicrophoneTestError { message },
});
}
});
handle
}
/// The session a command is for (engine-wide commands are handled before).
fn command_session(command: &Command) -> SessionId {
match command {
Command::ConnectVoice { session, .. }
@@ -318,6 +418,12 @@ fn command_session(command: &Command) -> SessionId {
| Command::WatchStream { session, .. }
| Command::LeaveStream { session, .. }
| Command::RequestStreamKeyframe { session, .. }
| Command::SetStreamVolume { session, .. }
| Command::SetClientVolume { session, .. }
| Command::SetClientMuted { session, .. }
| Command::CloseSession { session } => *session,
Command::SetAudioSettings(_) | Command::TestMicrophone { .. } => {
unreachable!("engine-wide commands have no session")
}
}
}
File diff suppressed because it is too large. Load diff
@@ -1,8 +1,10 @@
//! The query source: own ServerQuery credentials, in-process observer and relays.
use tokio::sync::{broadcast, mpsc};
use tsc_model::{ChatMessage, ChatTarget, Presence};
use tsc_observer::{Observer, ObserverConfig, ObserverEvent, RelayConfig, RelayEvent, RelayPool};
use voelin_model::{ChatMessage, ChatTarget, Presence};
use voelin_observer::{
Observer, ObserverConfig, ObserverEvent, RelayConfig, RelayEvent, RelayPool,
};
pub(crate) enum QueryCmd {
OpenChat(ChatTarget),
@@ -19,7 +21,7 @@ pub(crate) enum QueryEvent {
}
pub(crate) async fn run(
connect: tsc_query::Connect,
connect: voelin_query::Connect,
mut commands: mpsc::UnboundedReceiver<QueryCmd>,
events: mpsc::UnboundedSender<QueryEvent>,
) {
@@ -74,7 +76,7 @@ pub(crate) async fn run(
Some(QueryCmd::SendChat { target, nick, text }) => {
let result = match &target {
ChatTarget::Channel(cid) => relays.send(*cid, &nick, &text).await,
_ => Err(tsc_query::Error::Unsupported("only channel chat is relayed with own credentials")),
_ => Err(voelin_query::Error::Unsupported("only channel chat is relayed with own credentials")),
};
if let Err(e) = result {
let _ = events.send(QueryEvent::Error(e.to_string()));
@@ -2,7 +2,7 @@
use std::collections::VecDeque;
use tsc_model::{ChannelId, ChatMessage, ChatTarget};
use voelin_model::{ChannelId, ChatMessage, ChatTarget};
/// Which source carries a chat.
#[derive(Clone, Debug, PartialEq, Eq)]
@@ -5,9 +5,11 @@ use std::sync::Arc;
use tokio::sync::{broadcast, mpsc};
use tracing::debug;
use tsc_model::{ChatMessage, ChatTarget, Presence};
use tsclientlib::ClientId;
use voelin_audio::AudioSettings;
use voelin_model::{ChatMessage, ChatTarget, Presence};
use crate::audio::{self, AudioHandle, AudioIn};
use crate::audio::{self, AudioEvent, AudioHandle, AudioIn};
use crate::gateway::{self, GatewayCmd, GatewayEvent};
use crate::query::{self, QueryCmd, QueryEvent};
use crate::route::{ChatRoute, Dedup, route_chat};
@@ -24,9 +26,10 @@ impl SessionHandle {
id: SessionId,
events: broadcast::Sender<Event>,
frames: broadcast::Sender<StreamFrame>,
audio_settings: AudioSettings,
) -> Self {
let (tx, rx) = mpsc::unbounded_channel();
tokio::spawn(Session::new(id, events, frames).run(rx));
tokio::spawn(Session::new(id, events, frames, audio_settings).run(rx));
Self { tx }
}
@@ -42,7 +45,7 @@ enum SourceEvent {
Gateway(u64, GatewayEvent),
Query(u64, QueryEvent),
AudioOut(u64, tsproto_packets::packets::OutPacket),
AudioError(String),
Audio(u64, AudioEvent),
}
struct Session {
@@ -58,6 +61,7 @@ struct Session {
query: Option<(u64, mpsc::UnboundedSender<QueryCmd>)>,
query_presence: Option<Presence>,
audio: Option<AudioHandle>,
audio_settings: AudioSettings,
/// Streams of the voice connection (TeamSpeak 6 only).
streams: Option<StreamHandle>,
stream_peer: PeerConfig,
@@ -75,6 +79,7 @@ impl Session {
id: SessionId,
events: broadcast::Sender<Event>,
frames: broadcast::Sender<StreamFrame>,
audio_settings: AudioSettings,
) -> Self {
let (sources_tx, sources_rx) = mpsc::unbounded_channel();
Self {
@@ -90,6 +95,7 @@ impl Session {
query: None,
query_presence: None,
audio: None,
audio_settings,
streams: None,
stream_peer: PeerConfig::default(),
frames,
@@ -160,12 +166,13 @@ impl Session {
self.stream_peer = options.stream_peer.clone();
let (cmd_tx, cmd_rx) = mpsc::unbounded_channel();
let (ev_tx, ev_rx) = mpsc::unbounded_channel();
self.audio = None;
if options.audio {
let (out_tx, out_rx) = mpsc::unbounded_channel();
let (err_tx, err_rx) = mpsc::unbounded_channel();
self.audio = Some(audio::spawn(out_tx, err_tx, false));
let (audio_tx, audio_rx) = mpsc::unbounded_channel();
self.audio = Some(audio::spawn(out_tx, audio_tx, self.audio_settings.clone()));
self.forward(out_rx, move |p| SourceEvent::AudioOut(generation, p));
self.forward(err_rx, SourceEvent::AudioError);
self.forward(audio_rx, move |e| SourceEvent::Audio(generation, e));
}
tokio::spawn(voice::run(*options, cmd_rx, ev_tx));
self.forward(ev_rx, move |e| SourceEvent::Voice(generation, e));
@@ -264,6 +271,29 @@ impl Session {
}
self.emit_state();
}
Command::SetAudioSettings(settings) => {
self.audio_settings = (*settings).clone();
if let Some(a) = &self.audio {
a.send(AudioIn::Settings(settings));
}
}
// Without audio there is nothing to adjust; the UI sends volumes
// again after connecting.
Command::SetClientVolume { client, volume, .. } => {
if let Some(a) = &self.audio {
a.send(AudioIn::ClientVolume { client: ClientId(client), volume });
}
}
Command::SetClientMuted { client, muted, .. } => {
if let Some(a) = &self.audio {
a.send(AudioIn::ClientMuted { client: ClientId(client), muted });
}
}
Command::SetStreamVolume { stream_id, volume, .. } => {
if let Some(a) = &self.audio {
a.send(AudioIn::StreamVolume { stream: stream_id, volume });
}
}
Command::StartStream { setup, auto_accept, .. } => {
self.stream_input(StreamInput::Start { setup, auto_accept });
}
@@ -287,7 +317,7 @@ impl Session {
Command::RequestStreamKeyframe { stream_id, .. } => {
self.stream_input(StreamInput::RequestKeyframe { stream_id });
}
Command::CloseSession { .. } => {}
Command::CloseSession { .. } | Command::TestMicrophone { .. } => {}
}
}
@@ -389,7 +419,12 @@ impl Session {
let _ = tx.send(VoiceCmd::Audio(packet));
}
}
SourceEvent::AudioError(message) => self.error(message),
SourceEvent::Audio(g, event) if self.is_current(Source::Voice, g) => match event {
AudioEvent::Error(message) => self.error(message),
AudioEvent::Level { db, sending } => {
self.emit(Event::InputLevel { session: Some(self.id), level_db: db, sending })
}
},
_ => debug!("event from a replaced source ignored"),
}
}
@@ -398,6 +433,7 @@ impl Session {
match e {
VoiceEvent::Connected { name, flavor, own_client } => {
self.state.voice = VoiceState::Connected;
self.state.own_client = Some(own_client);
self.emit_state();
let capabilities = flavor.capabilities();
if capabilities.streams
@@ -410,12 +446,19 @@ impl Session {
voice.clone(),
self.events.clone(),
self.frames.clone(),
self.audio.clone(),
));
}
self.emit(Event::ServerInfo { session: self.id, name, flavor, capabilities });
self.reopen_relayed_chats();
}
VoiceEvent::Presence(p) => {
// Client ids are reused: forget the volumes of those who left.
if let (Some(a), Some(old)) = (&self.audio, &self.voice_presence) {
for id in old.clients.keys().filter(|id| !p.clients.contains_key(id)) {
a.send(AudioIn::ClientLeft(ClientId(*id)));
}
}
if let Some(s) = &self.streams {
let clients: BTreeMap<_, _> =
p.clients.values().map(|c| (c.id, c.streaming)).collect();
@@ -459,6 +502,7 @@ impl Session {
self.audio = None;
self.state.voice = VoiceState::Disconnected;
self.state.own_channel = None;
self.state.own_client = None;
self.emit_state();
if let Some(reason) = reason {
self.error(format!("voice: {reason}"));
@@ -1,5 +1,5 @@
//! TeamSpeak 6 streams of a session: a task that runs the stream sessions
//! ([`tsc_stream::Streams`]) of the voice connection.
//! ([`voelin_stream::Streams`]) of the voice connection.
//!
//! The voice task forwards stream notifications here and sends the resulting
//! commands. Only started for TeamSpeak 6 servers.
@@ -11,17 +11,18 @@ use std::sync::atomic::{AtomicBool, Ordering};
use tokio::sync::{broadcast, mpsc};
use tracing::debug;
pub use tsc_stream::{
use tsclientlib::ClientId;
pub use voelin_stream::{
Codec, EncodedFrame, EndReason, FrameSource, Frequency, LeaveReason, MediaFrame, MediaKind,
MediaTime, PeerConfig, StreamInfo, StreamKind, StreamSetup, SyntheticSource, VideoCodec,
ViewerInfo, ViewerState,
};
use tsc_stream::{
use voelin_stream::{
Output, Request, StreamEvent, StreamNotification, StreamerEvent, StreamerOptions, Streams,
WatchEvent,
};
use tsclientlib::ClientId;
use crate::audio::{AudioHandle, AudioIn};
use crate::voice::VoiceCmd;
use crate::{Event, SessionId};
@@ -138,6 +139,7 @@ impl StreamHandle {
voice: mpsc::UnboundedSender<VoiceCmd>,
events: broadcast::Sender<Event>,
frames: broadcast::Sender<StreamFrame>,
audio: Option<AudioHandle>,
) -> Self {
let (tx, rx) = mpsc::unbounded_channel();
let task = StreamTask {
@@ -146,6 +148,7 @@ impl StreamHandle {
voice,
events,
frames,
audio,
tx: tx.clone(),
sink: None,
clients: BTreeMap::new(),
@@ -165,6 +168,8 @@ struct StreamTask {
voice: mpsc::UnboundedSender<VoiceCmd>,
events: broadcast::Sender<Event>,
frames: broadcast::Sender<StreamFrame>,
/// Where the audio of watched streams plays, if the session has audio.
audio: Option<AudioHandle>,
/// For the sinks handed out.
tx: mpsc::UnboundedSender<StreamInput>,
/// The sink of our live stream.
@@ -299,8 +304,20 @@ impl StreamTask {
let state = match event {
WatchEvent::Accepted => WatchState::Connecting,
WatchEvent::Connected => WatchState::Connected,
WatchEvent::Ended(reason) => WatchState::Ended(reason),
WatchEvent::Ended(reason) => {
if let Some(audio) = &self.audio {
audio.send(AudioIn::StreamEnded(id.clone()));
}
WatchState::Ended(reason)
}
WatchEvent::Frame(frame) => {
if let (MediaKind::Audio, Some(audio)) = (frame.kind, &self.audio) {
audio.send(AudioIn::StreamAudio {
stream: id.clone(),
time: frame.time.rebase(Frequency::FORTY_EIGHT_KHZ).numer(),
data: frame.data.clone(),
});
}
let _ = self.frames.send(StreamFrame { session, stream_id: id, frame });
return;
}
@@ -322,6 +339,9 @@ impl StreamTask {
}
for watched in self.streams.watching() {
let stream_id = watched.id().to_owned();
if let Some(audio) = &self.audio {
audio.send(AudioIn::StreamEnded(stream_id.clone()));
}
self.emit(Event::WatchState { session, stream_id, state: WatchState::Ended(ended()) });
}
if self.streams.directory().iter().next().is_some() {
@@ -335,7 +355,7 @@ mod tests {
use std::time::{Duration, Instant};
use tokio::time::timeout;
use tsc_stream::{FrameSource, SyntheticSource};
use voelin_stream::{FrameSource, SyntheticSource};
use super::*;
@@ -416,13 +436,18 @@ mod tests {
.expect("timed out")
}
/// Two stream tasks (sessions 1 and 2) whose commands go through a fake server.
#[tokio::test(flavor = "multi_thread")]
async fn stream_tasks_through_fake_server() {
let (events, mut rx) = broadcast::channel(4096);
let (frames, mut frames_rx) = broadcast::channel(4096);
type Handles = Arc<Vec<StreamHandle>>;
/// Two stream tasks (sessions 1 and 2) whose commands go through a fake
/// server; `audio` is the viewer's audio thread.
fn pair(
audio: Option<AudioHandle>,
) -> (Handles, broadcast::Receiver<Event>, broadcast::Receiver<StreamFrame>) {
let (events, rx) = broadcast::channel(4096);
let (frames, frames_rx) = broadcast::channel(4096);
let mut voices = Vec::new();
let mut handles = Vec::new();
let mut audio = audio;
for (i, clid) in CLIENTS.into_iter().enumerate() {
let (voice, voice_rx) = mpsc::unbounded_channel();
let config = PeerConfig::loopback();
@@ -434,6 +459,7 @@ mod tests {
voice,
events.clone(),
frames.clone(),
if session == 2 { audio.take() } else { None },
));
voices.push(voice_rx);
}
@@ -452,12 +478,20 @@ mod tests {
}
});
}
(handles, rx, frames_rx)
}
/// Session 1 streams (auto-accepting), session 2 watches; returns the sink
/// once the viewer is connected.
async fn live_and_watching(
handles: &Handles,
rx: &mut broadcast::Receiver<Event>,
) -> StreamSink {
let setup = StreamSetup { name: "t".into(), ..Default::default() };
handles[0].send(StreamInput::Start { setup, auto_accept: true });
// Live for the streamer and listed for the viewer, in either order.
let (mut sink, mut listed) = (None, false);
wait(&mut rx, |e| {
wait(rx, |e| {
match e {
Event::StreamState { session: 1, state: StreamState::Live { sink: s, .. } } => {
sink = Some(s);
@@ -468,13 +502,21 @@ mod tests {
(sink.is_some() && listed).then_some(())
})
.await;
let sink = sink.unwrap();
handles[1].send(StreamInput::Watch { stream_id: "s-1".into() });
wait(&mut rx, |e| match e {
wait(rx, |e| match e {
Event::WatchState { session: 2, state: WatchState::Connected, .. } => Some(()),
_ => None,
})
.await;
sink.unwrap()
}
#[tokio::test(flavor = "multi_thread")]
async fn stream_tasks_through_fake_server() {
// The viewer's audio thread.
let (audio, audio_rx) = AudioHandle::channel();
let (handles, mut rx, mut frames_rx) = pair(Some(audio));
let sink = live_and_watching(&handles, &mut rx).await;
// Frames from the sink reach the viewer's frame bus.
let feeder = tokio::spawn({
@@ -518,6 +560,20 @@ mod tests {
assert!(!sink.is_live());
feeder.await.unwrap();
// Stream audio went to the viewer's audio thread, in 20 ms steps,
// and the ended stream was forgotten there.
let received: Vec<AudioIn> = audio_rx.try_iter().collect();
let times: Vec<u64> = received
.iter()
.filter_map(|m| match m {
AudioIn::StreamAudio { stream, time, .. } if stream == "s-1" => Some(*time),
_ => None,
})
.collect();
assert!(times.len() >= 10, "{} audio frames", times.len());
assert!(times.windows(2).all(|w| w[1] > w[0] && (w[1] - w[0]) % 960 == 0), "{times:?}");
assert!(matches!(received.last(), Some(AudioIn::StreamEnded(id)) if id == "s-1"));
// Errors surface as events.
handles[1].send(StreamInput::Leave { stream_id: "s-1".into() });
wait(&mut rx, |e| match e {
@@ -527,4 +583,77 @@ mod tests {
.await;
handles[1].send(StreamInput::Shutdown("bye".into()));
}
/// The whole path: test pattern → VP8 → stream task → str0m peers on
/// loopback → the viewer's frame bus → decoder. The pictures show the
/// moving rectangle.
#[cfg(feature = "media-desktop")]
#[tokio::test(flavor = "multi_thread")]
async fn test_pattern_through_stream_tasks() {
use std::sync::mpsc as std_mpsc;
use voelin_media::capture::SourceId;
use voelin_media::{Codec, Codecs};
use crate::media::{Streamer, StreamerConfig, VideoPipeline, rectangle_span};
let (handles, mut rx, mut frames_rx) = pair(None);
let sink = live_and_watching(&handles, &mut rx).await;
let codecs = Arc::new(Codecs::new());
let config = StreamerConfig {
source: SourceId::Synthetic,
synthetic_size: (320, 240),
bitrate_kbps: 1500,
..StreamerConfig::default()
};
let streamer = Streamer::start(&codecs, config).await.unwrap();
streamer.attach(Arc::new(sink.clone()));
let (tx, pictures) = std_mpsc::channel();
let pipeline = VideoPipeline::new(
codecs,
move |picture| {
let _ = tx.send(picture);
},
{
let handles = handles.clone();
move || handles[1].send(StreamInput::RequestKeyframe { stream_id: "s-1".into() })
},
);
let input = pipeline.input();
let forward = tokio::spawn(async move {
while let Ok(f) = frames_rx.recv().await {
input.push(f.frame);
}
});
let spans = tokio::task::spawn_blocking(move || {
let mut spans = Vec::new();
while spans.len() < 15 {
let picture = pictures.recv_timeout(Duration::from_secs(10)).expect("no picture");
assert_eq!((picture.width, picture.height), (320, 240));
spans.push(rectangle_span(&picture));
}
spans
})
.await
.unwrap();
for (a, b) in &spans {
assert!((60..=68).contains(&(b - a + 1)), "{spans:?}");
}
assert_ne!(spans.first(), spans.last(), "the rectangle moves");
let stats = pipeline.stats();
assert_eq!(stats.codec, Some(Codec::Vp8));
assert!(stats.error.is_none(), "{stats:?}");
let sent = streamer.stats();
assert!(sent.video_frames >= 15 && sent.audio_frames > 0, "{sent:?}");
handles[0].send(StreamInput::Stop);
wait(&mut rx, |e| match e {
Event::WatchState { session: 2, state: WatchState::Ended(_), .. } => Some(()),
_ => None,
})
.await;
forward.abort();
drop(streamer);
}
}
@@ -7,10 +7,6 @@ use futures::prelude::*;
use tokio::sync::mpsc;
use tokio::time::{Instant, timeout};
use tracing::{info, warn};
use tsc_model::{
ChannelId, ChannelInfo, ChatMessage, ChatTarget, ClientInfo, Presence, ServerFlavor,
};
use tsc_stream::{PeerConfig, Request, StreamNotification};
use tsclientlib::data;
use tsclientlib::events::Event as BookEvent;
use tsclientlib::prelude::*;
@@ -19,6 +15,10 @@ use tsclientlib::{
StreamItem, Version,
};
use tsproto_packets::packets::{AudioData, InAudioBuf, OutPacket};
use voelin_model::{
ChannelId, ChannelInfo, ChatMessage, ChatTarget, ClientInfo, Presence, ServerFlavor,
};
use voelin_stream::{PeerConfig, Request, StreamNotification};
#[derive(Clone, Debug)]
pub struct VoiceOptions {
@@ -1,15 +1,15 @@
//! Engine against the development servers (dev/docker-compose.yml).
//! Runs only with `TSC_LIVE=1`; `scripts/it-smoke.sh` sets it.
//! Runs only with `VOELIN_LIVE=1`; `scripts/it-smoke.sh` sets it.
use std::time::Duration;
use tokio::sync::broadcast::Receiver;
use tokio::time::{Instant, timeout_at};
use tsc_core::{Command, Engine, Event, ObserveState, Source, VoiceOptions, VoiceState};
use tsc_model::ChatTarget;
use voelin_core::{Command, Engine, Event, ObserveState, Source, VoiceOptions, VoiceState};
use voelin_model::ChatTarget;
fn live() -> bool {
std::env::var("TSC_LIVE").is_ok_and(|v| v == "1")
std::env::var("VOELIN_LIVE").is_ok_and(|v| v == "1")
}
/// Wait for an event matching `f`, failing after 20 s.
@@ -29,7 +29,7 @@ async fn wait_for(
}
}
async fn engine_roundtrip(voice_addr: &str, query: tsc_query::Connect) {
async fn engine_roundtrip(voice_addr: &str, query: voelin_query::Connect) {
let engine = Engine::start();
let mut events = engine.subscribe();
let nick = format!("engine-{}", std::process::id() % 10_000);
@@ -93,15 +93,15 @@ async fn engine_roundtrip(voice_addr: &str, query: tsc_query::Connect) {
tokio::time::sleep(Duration::from_millis(500)).await;
}
fn query(transport: tsc_query::Transport, addr: &str) -> tsc_query::Connect {
tsc_query::Connect {
fn query(transport: voelin_query::Transport, addr: &str) -> voelin_query::Connect {
voelin_query::Connect {
transport,
addr: addr.into(),
user: "serveradmin".into(),
secret: Some("tsc-dev-admin".into()),
secret: Some("voelin-dev-admin".into()),
server_port: Some(9987),
server_id: None,
line: tsc_query::LineOptions { rate_limit: None, ..Default::default() },
line: voelin_query::LineOptions { rate_limit: None, ..Default::default() },
}
}
@@ -110,7 +110,8 @@ async fn ts6_engine() {
if !live() {
return;
}
engine_roundtrip("127.0.0.1:9988", query(tsc_query::Transport::Ssh, "127.0.0.1:10022")).await;
engine_roundtrip("127.0.0.1:9988", query(voelin_query::Transport::Ssh, "127.0.0.1:10022"))
.await;
}
#[tokio::test(flavor = "multi_thread")]
@@ -118,5 +119,6 @@ async fn ts3_engine() {
if !live() {
return;
}
engine_roundtrip("127.0.0.1:9987", query(tsc_query::Transport::Raw, "127.0.0.1:10011")).await;
engine_roundtrip("127.0.0.1:9987", query(voelin_query::Transport::Raw, "127.0.0.1:10011"))
.await;
}
+175
View File
@@ -0,0 +1,175 @@
//! The media pipeline through the engine and the TeamSpeak 6 development
//! server (dev/docker-compose.yml): one session streams the test pattern
//! (VP8 + Opus), another decodes it. Runs only with `VOELIN_LIVE=1`.
#![cfg(feature = "media-desktop")]
use std::sync::Arc;
use std::sync::mpsc as std_mpsc;
use std::time::Duration;
use tokio::sync::broadcast::Receiver;
use tokio::time::timeout;
use voelin_core::media::voelin_media::capture::SourceId;
use voelin_core::media::voelin_media::capture::synthetic::RECT_COLOR;
use voelin_core::media::voelin_media::{Codec, Codecs, convert};
use voelin_core::media::{Streamer, StreamerConfig, Viewer, peer_config, stream_codec};
use voelin_core::stream::{PeerConfig, StreamSetup};
use voelin_core::{Command, Engine, Event, StreamState, VoiceOptions, VoiceState, WatchState};
fn live() -> bool {
std::env::var("VOELIN_LIVE").is_ok_and(|v| v == "1")
}
/// Wait for an event matching `f`, failing after 20 s.
async fn wait_for<T>(
rx: &mut Receiver<Event>,
what: &str,
mut f: impl FnMut(&Event) -> Option<T>,
) -> T {
timeout(Duration::from_secs(20), async {
loop {
match rx.recv().await {
Ok(e) => {
if let Some(t) = f(&e) {
return t;
}
if let Event::Error { session, message } = e {
eprintln!("engine error (session {session}): {message}");
}
}
Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => {}
Err(e) => panic!("event bus closed: {e}"),
}
}
})
.await
.unwrap_or_else(|_| panic!("timed out waiting for {what}"))
}
async fn connect(
engine: &Engine,
events: &mut Receiver<Event>,
session: u64,
nick: &str,
peer: PeerConfig,
) {
let mut options = VoiceOptions::new("127.0.0.1:9988", nick);
options.stream_peer = peer;
engine.send(Command::ConnectVoice { session, options: Box::new(options) });
wait_for(events, "voice connected", |e| match e {
Event::State { session: s, state }
if *s == session
&& state.voice == VoiceState::Connected
&& state.own_channel.is_some() =>
{
Some(())
}
_ => None,
})
.await;
}
#[tokio::test(flavor = "multi_thread")]
async fn ts6_test_pattern_decoded() {
if !live() {
eprintln!("skipped: set VOELIN_LIVE=1 with the dev servers running");
return;
}
let engine = Engine::start();
let mut events = engine.subscribe();
let codecs = Arc::new(Codecs::new());
let peer = peer_config(&codecs, PeerConfig::loopback());
let codec = stream_codec(&codecs, &peer).expect("an encoder");
assert_eq!(codec, Codec::Vp8);
let tag = std::process::id() % 10_000;
connect(&engine, &mut events, 1, &format!("m-streamer-{tag}"), peer.clone()).await;
connect(&engine, &mut events, 2, &format!("m-viewer-{tag}"), peer).await;
// Capture first (as the app does: the portal may ask), then go live.
let config = StreamerConfig {
source: SourceId::Synthetic,
synthetic_size: (640, 360),
bitrate_kbps: 2000,
codec,
..StreamerConfig::default()
};
let streamer = Streamer::start(&codecs, config).await.unwrap();
let setup = StreamSetup { name: format!("media {tag}"), ..Default::default() };
engine.send(Command::StartStream { session: 1, setup, auto_accept: true });
// The viewer's list may update before the streamer goes live.
let mut live = None;
let mut listed = Vec::new();
let (id, sink) = wait_for(&mut events, "stream live and in the viewer's list", |e| {
match e {
Event::StreamState { session: 1, state: StreamState::Live { id, sink } } => {
live = Some((id.clone(), sink.clone()));
}
Event::StreamState { session: 1, state: StreamState::Ended(reason) } => {
panic!("stream ended: {reason:?}")
}
Event::StreamsChanged { session: 2, streams } => {
listed = streams.iter().map(|s| s.id.clone()).collect();
}
_ => {}
}
live.clone().filter(|(id, _)| listed.contains(id))
})
.await;
streamer.attach(Arc::new(sink));
let (tx, pictures) = std_mpsc::channel();
let viewer = Viewer::start(&engine, 2, &id, codecs, move |picture| {
let _ = tx.send(picture);
});
engine.send(Command::WatchStream { session: 2, stream_id: id.clone() });
wait_for(&mut events, "watching", |e| match e {
Event::WatchState { session: 2, stream_id, state: WatchState::Connected }
if *stream_id == id =>
{
Some(())
}
Event::WatchState { session: 2, state: WatchState::Ended(reason), .. } => {
panic!("watching ended: {reason:?}")
}
_ => None,
})
.await;
// 60 decoded pictures (two seconds), each with the rectangle in the
// middle row, about a fifth of the width.
let widths = tokio::task::spawn_blocking(move || {
let mut widths = Vec::new();
while widths.len() < 60 {
let picture = pictures.recv_timeout(Duration::from_secs(10)).expect("no picture");
assert_eq!((picture.width, picture.height), (640, 360));
let rgba = convert::to_rgba_vec(&picture).unwrap();
let row = &rgba[(picture.height / 2 * picture.width * 4) as usize..]
[..(picture.width * 4) as usize];
let rect = row
.chunks_exact(4)
.filter(|p| p.iter().zip(RECT_COLOR).all(|(a, b)| a.abs_diff(b) <= 24))
.count();
widths.push(rect);
}
widths
})
.await
.unwrap();
assert!(widths.iter().all(|w| (120..=136).contains(w)), "{widths:?}");
let stats = viewer.stats();
assert!(stats.error.is_none(), "{stats:?}");
eprintln!("decoded {stats:?}, sent {:?}", streamer.stats());
engine.send(Command::StopStream { session: 1 });
wait_for(&mut events, "stream ended", |e| match e {
Event::StreamState { session: 1, state: StreamState::Ended(_) } => Some(()),
_ => None,
})
.await;
drop(viewer);
drop(streamer);
engine.send(Command::CloseSession { session: 1 });
engine.send(Command::CloseSession { session: 2 });
tokio::time::sleep(Duration::from_millis(500)).await;
}
@@ -1,19 +1,19 @@
//! Streams through the engine against the development servers
//! (dev/docker-compose.yml): one session streams synthetic frames, another
//! watches. Runs only with `TSC_LIVE=1`.
//! watches. Runs only with `VOELIN_LIVE=1`.
use std::time::{Duration, Instant};
use tokio::sync::broadcast::Receiver;
use tokio::time::timeout;
use tsc_core::stream::{
use voelin_core::stream::{
EndReason, FrameSource, LeaveReason, MediaKind, PeerConfig, StreamSetup, SyntheticSource,
ViewerState,
};
use tsc_core::{Command, Engine, Event, StreamState, VoiceOptions, VoiceState, WatchState};
use voelin_core::{Command, Engine, Event, StreamState, VoiceOptions, VoiceState, WatchState};
fn live() -> bool {
std::env::var("TSC_LIVE").is_ok_and(|v| v == "1")
std::env::var("VOELIN_LIVE").is_ok_and(|v| v == "1")
}
/// Wait for an event matching `f`, failing after 20 s.
@@ -90,7 +90,7 @@ async fn connect(
#[tokio::test(flavor = "multi_thread")]
async fn ts6_stream_between_sessions() {
if !live() {
eprintln!("skipped: set TSC_LIVE=1 with the dev servers running");
eprintln!("skipped: set VOELIN_LIVE=1 with the dev servers running");
return;
}
let engine = Engine::start();
@@ -220,9 +220,9 @@ async fn ts6_stream_between_sessions() {
},
)
.await;
assert!(!sink.send(tsc_core::stream::EncodedFrame {
assert!(!sink.send(voelin_core::stream::EncodedFrame {
kind: MediaKind::Audio,
time: tsc_core::stream::MediaTime::from_90khz(0),
time: voelin_core::stream::MediaTime::from_90khz(0),
data: vec![0].into(),
}));
feeder.await.unwrap();
@@ -1,5 +1,5 @@
[package]
name = "tsc-gateway-proto"
name = "voelin-gateway-proto"
version = "0.1.0"
description = "Wire protocol and identity-challenge authentication of the tsgw gateway."
edition.workspace = true
@@ -15,7 +15,7 @@ serde_json = "1"
sha1 = { package = "sha-1", version = "0.10" }
sha2 = "0.10"
thiserror = "2"
tsc-model = { path = "../tsc-model" }
voelin-model = { path = "../voelin-model" }
tsproto-types = { path = "../proto/tsproto-types" }
[lints]
File renamed without changes.
File renamed without changes.
@@ -1,7 +1,7 @@
//! Messages in both directions.
use serde::{Deserialize, Serialize};
use tsc_model::{ChatMessage, ChatTarget, PresenceDelta, PresenceSnapshot};
use voelin_model::{ChatMessage, ChatTarget, PresenceDelta, PresenceSnapshot};
/// Every frame: `{"v":1,"id":7,"type":"send_chat","data":{...}}`.
///
@@ -1,5 +1,5 @@
[package]
name = "tsc-gateway"
name = "voelin-gateway"
version = "0.1.0"
description = "tsgw: companion gateway giving app users invisible presence and channel chat over ServerQuery."
edition.workspace = true
@@ -28,10 +28,10 @@ tokio = { version = "1.53.1", features = ["full"] }
toml = "1.1.6"
tracing = "0.1.44"
tracing-subscriber = { version = "0.3.23", features = ["env-filter"] }
tsc-gateway-proto = { path = "../tsc-gateway-proto" }
tsc-model = { path = "../tsc-model" }
tsc-observer = { path = "../tsc-observer" }
tsc-query = { path = "../tsc-query" }
voelin-gateway-proto = { path = "../voelin-gateway-proto" }
voelin-model = { path = "../voelin-model" }
voelin-observer = { path = "../voelin-observer" }
voelin-query = { path = "../voelin-query" }
[lints]
workspace = true
@@ -1,10 +1,10 @@
# Build: docker build -f crates/tsc-gateway/Dockerfile -t tsgw .
# Build: docker build -f crates/voelin-gateway/Dockerfile -t tsgw .
# Run: docker run -v ./tsgw.toml:/etc/tsgw/tsgw.toml -p 7788:7788 tsgw
FROM rust:1.94-bookworm AS build
WORKDIR /src
RUN apt-get update && apt-get install -y --no-install-recommends cmake libasound2-dev && rm -rf /var/lib/apt/lists/*
COPY . .
RUN cargo build --release --locked -p tsc-gateway && cp target/release/tsgw /tsgw
RUN cargo build --release --locked -p voelin-gateway && cp target/release/tsgw /tsgw
FROM gcr.io/distroless/cc-debian12:nonroot
COPY --from=build /tsgw /usr/local/bin/tsgw
@@ -5,7 +5,7 @@ use std::path::{Path, PathBuf};
use anyhow::{Context, Result, bail};
use serde::Deserialize;
use tsc_query::Transport;
use voelin_query::Transport;
#[derive(Clone, Debug, Deserialize)]
#[serde(deny_unknown_fields)]
@@ -199,19 +199,19 @@ impl Config {
.unwrap_or_else(|| format!("tsgw@{}", self.query.addr))
}
pub fn query_connect(&self) -> tsc_query::Connect {
tsc_query::Connect {
pub fn query_connect(&self) -> voelin_query::Connect {
voelin_query::Connect {
transport: self.query.transport,
addr: self.query.addr.clone(),
user: self.query.user.clone(),
secret: self.query.password.clone(),
server_port: Some(self.server.voice_port),
server_id: None,
line: tsc_query::LineOptions {
line: voelin_query::LineOptions {
rate_limit: if self.query.allowlisted {
None
} else {
tsc_query::LineOptions::default().rate_limit
voelin_query::LineOptions::default().rate_limit
},
..Default::default()
},
@@ -4,7 +4,7 @@ use std::path::Path;
use std::sync::Mutex;
use rusqlite::{Connection, OptionalExtension, params};
use tsc_model::{ChatMessage, ChatTarget};
use voelin_model::{ChatMessage, ChatTarget};
pub struct Db(Mutex<Connection>);
@@ -11,10 +11,12 @@ use rand::RngExt;
use sha2::{Digest, Sha256};
use tokio::sync::broadcast;
use tracing::{info, warn};
use tsc_gateway_proto::{ErrorCode, UniqueIds, identity_level, verify_auth};
use tsc_model::{ChannelId, ChatMessage, ChatTarget, Presence, ServerFlavor, relay_text};
use tsc_observer::{Observer, ObserverConfig, ObserverEvent, RelayConfig, RelayEvent, RelayPool};
use tsc_query::{Command, QueryClient};
use voelin_gateway_proto::{ErrorCode, UniqueIds, identity_level, verify_auth};
use voelin_model::{ChannelId, ChatMessage, ChatTarget, Presence, ServerFlavor, relay_text};
use voelin_observer::{
Observer, ObserverConfig, ObserverEvent, RelayConfig, RelayEvent, RelayPool,
};
use voelin_query::{Command, QueryClient};
use crate::config::Config;
use crate::db::{Db, TokenInfo};
@@ -53,8 +55,8 @@ impl Denied {
}
}
impl From<tsc_query::Error> for Denied {
fn from(e: tsc_query::Error) -> Self {
impl From<voelin_query::Error> for Denied {
fn from(e: voelin_query::Error) -> Self {
Denied::new(ErrorCode::Unavailable, e.to_string())
}
}
@@ -414,7 +416,7 @@ impl Hub {
return Err(Denied::new(ErrorCode::Forbidden, "no permission for server chat"));
}
let msg = relay_text(&self.config.relay.format, &user.nickname, text);
for part in tsc_model::split_message(&msg, 1024) {
for part in voelin_model::split_message(&msg, 1024) {
self.lookup
.send(
&Command::new("sendtextmessage").arg("targetmode", 3).arg("msg", part),
@@ -2,7 +2,7 @@
//!
//! Gives app users invisible presence (who is in which channel) and channel
//! chat without joining voice, through ServerQuery. See
//! docs/gateway-admin.md and the protocol in `tsc-gateway-proto`.
//! docs/gateway-admin.md and the protocol in `voelin-gateway-proto`.
mod config;
mod db;
@@ -55,7 +55,7 @@ async fn main() -> Result<()> {
async fn ws(State(hub): State<Arc<Hub>>, upgrade: WebSocketUpgrade) -> impl IntoResponse {
upgrade
.protocols([tsc_gateway_proto::SUBPROTOCOL])
.protocols([voelin_gateway_proto::SUBPROTOCOL])
.on_upgrade(move |socket| session::run(hub, socket))
}
@@ -9,7 +9,7 @@ use std::collections::HashMap;
use std::sync::Mutex;
use std::time::{Duration, Instant};
use tsc_query::{Command, QueryClient, Row};
use voelin_query::{Command, QueryClient, Row};
const CACHE_TTL: Duration = Duration::from_secs(60);
@@ -81,7 +81,7 @@ pub struct PermIds {
}
impl PermIds {
pub async fn load(client: &QueryClient) -> tsc_query::Result<Self> {
pub async fn load(client: &QueryClient) -> voelin_query::Result<Self> {
let names = [
"i_channel_join_power",
"i_channel_needed_join_power",
@@ -93,10 +93,9 @@ impl PermIds {
let mut ids = [0u32; 6];
for (i, name) in names.iter().enumerate() {
let rows = client.send(&Command::new("permidgetbyname").arg("permsid", name)).await?;
ids[i] = rows
.first()
.and_then(|r| r.parse("permid"))
.ok_or_else(|| tsc_query::Error::Protocol(format!("unknown permission {name}")))?;
ids[i] = rows.first().and_then(|r| r.parse("permid")).ok_or_else(|| {
voelin_query::Error::Protocol(format!("unknown permission {name}"))
})?;
}
Ok(Self {
join_power: ids[0],
@@ -148,7 +147,7 @@ impl PermResolver {
client: &QueryClient,
cldbid: u64,
cid: u64,
) -> tsc_query::Result<Vec<Entry>> {
) -> voelin_query::Result<Vec<Entry>> {
if let Some((at, entries)) = self.cache.lock().unwrap().get(&(cldbid, cid))
&& at.elapsed() < CACHE_TTL
{
@@ -9,9 +9,9 @@ use base64::prelude::*;
use rand::RngExt;
use tokio::sync::broadcast::error::RecvError;
use tracing::{debug, info};
use tsc_gateway_proto::{ClientMsg, Envelope, ErrorCode, HistoryEntry, ServerMsg};
use tsc_model::{ChatTarget, Presence};
use tsc_observer::ObserverEvent;
use voelin_gateway_proto::{ClientMsg, Envelope, ErrorCode, HistoryEntry, ServerMsg};
use voelin_model::{ChatTarget, Presence};
use voelin_observer::ObserverEvent;
use crate::hub::{Denied, Hub, User};
@@ -97,7 +97,7 @@ pub async fn run(hub: Arc<Hub>, mut socket: WebSocket) {
}
async fn send(socket: &mut WebSocket, id: Option<u64>, msg: ServerMsg) -> Result<(), axum::Error> {
let env = Envelope { v: tsc_gateway_proto::VERSION, id, msg };
let env = Envelope { v: voelin_gateway_proto::VERSION, id, msg };
let text = serde_json::to_string(&env).expect("messages serialize");
socket.send(Message::Text(text.into())).await
}
File renamed without changes.
@@ -1,5 +1,5 @@
[package]
name = "tsc-media"
name = "voelin-media"
version = "0.1.0"
description = "Video frames, pixel conversion, video codecs (VP8/VP9, H.264, AV1) and screen / system-audio capture for streams."
edition.workspace = true
@@ -47,6 +47,9 @@ pipewire = { version = "0.10.1", optional = true }
rustix = { version = "1.1.5", features = ["fs"], optional = true }
x11rb = { version = "0.13.2", features = ["randr", "shm", "xfixes"], optional = true }
[target.'cfg(target_os = "android")'.dependencies]
ndk = { version = "0.9.0", default-features = false, features = ["media", "api-level-29"] }
[target.'cfg(windows)'.dependencies]
wasapi = "0.24.0"
windows-capture = "2.0.1"
+274
View File
@@ -0,0 +1,274 @@
//! Capture driven by platform code outside this crate.
//!
//! On Android, screen and system-audio capture need a MediaProjection, which
//! only the app's Java/Kotlin side can obtain (it asks the user and runs a
//! foreground service). The app registers a [`ScreenProvider`] and an
//! [`AudioProvider`] at start; [`super::default_screen_capture`] and
//! [`super::default_audio_capture`] then hand out capture backends that
//! forward to them, so stream code needs no platform knowledge.
//!
//! A provider receives the [`FrameSender`] of the capture and pushes frames
//! into it from any thread; dropping the sender ends the capture for the
//! consumer (e.g. when the user stops sharing from the system UI).
use std::sync::{Arc, Mutex, PoisonError};
use crate::Result;
use crate::capture::{
AudioCapture, BoxFuture, CaptureOptions, CaptureSource, ScreenCapture, SourceId,
};
use crate::frame::{AudioBuffer, VideoFrame};
use crate::queue::{FrameReceiver, FrameSender, frame_channel};
/// Platform code that captures the screen.
pub trait ScreenProvider: Send + Sync {
/// Short name for logs (`"mediaprojection"`).
fn name(&self) -> &'static str;
/// What can be captured (Android: the whole screen, as one
/// [`SourceId::Portal`] entry since the system dialog picks).
fn sources(&self) -> Vec<CaptureSource>;
/// Start delivering frames into `frames`. Resolves once frames flow, or
/// with an error such as [`crate::Error::Cancelled`] when the user
/// declined.
fn start(
&self,
source: &SourceId,
options: &CaptureOptions,
frames: FrameSender<VideoFrame>,
) -> BoxFuture<'static, Result<()>>;
fn stop(&self);
}
/// Platform code that captures what the device plays (48 kHz `f32`).
pub trait AudioProvider: Send + Sync {
fn name(&self) -> &'static str;
/// Start delivering audio into `buffers`.
fn start(&self, buffers: FrameSender<AudioBuffer>) -> Result<()>;
fn stop(&self);
}
type Slot<T> = Mutex<Option<Arc<T>>>;
static SCREEN: Slot<dyn ScreenProvider> = Mutex::new(None);
static AUDIO: Slot<dyn AudioProvider> = Mutex::new(None);
fn get<T: ?Sized>(slot: &Slot<T>) -> Option<Arc<T>> {
slot.lock().unwrap_or_else(PoisonError::into_inner).clone()
}
/// Make [`super::default_screen_capture`] use `provider` (`None` restores
/// the built-in backends).
pub fn set_screen_provider(provider: Option<Arc<dyn ScreenProvider>>) {
*SCREEN.lock().unwrap_or_else(PoisonError::into_inner) = provider;
}
/// Make [`super::default_audio_capture`] use `provider`.
pub fn set_audio_provider(provider: Option<Arc<dyn AudioProvider>>) {
*AUDIO.lock().unwrap_or_else(PoisonError::into_inner) = provider;
}
pub fn screen_provider() -> Option<Arc<dyn ScreenProvider>> {
get(&SCREEN)
}
pub fn audio_provider() -> Option<Arc<dyn AudioProvider>> {
get(&AUDIO)
}
/// A [`ScreenCapture`] backed by a [`ScreenProvider`].
pub struct ExternalScreenCapture {
provider: Arc<dyn ScreenProvider>,
running: bool,
}
impl ExternalScreenCapture {
pub fn new(provider: Arc<dyn ScreenProvider>) -> Self {
Self { provider, running: false }
}
}
impl ScreenCapture for ExternalScreenCapture {
fn backend(&self) -> &'static str {
self.provider.name()
}
fn sources(&mut self) -> Result<Vec<CaptureSource>> {
Ok(self.provider.sources())
}
fn start(
&mut self,
source: &SourceId,
options: &CaptureOptions,
) -> BoxFuture<'_, Result<FrameReceiver<VideoFrame>>> {
self.stop();
let (tx, rx) = frame_channel(options.queue);
let started = self.provider.start(source, options, tx);
self.running = true;
Box::pin(async move {
started.await?;
Ok(rx)
})
}
fn stop(&mut self) {
if std::mem::take(&mut self.running) {
self.provider.stop();
}
}
}
impl Drop for ExternalScreenCapture {
fn drop(&mut self) {
self.stop();
}
}
/// An [`AudioCapture`] backed by an [`AudioProvider`].
pub struct ExternalAudioCapture {
provider: Arc<dyn AudioProvider>,
running: bool,
}
impl ExternalAudioCapture {
pub fn new(provider: Arc<dyn AudioProvider>) -> Self {
Self { provider, running: false }
}
}
impl AudioCapture for ExternalAudioCapture {
fn backend(&self) -> &'static str {
self.provider.name()
}
fn start(&mut self) -> Result<FrameReceiver<AudioBuffer>> {
self.stop();
// About a second of 10 ms buffers.
let (tx, rx) = frame_channel(100);
self.provider.start(tx)?;
self.running = true;
Ok(rx)
}
fn stop(&mut self) {
if std::mem::take(&mut self.running) {
self.provider.stop();
}
}
}
impl Drop for ExternalAudioCapture {
fn drop(&mut self) {
self.stop();
}
}
#[cfg(test)]
mod tests {
use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::Duration;
use super::*;
use crate::Error;
/// Sends one frame per start, or refuses.
#[derive(Default)]
struct Fake {
refuse: bool,
stops: AtomicUsize,
sender: Mutex<Option<FrameSender<VideoFrame>>>,
}
impl ScreenProvider for Fake {
fn name(&self) -> &'static str {
"fake"
}
fn sources(&self) -> Vec<CaptureSource> {
vec![CaptureSource {
id: SourceId::Portal,
name: "Screen".into(),
width: 0,
height: 0,
primary: true,
}]
}
fn start(
&self,
_: &SourceId,
_: &CaptureOptions,
frames: FrameSender<VideoFrame>,
) -> BoxFuture<'static, Result<()>> {
if self.refuse {
return Box::pin(async { Err(Error::Cancelled) });
}
frames.send(VideoFrame::black_i420(4, 4));
*self.sender.lock().unwrap() = Some(frames);
Box::pin(async { Ok(()) })
}
fn stop(&self) {
self.stops.fetch_add(1, Ordering::Relaxed);
self.sender.lock().unwrap().take();
}
}
#[tokio::test]
async fn frames_flow_until_the_provider_drops_the_sender() {
let fake = Arc::new(Fake::default());
let mut capture = ExternalScreenCapture::new(fake.clone());
assert_eq!(capture.backend(), "fake");
assert_eq!(capture.sources().unwrap().len(), 1);
let mut rx = capture.start(&SourceId::Portal, &CaptureOptions::default()).await.unwrap();
assert_eq!(rx.recv().await.unwrap().width, 4);
// The system stopped the projection.
fake.sender.lock().unwrap().take();
assert!(rx.recv_timeout(Duration::from_millis(10)).is_none());
assert!(rx.is_closed());
drop(capture);
assert_eq!(fake.stops.load(Ordering::Relaxed), 1);
}
#[tokio::test]
async fn refusal_is_an_error_and_stop_is_not_repeated() {
let fake = Arc::new(Fake { refuse: true, ..Fake::default() });
let mut capture = ExternalScreenCapture::new(fake.clone());
let result = capture.start(&SourceId::Portal, &CaptureOptions::default()).await;
assert!(matches!(result, Err(Error::Cancelled)));
capture.stop();
capture.stop();
assert_eq!(fake.stops.load(Ordering::Relaxed), 1);
}
#[test]
fn registered_provider_is_the_default() {
struct Silent;
impl AudioProvider for Silent {
fn name(&self) -> &'static str {
"silent"
}
fn start(&self, buffers: FrameSender<AudioBuffer>) -> Result<()> {
buffers.send(AudioBuffer {
samples: vec![0.0; 960],
channels: 2,
timestamp: Duration::ZERO,
});
Ok(())
}
fn stop(&self) {}
}
set_audio_provider(Some(Arc::new(Silent)));
let mut capture = crate::capture::default_audio_capture().unwrap();
assert_eq!(capture.backend(), "silent");
let mut rx = capture.start().unwrap();
assert_eq!(rx.try_recv().unwrap().frames(), 480);
set_audio_provider(None);
assert!(audio_provider().is_none());
}
}
@@ -9,6 +9,7 @@
//! | `x11` (Linux, feature `x11`) | MIT-SHM / GetImage, XFixes cursor | |
//! | `portal` / `pipewire_audio` (Linux, feature `pipewire`) | ScreenCast portal + PipeWire | default sink monitor |
//! | `windows` | Windows Graphics Capture | WASAPI process loopback |
//! | [`external`] | platform code (Android MediaProjection) | same |
use std::future::Future;
use std::pin::Pin;
@@ -21,6 +22,7 @@ use crate::frame::{AudioBuffer, VideoFrame};
use crate::queue::FrameReceiver;
use crate::{Error, Result};
pub mod external;
#[cfg(all(target_os = "linux", feature = "pipewire"))]
pub mod pipewire_audio;
#[cfg(all(target_os = "linux", feature = "pipewire"))]
@@ -106,9 +108,13 @@ pub trait AudioCapture: Send {
fn stop(&mut self);
}
/// The screen capture backend for this session: the ScreenCast portal on
/// The screen capture backend for this session: a registered
/// [`external::ScreenProvider`] (Android), else the ScreenCast portal on
/// Wayland, X11 otherwise on Linux, Windows Graphics Capture on Windows.
pub fn default_screen_capture() -> Result<Box<dyn ScreenCapture>> {
if let Some(provider) = external::screen_provider() {
return Ok(Box::new(external::ExternalScreenCapture::new(provider)));
}
#[cfg(target_os = "linux")]
{
let wayland = std::env::var_os("WAYLAND_DISPLAY").is_some()
@@ -132,8 +138,12 @@ pub fn default_screen_capture() -> Result<Box<dyn ScreenCapture>> {
})
}
/// The system-audio backend: PipeWire on Linux, WASAPI loopback on Windows.
/// The system-audio backend: a registered [`external::AudioProvider`]
/// (Android), else PipeWire on Linux, WASAPI loopback on Windows.
pub fn default_audio_capture() -> Result<Box<dyn AudioCapture>> {
if let Some(provider) = external::audio_provider() {
return Ok(Box::new(external::ExternalAudioCapture::new(provider)));
}
#[cfg(all(target_os = "linux", feature = "pipewire"))]
return Ok(Box::new(pipewire_audio::PipeWireAudioCapture::new()));
#[cfg(windows)]
@@ -26,7 +26,7 @@ use crate::{Error, Result};
const BACKEND: &str = "pipewire";
/// Name of our capture node in PipeWire.
pub const NODE_NAME: &str = "tsc-system-audio";
pub const NODE_NAME: &str = "voelin-system-audio";
/// Captures the default sink's monitor through PipeWire.
#[derive(Default)]
@@ -49,7 +49,7 @@ impl AudioCapture for PipeWireAudioCapture {
self.stop();
// Half a second at PipeWire's usual 10-20 ms quantum.
let (tx, rx) = frame_channel(50);
let thread = PwThread::spawn("tsc-pipewire-audio", None, move |core, mainloop| {
let thread = PwThread::spawn("voelin-pipewire-audio", None, move |core, mainloop| {
audio_stream(core, mainloop, tx)
})
.map_err(|reason| Error::CaptureUnavailable { backend: BACKEND, reason })?;
@@ -159,10 +159,11 @@ impl ScreenCapture for PortalCapture {
let (fd, node) = self.open(&options).await?;
let (tx, rx) = frame_channel(options.queue);
let fps = options.fps.max(1);
let thread = PwThread::spawn("tsc-portal-capture", Some(fd), move |core, mainloop| {
video_stream(core, mainloop, node, fps, tx)
})
.map_err(|e| Error::Capture { backend: BACKEND, message: e })?;
let thread =
PwThread::spawn("voelin-portal-capture", Some(fd), move |core, mainloop| {
video_stream(core, mainloop, node, fps, tx)
})
.map_err(|e| Error::Capture { backend: BACKEND, message: e })?;
self.thread = Some(thread);
Ok(rx)
})
@@ -210,7 +211,7 @@ fn video_stream(
*pw::keys::MEDIA_CATEGORY => "Capture",
*pw::keys::MEDIA_ROLE => "Screen",
};
let stream = pw::stream::StreamRc::new(core.clone(), "tsc-screen-capture", props)
let stream = pw::stream::StreamRc::new(core.clone(), "voelin-screen-capture", props)
.map_err(|e| format!("PipeWire stream: {e}"))?;
let state = VideoState {
tx,
File renamed without changes.
@@ -124,7 +124,7 @@ impl ScreenCapture for SyntheticScreen {
let (tx, rx) = frame_channel(options.queue);
let pattern = SyntheticScreen::new(self.width, self.height);
let fps = options.fps;
self.worker = Some(Worker::spawn("tsc-synthetic-video", move |stop| {
self.worker = Some(Worker::spawn("voelin-synthetic-video", move |stop| {
let mut ticker = Ticker::new(fps);
let mut n = 0;
while tx.send(pattern.frame(n, fps)) && ticker.wait(&stop) {
@@ -179,7 +179,7 @@ impl AudioCapture for SineSource {
// Half a second of audio before the oldest is dropped.
let (tx, rx) = frame_channel(50);
let tone = SineSource::new(self.frequency, self.amplitude);
self.worker = Some(Worker::spawn("tsc-synthetic-audio", move |stop| {
self.worker = Some(Worker::spawn("voelin-synthetic-audio", move |stop| {
let mut ticker = Ticker::new(100);
let mut n = 0;
while tx.send(tone.buffer(n)) && ticker.wait(&stop) {
@@ -207,7 +207,7 @@ impl AudioCapture for WasapiLoopback {
self.stop();
let (tx, rx) = frame_channel(50);
let (init_tx, init_rx) = std::sync::mpsc::channel();
self.worker = Some(Worker::spawn("tsc-wasapi-loopback", move |stop| {
self.worker = Some(Worker::spawn("voelin-wasapi-loopback", move |stop| {
if let Err(e) = loopback(&tx, &stop, &init_tx) {
// After a successful start the receiver just sees the end.
let _ = init_tx.send(Err(e.clone()));
Loaded 100 of 224 files, more files were not shown because too many files have changed in this diff. Show more