Compare commits
236
Commits
No files matched your search
@@ -2,7 +2,7 @@
|
||||
name: mao-designer
|
||||
description: Produces designs and acceptance criteria for a task, and handles escalations from mao-implementer after 3 failed attempts. Use before delegating non-trivial work and whenever an implementation is stuck.
|
||||
model: opus
|
||||
effort: max
|
||||
effort: xhigh
|
||||
---
|
||||
|
||||
You are **mao-designer**, the design and escalation role of the Voelin
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
name: mao-opus-reviewer
|
||||
description: Final, fresh and independent review of substantive code changes for correctness, architecture and unresolved risks. Reports concrete defects; does not fix code. Use after the sonnet review, in a new agent, never in the design agent's conversation.
|
||||
model: opus
|
||||
effort: max
|
||||
effort: xhigh
|
||||
tools: Read, Grep, Glob, Bash
|
||||
---
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
{
|
||||
"$schema": "https://json.schemastore.org/claude-code-settings.json",
|
||||
"model": "fable",
|
||||
"effortLevel": "xhigh"
|
||||
"effortLevel": "xhigh",
|
||||
"maxEffortLevel": "xhigh"
|
||||
}
|
||||
@@ -2,6 +2,10 @@
|
||||
# the sources only. Builds keep target/ in cache mounts, never in the context.
|
||||
.git
|
||||
.claude
|
||||
# The per-developer .cargo/config.toml (docs/building.md, a [patch] to a sibling
|
||||
# VoelinProtocol checkout): never part of a build. Only the root one; the
|
||||
# committed third_party/dimpl/.cargo stays.
|
||||
.cargo
|
||||
target
|
||||
dist
|
||||
fuzz/target
|
||||
|
||||
@@ -1,9 +1,118 @@
|
||||
name: Linux checks
|
||||
description: Shared Linux validation for Gitea CI and release packaging.
|
||||
inputs:
|
||||
protocol-deploy-key:
|
||||
description: >
|
||||
Private half of the read-only deploy key registered on the private
|
||||
Voelin/VoelinProtocol repository (the repository secret
|
||||
VOELIN_PROTOCOL_DEPLOY_KEY, passed in by the workflow: secrets are not
|
||||
visible inside a composite action). The action fails when it is empty.
|
||||
required: true
|
||||
runs:
|
||||
using: composite
|
||||
steps:
|
||||
# The workspace depends on the private VoelinProtocol repository over SSH
|
||||
# (docs/ci.md, "VoelinProtocol access"). First, so that a missing key fails
|
||||
# in seconds and before anything runs cargo.
|
||||
- name: Install the VoelinProtocol deploy key
|
||||
# The key reaches this step through the environment only: never in the
|
||||
# script text, never echoed, no `set -x`.
|
||||
env:
|
||||
PROTOCOL_DEPLOY_KEY: ${{ inputs.protocol-deploy-key }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
umask 077
|
||||
if [[ -z "${PROTOCOL_DEPLOY_KEY//[[:space:]]/}" ]]; then
|
||||
echo "::error::The VoelinProtocol deploy key is empty. Set the repository secret VOELIN_PROTOCOL_DEPLOY_KEY to the private key of the read-only deploy key on Voelin/VoelinProtocol (docs/ci.md, VoelinProtocol access). Pull requests from forks get no secrets." >&2
|
||||
exit 1
|
||||
fi
|
||||
for tool in ssh ssh-keygen; do
|
||||
command -v "$tool" > /dev/null || {
|
||||
echo "::error::The job image needs the OpenSSH client: $tool is missing." >&2
|
||||
exit 1
|
||||
}
|
||||
done
|
||||
ssh_dir="$HOME/.ssh"
|
||||
key_file="$ssh_dir/voelin_protocol"
|
||||
mkdir -p "$ssh_dir"
|
||||
chmod 700 "$ssh_dir"
|
||||
|
||||
# Whatever the secret store did to the line ends and the final newline,
|
||||
# OpenSSH needs LF lines, the BEGIN line first and a newline at the end.
|
||||
printf '%s\n' "$PROTOCOL_DEPLOY_KEY" | tr -d '\r' | sed '/^[[:space:]]*$/d' > "$key_file"
|
||||
unset PROTOCOL_DEPLOY_KEY
|
||||
chmod 600 "$key_file"
|
||||
if ! public=$(ssh-keygen -y -f "$key_file" < /dev/null); then
|
||||
rm -f "$key_file"
|
||||
echo "::error::VOELIN_PROTOCOL_DEPLOY_KEY is not an unencrypted OpenSSH or PEM private key." >&2
|
||||
exit 1
|
||||
fi
|
||||
# The fingerprint of the public half, to compare with the deploy key in
|
||||
# the VoelinProtocol settings.
|
||||
printf 'Deploy key installed: %s\n' "$(ssh-keygen -lf - <<< "$public")"
|
||||
|
||||
# The reviewed host key from the repository, never one fetched now.
|
||||
known_hosts="$ssh_dir/known_hosts"
|
||||
touch "$known_hosts"
|
||||
chmod 600 "$known_hosts"
|
||||
[[ -s "${GITHUB_WORKSPACE:-.}/.gitea/known_hosts" ]] || {
|
||||
echo "::error::.gitea/known_hosts is missing from the checkout." >&2
|
||||
exit 1
|
||||
}
|
||||
while IFS= read -r line; do
|
||||
case "$line" in '' | '#'*) continue ;; esac
|
||||
grep -qxF -- "$line" "$known_hosts" || printf '%s\n' "$line" >> "$known_hosts"
|
||||
done < "${GITHUB_WORKSPACE:-.}/.gitea/known_hosts"
|
||||
|
||||
# Use this key, and only this one, for the Gitea server; fail rather than
|
||||
# ask when its host key is unknown or changed. The block goes first: ssh
|
||||
# takes the first value it finds for each option.
|
||||
config="$ssh_dir/config"
|
||||
marker="# VoelinProtocol deploy key (.gitea/actions/checks)"
|
||||
touch "$config"
|
||||
if ! grep -qxF -- "$marker" "$config"; then
|
||||
{
|
||||
cat << EOF
|
||||
$marker
|
||||
Host git.faumaray.com
|
||||
User gitea
|
||||
IdentityFile $key_file
|
||||
IdentitiesOnly yes
|
||||
UserKnownHostsFile $known_hosts
|
||||
StrictHostKeyChecking yes
|
||||
BatchMode yes
|
||||
ConnectTimeout 30
|
||||
|
||||
EOF
|
||||
cat "$config"
|
||||
} > "$config.new"
|
||||
mv "$config.new" "$config"
|
||||
fi
|
||||
chmod 600 "$config"
|
||||
|
||||
# Cargo's built-in git client (libgit2) cannot use IdentityFile; the
|
||||
# system git runs ssh, which reads the config above. `-F` names it
|
||||
# outright: ssh looks for ~/.ssh in the passwd entry's home directory, not
|
||||
# in $HOME, and a job image may set the two apart.
|
||||
{
|
||||
echo "CARGO_NET_GIT_FETCH_WITH_CLI=true"
|
||||
echo "GIT_SSH_COMMAND=ssh -F '$config'"
|
||||
} >> "$GITHUB_ENV"
|
||||
shell: bash
|
||||
- uses: ./.github/actions/system-deps
|
||||
- name: Check read access to VoelinProtocol
|
||||
# The first thing cargo does, with the same git and ssh configuration, so
|
||||
# that a wrong key or a changed host key fails here with a clear message
|
||||
# and not minutes later inside a cargo command.
|
||||
run: |
|
||||
set -euo pipefail
|
||||
if ! GIT_TERMINAL_PROMPT=0 timeout 120 git ls-remote --exit-code \
|
||||
ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git HEAD > /dev/null; then
|
||||
echo "::error::git cannot read Voelin/VoelinProtocol over SSH with the deploy key. 'Permission denied (publickey)' above: the key is not registered on that repository (or is not the one in VOELIN_PROTOCOL_DEPLOY_KEY). 'Host key verification failed': .gitea/known_hosts no longer matches the server (docs/ci.md, VoelinProtocol access)." >&2
|
||||
exit 1
|
||||
fi
|
||||
echo "Voelin/VoelinProtocol is readable with the deploy key."
|
||||
shell: bash
|
||||
- name: Install pinned Rust toolchain
|
||||
run: |
|
||||
set -euo pipefail
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
# SSH host key of git.faumaray.com (Gitea's built-in SSH server, which offers an
|
||||
# RSA host key only). Fingerprint SHA256:fugBYnqAnqmTLsGpafVgQF9gPQzJqps7uHvs48blg2A,
|
||||
# recorded on 2026-10-24 with `ssh-keyscan -t rsa git.faumaray.com`.
|
||||
#
|
||||
# Committed, never fetched while a job runs, so a CI or release build trusts the
|
||||
# key reviewed here and not whatever answers on the network at that moment.
|
||||
# Read by .gitea/actions/checks (appended to ~/.ssh/known_hosts) and COPYed by
|
||||
# docker/*.Dockerfile and crates/voelin-gateway/Dockerfile. How to re-check it
|
||||
# and how to rotate it: docs/ci.md, "VoelinProtocol access".
|
||||
git.faumaray.com ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACAQCzZEz9JLrzk6oLiloSbueAN28vYL58Y/dTHBgRuBMMib9IJ1aDJShhr3kwC9sfOT0AzK0uwcMAqCAIkwJwttde8dIg0Mee0cmB/1JkoqFF4X3MUGD1r3nk8SSZNhIiPqo16hDF9Hf3FkovztIlBVntkyP9Iy9hYfP818Tiq3yRXROGdHjR7IfY4jR2QGfGrd/RtvPGExVqusxidy141240A8aRAwMFUqFdEvmXWjizrtCUqcrL/k1GEh0yJzbCdNOVUI6OuWd8tPluSBvmmeoNpKnCSl4Mkg36HObbOyrsme0asZqjcj0od65WYWApMPN0pUqhNu2CP83Nfor2VFwkdPRwe7cAZ0OD/8wyT6Hz5q1wWgf82y4tYDoDRYsd8JU86eebkJ07T5nCrEeC4Sj+qT4S5xv/kECAhxyP4QGnunORnY2fYsdNGzpPvbMN7gHe9UcIcQdOIgV3wrR1qpMVNcd8AEC2A3TRv/jzMCHSjmGGpgiy1Db2CZAjp5+PcjNmjvoPNN0NiA9X4rIVSeTfflWnDRmeNRJeZa73StjpU17EcAf97COUQPGWJQDgpJqINSpYU50fuaLBfzKnIRuiHjKQmyKe/zgRSmulnYFYM3AJfn8Ykg2VvkUQGvCt1+fqYiUa1iVFuwPP3ZigYF1mOZRpPnos5kaNmlB01q2sZw==
|
||||
@@ -20,6 +20,11 @@ on:
|
||||
|
||||
env:
|
||||
CARGO_TERM_COLOR: always
|
||||
# Cargo fetches the private VoelinProtocol dependency with the system git and
|
||||
# ssh (docs/ci.md, "VoelinProtocol access"). The checks action exports this
|
||||
# too; set here as well, it does not depend on the runner handing a composite
|
||||
# action's GITHUB_ENV on to the later steps.
|
||||
CARGO_NET_GIT_FETCH_WITH_CLI: "true"
|
||||
|
||||
jobs:
|
||||
linux:
|
||||
@@ -32,3 +37,8 @@ jobs:
|
||||
steps:
|
||||
- uses: https://github.com/actions/checkout@v4
|
||||
- uses: ./.gitea/actions/checks
|
||||
with:
|
||||
# A repository secret is not visible inside the composite action, so
|
||||
# it is passed in. Pull requests from forks get no secrets: the
|
||||
# action then fails at once with a message that says so.
|
||||
protocol-deploy-key: ${{ secrets.VOELIN_PROTOCOL_DEPLOY_KEY }}
|
||||
@@ -32,6 +32,38 @@ jobs:
|
||||
docker info >/dev/null
|
||||
# Remove only output owned by this workflow in its checkout.
|
||||
rm -rf dist
|
||||
# The workspace depends on the private VoelinProtocol repository over SSH
|
||||
# (docs/ci.md, "VoelinProtocol access"). The Docker builds fetch it with
|
||||
# this agent (`docker build --ssh default`): the key lives in the agent's
|
||||
# memory, never on disk and never in an image layer. Stopped by the last
|
||||
# step; the lifetime below ends the key anyway if the runner dies first.
|
||||
- name: Start ssh-agent with the VoelinProtocol deploy key
|
||||
env:
|
||||
PROTOCOL_DEPLOY_KEY: ${{ secrets.VOELIN_PROTOCOL_DEPLOY_KEY }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
if [[ -z "${PROTOCOL_DEPLOY_KEY//[[:space:]]/}" ]]; then
|
||||
echo "::error::The repository secret VOELIN_PROTOCOL_DEPLOY_KEY is missing or empty. It holds the private key of the read-only deploy key on Voelin/VoelinProtocol (docs/ci.md, VoelinProtocol access)." >&2
|
||||
exit 1
|
||||
fi
|
||||
for tool in ssh-agent ssh-add; do
|
||||
command -v "$tool" > /dev/null || { echo "::error::The runner needs the OpenSSH client: $tool is missing." >&2; exit 1; }
|
||||
done
|
||||
eval "$(ssh-agent -s -t 32400)" > /dev/null
|
||||
started=
|
||||
trap '[[ -n "$started" ]] || ssh-agent -k > /dev/null' EXIT
|
||||
# LF lines and one final newline, whatever the secret store did.
|
||||
printf '%s\n' "$PROTOCOL_DEPLOY_KEY" | tr -d '\r' | sed '/^[[:space:]]*$/d' | ssh-add -q -
|
||||
unset PROTOCOL_DEPLOY_KEY
|
||||
# The fingerprint of the public half, to compare with the deploy key.
|
||||
ssh-add -l
|
||||
{
|
||||
echo "SSH_AUTH_SOCK=$SSH_AUTH_SOCK"
|
||||
echo "SSH_AGENT_PID=$SSH_AGENT_PID"
|
||||
# Only an agent this job started is stopped at the end.
|
||||
echo "VOELIN_AGENT_STARTED=1"
|
||||
} >> "$GITHUB_ENV"
|
||||
started=1
|
||||
- name: Linux packages
|
||||
run: scripts/docker-build.sh linux --progress=plain
|
||||
- name: Windows packages (MinGW)
|
||||
@@ -77,7 +109,7 @@ jobs:
|
||||
set -euo pipefail
|
||||
version=$(sed -n 's/^version = "\(.*\)"$/\1/p' crates/voelin-gateway/Cargo.toml | head -n 1)
|
||||
test -n "$version"
|
||||
docker build -f crates/voelin-gateway/Dockerfile -t "tsgw:$version" -t tsgw:latest .
|
||||
DOCKER_BUILDKIT=1 docker build --ssh default -f crates/voelin-gateway/Dockerfile -t "tsgw:$version" -t tsgw:latest .
|
||||
mkdir -p dist/gateway
|
||||
docker save "tsgw:$version" tsgw:latest | gzip > dist/gateway/tsgw-image.tar.gz
|
||||
- name: Collect packages and checksums
|
||||
@@ -104,3 +136,9 @@ jobs:
|
||||
# Gitea refuses secret names starting with GITEA_ or GITHUB_.
|
||||
GITEA_RELEASE_TOKEN: ${{ secrets.RELEASE_TOKEN }}
|
||||
run: scripts/gitea-release.sh dist/release
|
||||
- name: Stop the ssh-agent
|
||||
if: always()
|
||||
run: |
|
||||
if [[ -n "${VOELIN_AGENT_STARTED:-}" && -n "${SSH_AGENT_PID:-}" ]]; then
|
||||
ssh-agent -k > /dev/null || true
|
||||
fi
|
||||
@@ -16,7 +16,8 @@ runs:
|
||||
- name: apt packages
|
||||
if: runner.os == 'Linux'
|
||||
shell: bash
|
||||
# ALSA (audio devices), fontconfig + xkbcommon (UI), libvpx + dav1d
|
||||
# ALSA (audio devices), fontconfig + xkbcommon (UI), xkbcommon-x11 + xcb (linked
|
||||
# by the GPUI front end), libvpx + dav1d
|
||||
# (video codecs), PipeWire + SPA (screen and audio capture), libclang
|
||||
# (bindgen), Xvfb (X11 tests).
|
||||
run: |
|
||||
@@ -27,7 +28,7 @@ runs:
|
||||
"${sudo[@]}" apt-get update
|
||||
"${sudo[@]}" apt-get install -y --no-install-recommends \
|
||||
build-essential ca-certificates cmake curl git jq pkg-config python3 \
|
||||
libasound2-dev libfontconfig1-dev libxkbcommon-dev \
|
||||
libasound2-dev libfontconfig1-dev libxkbcommon-dev libxkbcommon-x11-dev libxcb1-dev \
|
||||
libvpx-dev libdav1d-dev libpipewire-0.3-dev libspa-0.2-dev libclang-dev \
|
||||
xvfb xauth
|
||||
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
/target/
|
||||
/dev/.state/
|
||||
/dist/
|
||||
/.cargo/
|
||||
# agent scratch of a worktree (the MAO policy in CLAUDE.md)
|
||||
/.scratch/
|
||||
@@ -8,6 +8,24 @@ User-visible changes of the apps and the `tsgw` gateway. The format follows
|
||||
|
||||
### Added
|
||||
|
||||
- `voelin-gpui`, the GPUI front end of the desktop app, in its first form: a
|
||||
window titled Voelin with one line of the app's state in it (the version,
|
||||
the voice connections that are up, the engine events handled, the seconds
|
||||
up), fed by the same engine and the same view models as the Slint app
|
||||
(`cargo run -p voelin-gpui --release`), in the Voelin theme: every colour,
|
||||
radius, size and type token of the Slint app's `theme.slint`, light and dark
|
||||
(a test reads the Slint file and fails when the two differ), written into
|
||||
the widget library's theme too, in Inter, with the Slint app's Lucide icons.
|
||||
`system` mode follows the window's appearance. `VOELIN_OPEN=swatch` shows
|
||||
every token, a few widgets and the icons (`VOELIN_DEV_THEME`,
|
||||
`VOELIN_FONT_SCALE`, `VOELIN_WINDOW_SIZE`; screenshots with
|
||||
`scripts/gpui-shot.sh`, docs/ui/). `VOELIN_METER=1` logs what it costs once a
|
||||
second: the CPU by group of threads, the memory and its own counters. A
|
||||
window that cannot open (no driver, no display server) ends the app with
|
||||
the reason and exit status 1. The Slint app (`voelin`) is unchanged and
|
||||
stays the app; both run on one engine until the GPUI one reaches parity
|
||||
(docs/ui.md). It needs Vulkan or OpenGL at run time (Mesa's lavapipe renders
|
||||
in software); no package ships it yet.
|
||||
- Log files: each run logs to `<state>/voelin/logs/voelin.log`, the previous
|
||||
four runs are kept; `VOELIN_LOG` sets what is logged. Settings → Advanced
|
||||
opens the folder.
|
||||
@@ -69,6 +87,43 @@ User-visible changes of the apps and the `tsgw` gateway. The format follows
|
||||
|
||||
### Changed
|
||||
|
||||
- The desktop portals (screen capture and camera through PipeWire, the push to
|
||||
talk shortcut, the file chooser and the proxy settings) talk to D-Bus through
|
||||
ashpd on `async-io` instead of `tokio`. Nothing changes on screen; the GPUI
|
||||
front end, which is being built, enables ashpd's `async-io` and ashpd cannot
|
||||
have both. Every D-Bus connection of the apps, the desktop notifications'
|
||||
included, now runs on an I/O thread of its own, whichever part of the app
|
||||
asks first.
|
||||
- The build needs Rust 1.95 (`rust-toolchain.toml` and the workspace's
|
||||
`rust-version`; 1.95.0 was used to check it), up from 1.94: the GPUI
|
||||
front end, which is being built, depends on a library that calls a function
|
||||
stable since 1.95. Nothing changes in the apps; the gateway's Docker image
|
||||
builds from `rust:1.95-bookworm`.
|
||||
- The key store now keeps the device key when signing out of an account,
|
||||
unbound, whether it was in use before the account or was made for it; "Forget
|
||||
this device's identity" is the only way a key is deleted. The identity store
|
||||
also reports a damaged TeamSpeak identity by the kind of damage and never
|
||||
repeats its key in an error. Nothing changes on screen yet: accounts and
|
||||
sign-in are later steps.
|
||||
- The view models, the app's state, the state change of every engine event and
|
||||
the decisions of the settings pages, the Stream Studio, the streams, the chat,
|
||||
the servers, the audio settings page, the friends and the development
|
||||
switches moved out of `voelin-ui` into a new crate, `voelin-ui-vm`, which
|
||||
depends on no UI toolkit (a second front end can use it); `voelin-ui`
|
||||
converts its plain rows into Slint's and keeps the window, the Bridge writes
|
||||
and the engine's tasks. The chat formatting reader and the
|
||||
Twemoji archive moved with them. Two things change on screen: the chat of
|
||||
a server that is gone takes the colour of its title instead of opaque
|
||||
black, and a cached avatar file cut after a valid header shows the
|
||||
initials instead of a broken picture. See docs/ui.md, "Two crates".
|
||||
- The identity store keeps identities of more than one kind (TeamSpeak, a Voelin
|
||||
key, the signed-in account) with the account each belongs to, as a
|
||||
`voelin-identity` key store, in two database migrations. Existing
|
||||
databases migrate on first start and every identity stays what it was (kind
|
||||
TeamSpeak, no account, same key, name, origin and default); nothing changes
|
||||
on screen yet. The build now fetches `voelin-identity` from the private
|
||||
VoelinProtocol repository, so a fresh checkout needs read access to it
|
||||
(see docs/building.md).
|
||||
- Selecting a server observes it through its gateway at once; the Observe
|
||||
button is gone. The server dialog asks only for the address, password,
|
||||
name and nickname: the gateway is found from the address.
|
||||
@@ -180,6 +235,9 @@ User-visible changes of the apps and the `tsgw` gateway. The format follows
|
||||
|
||||
### Fixed
|
||||
|
||||
- A deleted identity key no longer stays in the database file: SQLite overwrites
|
||||
what it deletes, and the log is truncated after a key is deleted (an identity
|
||||
you delete, a key a sign-out deletes).
|
||||
- Hover help in the Stream Studio (a source's error, the status details)
|
||||
shows each time and closes when the pointer leaves; it showed only once,
|
||||
and stayed open until a click.
|
||||
|
||||
@@ -8,6 +8,12 @@ org `Voelin`; the current plan lives in the approved plan file referenced in
|
||||
`cargo fmt` (hard tabs, `rustfmt.toml`) and `cargo clippy -D warnings` on the
|
||||
project's own crates (`scripts/own-crates.sh`) green.
|
||||
|
||||
Two front ends run on one engine until the second reaches parity:
|
||||
`crates/voelin-ui` (Slint, the `voelin` binary, the app today) and
|
||||
`crates/voelin-gpui` (GPUI on an exactly pinned `gpui-kit`, the `voelin-gpui`
|
||||
binary, under construction); `crates/voelin-ui-vm` holds what they share, the
|
||||
view models and the state, with no UI toolkit (`docs/ui.md`).
|
||||
|
||||
## Hosting: Gitea, not GitHub
|
||||
|
||||
- The source of truth is **https://git.faumaray.com** (Gitea). Pull requests,
|
||||
@@ -30,10 +36,10 @@ review, help) and does not delegate it again or spawn further orchestration.
|
||||
| Agent | Model / effort | Job |
|
||||
|---|---|---|
|
||||
| main session | (settings) | **Orchestrator**: decomposes work, delegates, tracks progress and attempt counts, resolves escalations, reports results. Delegates implementation, investigation, testing and review rather than doing them inline. |
|
||||
| `mao-designer` | opus / max | Designs, acceptance criteria, escalation handling |
|
||||
| `mao-designer` | opus / xhigh | Designs, acceptance criteria, escalation handling |
|
||||
| `mao-implementer` | sonnet / xhigh | Implements, runs checks, self-reviews; escalates after 3 failed attempts |
|
||||
| `mao-sonnet-reviewer` | sonnet / xhigh | Fresh, independent implementation review |
|
||||
| `mao-opus-reviewer` | opus / max | Fresh, final independent review of substantive code changes (correctness, architecture, unresolved risks) |
|
||||
| `mao-opus-reviewer` | opus / xhigh | Fresh, final independent review of substantive code changes (correctness, architecture, unresolved risks) |
|
||||
| `mao-helper` | haiku | Focused file searches, summaries, routine git operations within the user's authorization |
|
||||
|
||||
### Before delegating
|
||||
|
||||
Generated
+3761
-149
File diff suppressed because it is too large.
Load diff
+24
-3
@@ -15,14 +15,15 @@ members = [
|
||||
"crates/voelin-core",
|
||||
"crates/voelin-gateway",
|
||||
"crates/voelin-gateway-proto",
|
||||
"crates/voelin-gpui",
|
||||
"crates/voelin-media",
|
||||
"crates/voelin-model",
|
||||
"crates/voelin-observer",
|
||||
"crates/voelin-platform",
|
||||
"crates/voelin-query",
|
||||
"crates/voelin-store",
|
||||
"crates/voelin-stream",
|
||||
"crates/voelin-ui",
|
||||
"crates/voelin-ui-vm",
|
||||
"tools/voelinctl",
|
||||
]
|
||||
default-members = [
|
||||
@@ -36,23 +37,43 @@ default-members = [
|
||||
"crates/voelin-core",
|
||||
"crates/voelin-gateway",
|
||||
"crates/voelin-gateway-proto",
|
||||
"crates/voelin-model",
|
||||
"crates/voelin-gpui",
|
||||
"crates/voelin-observer",
|
||||
"crates/voelin-platform",
|
||||
"crates/voelin-query",
|
||||
"crates/voelin-store",
|
||||
"crates/voelin-stream",
|
||||
"crates/voelin-ui",
|
||||
"crates/voelin-ui-vm",
|
||||
"tools/voelinctl",
|
||||
]
|
||||
|
||||
[workspace.package]
|
||||
edition = "2024"
|
||||
rust-version = "1.94"
|
||||
rust-version = "1.95"
|
||||
license = "MIT OR Apache-2.0"
|
||||
repository = "https://github.com/Faumaray/Voelin"
|
||||
publish = false
|
||||
|
||||
[workspace.dependencies]
|
||||
# The protocol repository is private (VoelinProtocol). This is the SSH URL its
|
||||
# docs/development.md names, so that a per-developer .cargo/config.toml [patch]
|
||||
# can point it at a sibling checkout (docs/building.md, "Working with a sibling
|
||||
# VoelinProtocol checkout"). Pinned by commit until the protocol tags a release:
|
||||
# the three crates below are at one revision (main c5bb6b9: the account-bound
|
||||
# KeyStore whose sign-out keeps every device key and the release of a device key,
|
||||
# Phase 2 task 34; the account types of the session seam).
|
||||
voelin-identity = { git = "ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git", rev = "c5bb6b914bdab86eb36f6e32a1a5bc9ac4785562" }
|
||||
# The backend-neutral session seam (`voelin_proto::link`) and the v1 messages.
|
||||
voelin-proto = { git = "ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git", rev = "c5bb6b914bdab86eb36f6e32a1a5bc9ac4785562" }
|
||||
# The UI-facing domain model and the client's replica of v1 entities.
|
||||
voelin-model = { git = "ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git", rev = "c5bb6b914bdab86eb36f6e32a1a5bc9ac4785562" }
|
||||
# GPUI, gpui-component and their assets for the GPUI front end (voelin-gpui). Pre-1.0:
|
||||
# pinned exactly (it pins its `gpui-pre` snapshot exactly too), upgraded in commits of
|
||||
# their own after rebuilding spikes/gpui on the new release (docs/design/gpui-spikes.md,
|
||||
# "The version to pin").
|
||||
gpui-kit = "=0.8.1"
|
||||
|
||||
[workspace.lints.rust]
|
||||
# deny, not forbid: generated code (Slint) needs a local allow.
|
||||
unsafe_code = "deny"
|
||||
|
||||
@@ -28,7 +28,7 @@ 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/voelin-model`: server flavor detection (TS3 / TS6) and capabilities
|
||||
- `voelin-model` (from VoelinProtocol, a git dependency): domain 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)
|
||||
@@ -45,6 +45,14 @@ Done so far (milestones M0–M4 and the first part of M5 of [the plan](docs/arch
|
||||
(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. Desktop and phone layouts
|
||||
from one design system, dark and light themes, text size, emoji ([docs/ui.md](docs/ui.md))
|
||||
- `crates/voelin-ui-vm`: the view models and the app's state behind the UI, with no UI toolkit: engine state
|
||||
as plain rows and forms, chat formatting, the Twemoji archive, and what the settings pages and the
|
||||
Stream Studio decide; `voelin-ui` puts them on Slint windows ([docs/ui.md](docs/ui.md))
|
||||
- `crates/voelin-gpui` (`voelin-gpui`): the GPUI front end, under construction, on the same engine and
|
||||
view models as the Slint one, which stays the app until it reaches parity: a window with the engine's
|
||||
state in one line, the Voelin theme (every token of the Slint one's `theme.slint`, light and dark, in
|
||||
Inter with the same Lucide icons; `VOELIN_OPEN=swatch` shows them) and a cost meter (`VOELIN_METER=1`)
|
||||
([docs/ui.md](docs/ui.md), "The GPUI front end")
|
||||
- `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
|
||||
@@ -76,6 +84,8 @@ The UI (design system, desktop and phone layouts, emoji, how to add a screen) is
|
||||
```sh
|
||||
# Desktop app
|
||||
cargo run -p voelin-ui --bin voelin
|
||||
# The GPUI front end, under construction (Vulkan or OpenGL at run time)
|
||||
cargo run -p voelin-gpui --release
|
||||
|
||||
# Local servers (use REGISTRY=mirror.gcr.io if Docker Hub rate-limits you)
|
||||
docker compose -f dev/docker-compose.yml up -d
|
||||
|
||||
+3267
-50
File diff suppressed because it is too large.
Load diff
+9
-1
@@ -3,13 +3,21 @@
|
||||
|
||||
<!-- From about-assets.md, appended by scripts/notices.sh. -->
|
||||
|
||||
The user interface bundles these assets (in crates/voelin-ui):
|
||||
The user interface bundles these assets (in crates/voelin-ui, the Twemoji
|
||||
archive in crates/voelin-ui-vm):
|
||||
|
||||
- Inter (the UI font), Copyright (c) 2016 The Inter Project Authors, under
|
||||
the SIL Open Font License 1.1 (OFL-1.1; text below).
|
||||
- Lucide icons (lucide-static 1.48.0), Copyright (c) Lucide Icons and
|
||||
Contributors, under the ISC License; the icons derived from Feather are
|
||||
Copyright (c) 2013-present Cole Bemis, under the MIT License (texts below).
|
||||
- Lucide icons 1.43.0 (the 1,818 icons of the catalogue of gpui-kit-assets
|
||||
0.8.1, embedded in the GPUI front end, crates/voelin-gpui, behind the
|
||||
client's own set above), Copyright (c) Lucide Icons and Contributors, under
|
||||
the ISC License; the icons derived from Feather are Copyright (c) 2013-present
|
||||
Cole Bemis, under the MIT License (the same texts, below). The catalogue's
|
||||
12 other icons are the crate's own, under its Apache-2.0 licence (listed with
|
||||
the crates).
|
||||
- Twemoji 15.0 (the emoji images): Twemoji graphics by Twitter, Inc and other
|
||||
contributors, licensed under CC-BY 4.0
|
||||
(https://creativecommons.org/licenses/by/4.0/). The SVG files are packed
|
||||
|
||||
@@ -23,6 +23,10 @@ accepted = [
|
||||
"LicenseRef-Slint-Royalty-free-2.0",
|
||||
# libbz2-rs-sys (unpacks Cisco's OpenH264 download in voelin-media).
|
||||
"bzip2-1.0.6",
|
||||
# The GPUI front end: 0BSD (enum-iterator, enum-iterator-derive) and CC0-1.0
|
||||
# (notify 8, tiny-keccak); see deny.toml.
|
||||
"0BSD",
|
||||
"CC0-1.0",
|
||||
]
|
||||
|
||||
# What the apps ship on: the desktop app on Linux (x86_64, and aarch64 for
|
||||
|
||||
@@ -19,7 +19,7 @@ tokio = { version = "1.53.1", features = ["rt-multi-thread", "macros", "sync", "
|
||||
tracing = "0.1.44"
|
||||
voelin-core = { path = "../voelin-core" }
|
||||
# Channels and people for the voice notification.
|
||||
voelin-model = { path = "../voelin-model" }
|
||||
voelin-model = { workspace = true }
|
||||
|
||||
[target.'cfg(target_os = "android")'.dependencies]
|
||||
anyhow = "1.0.104"
|
||||
@@ -32,9 +32,5 @@ voelin-platform = { path = "../voelin-platform", default-features = false }
|
||||
voelin-store = { path = "../voelin-store" }
|
||||
voelin-ui = { path = "../voelin-ui" }
|
||||
|
||||
[dev-dependencies]
|
||||
# Client ids of stream viewers in the tests.
|
||||
tsclientlib = { path = "../proto/tsclientlib" }
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -194,7 +194,7 @@ fn connected(viewers: &[ViewerInfo]) -> usize {
|
||||
mod tests {
|
||||
use voelin_core::SessionState;
|
||||
use voelin_core::stream::EndReason;
|
||||
use voelin_model::{Capabilities, ChannelInfo, ClientInfo, ServerFlavor};
|
||||
use voelin_model::{Capabilities, ChannelInfo, ClientInfo};
|
||||
|
||||
use super::*;
|
||||
|
||||
@@ -244,7 +244,7 @@ mod tests {
|
||||
let info = Event::ServerInfo {
|
||||
session: 1,
|
||||
name: "Home".into(),
|
||||
flavor: ServerFlavor::Unknown(String::new()),
|
||||
backend: voelin_core::BackendInfo::default(),
|
||||
capabilities: Capabilities::default(),
|
||||
};
|
||||
assert_eq!(fg.update_at(&info, 6).voice, notice("Connecting…", "Home", false, 0));
|
||||
@@ -316,7 +316,7 @@ mod tests {
|
||||
};
|
||||
assert_eq!(fg.screen(), screen("Live in Chill Zone", "a server").flatten());
|
||||
let viewer = |client, state| ViewerInfo {
|
||||
client: tsclientlib::ClientId(client),
|
||||
client,
|
||||
state,
|
||||
message: String::new(),
|
||||
layer: None,
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
[package]
|
||||
name = "voelin-audio"
|
||||
version = "0.1.0"
|
||||
description = "Voice pipeline: Opus encoding, framing, resampling, jitter buffer/mixer and audio devices."
|
||||
description = "Voice pipeline: Opus encoding, framing, resampling, jitter buffer/mixer and audio devices, independent of the voice transport."
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
license.workspace = true
|
||||
@@ -25,8 +25,6 @@ sonora-agc2 = "0.2"
|
||||
sonora-simd = "0.2"
|
||||
thiserror = "2.0.21"
|
||||
tracing = "0.1.44"
|
||||
tsclientlib = { path = "../proto/tsclientlib" }
|
||||
tsproto-packets = { path = "../proto/tsproto-packets" }
|
||||
|
||||
[dev-dependencies]
|
||||
serde_json = "1"
|
||||
|
||||
@@ -1,45 +1,15 @@
|
||||
//! Opus encoding into TeamSpeak voice packets.
|
||||
//! Opus encoding of 20 ms frames into [`EncodedVoice`].
|
||||
|
||||
use opus2::{Application, Bitrate, Channels, Encoder};
|
||||
use tsproto_packets::packets::{AudioData, CodecType, OutAudio, OutPacket};
|
||||
|
||||
use crate::pcm::{FRAME_SAMPLES, SAMPLE_RATE};
|
||||
use crate::packet::{EncodedVoice, VoiceCodec};
|
||||
use crate::pcm::SAMPLE_RATE;
|
||||
use crate::{Error, Result};
|
||||
|
||||
/// Largest possible Opus packet.
|
||||
const MAX_PACKET: usize = 1275;
|
||||
|
||||
/// The two Opus codecs TeamSpeak channels use.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum VoiceCodec {
|
||||
/// Mono, tuned for speech (`CodecType::OpusVoice`).
|
||||
Voice,
|
||||
/// Stereo, tuned for music (`CodecType::OpusMusic`).
|
||||
Music,
|
||||
}
|
||||
|
||||
impl VoiceCodec {
|
||||
pub fn channels(self) -> usize {
|
||||
match self {
|
||||
VoiceCodec::Voice => 1,
|
||||
VoiceCodec::Music => 2,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn codec_type(self) -> CodecType {
|
||||
match self {
|
||||
VoiceCodec::Voice => CodecType::OpusVoice,
|
||||
VoiceCodec::Music => CodecType::OpusMusic,
|
||||
}
|
||||
}
|
||||
|
||||
/// Samples (all channels) in one 20 ms frame.
|
||||
pub fn frame_len(self) -> usize {
|
||||
FRAME_SAMPLES * self.channels()
|
||||
}
|
||||
}
|
||||
|
||||
/// Encodes 20 ms frames of 48 kHz audio into voice packets.
|
||||
/// Encodes 20 ms frames of 48 kHz audio into Opus packets.
|
||||
pub struct VoiceEncoder {
|
||||
encoder: Encoder,
|
||||
codec: VoiceCodec,
|
||||
@@ -53,7 +23,7 @@ impl VoiceEncoder {
|
||||
VoiceCodec::Music => (Channels::Stereo, Application::Audio),
|
||||
};
|
||||
let mut encoder = Encoder::new(SAMPLE_RATE, channels, application)?;
|
||||
// Survive some packet loss: TeamSpeak voice is plain UDP.
|
||||
// Survive some packet loss: voice travels over unreliable datagrams.
|
||||
encoder.set_inband_fec(true)?;
|
||||
encoder.set_packet_loss_perc(5)?;
|
||||
Ok(Self { encoder, codec, out: vec![0; MAX_PACKET] })
|
||||
@@ -82,26 +52,25 @@ impl VoiceEncoder {
|
||||
Ok(&self.out[..len])
|
||||
}
|
||||
|
||||
/// Encode one frame into a packet ready for `Connection::send_audio`.
|
||||
/// The connection assigns the packet id.
|
||||
pub fn encode(&mut self, frame: &[f32]) -> Result<OutPacket> {
|
||||
let codec = self.codec.codec_type();
|
||||
let data = self.encode_to_bytes(frame)?;
|
||||
Ok(OutAudio::new(&AudioData::C2S { id: 0, codec, data }))
|
||||
/// Encode one frame for the transport to send. The transport assigns the
|
||||
/// packet number.
|
||||
pub fn encode(&mut self, frame: &[f32]) -> Result<EncodedVoice> {
|
||||
let codec = self.codec;
|
||||
let payload = self.encode_to_bytes(frame)?.to_vec();
|
||||
Ok(EncodedVoice { codec, payload })
|
||||
}
|
||||
|
||||
/// The empty packet that tells listeners the transmission ended.
|
||||
pub fn end_of_stream(&self) -> OutPacket {
|
||||
OutAudio::new(&AudioData::C2S { id: 0, codec: self.codec.codec_type(), data: &[] })
|
||||
pub fn end_of_stream(&self) -> EncodedVoice {
|
||||
EncodedVoice { codec: self.codec, payload: Vec::new() }
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use tsproto_packets::packets::{Direction, InAudioBuf};
|
||||
|
||||
use super::*;
|
||||
use crate::pcm;
|
||||
use crate::packet::{TalkerId, VoicePacket};
|
||||
use crate::pcm::{self, FRAME_SAMPLES};
|
||||
|
||||
/// Encode a tone, feed the packets through the mixer (jitter buffer +
|
||||
/// decoder), and check the tone comes out.
|
||||
@@ -112,15 +81,16 @@ mod tests {
|
||||
let tone = pcm::sine(1000.0, 1.0, 0.5);
|
||||
let mut decoded = Vec::new();
|
||||
for (i, frame) in tone.chunks_exact(FRAME_SAMPLES).enumerate() {
|
||||
let data = encoder.encode_to_bytes(frame).unwrap().to_vec();
|
||||
let packet = OutAudio::new(&AudioData::S2C {
|
||||
id: i as u16,
|
||||
codec: CodecType::OpusVoice,
|
||||
from: 7,
|
||||
data: &data,
|
||||
});
|
||||
let packet = InAudioBuf::try_new(Direction::S2C, packet.into_vec()).unwrap();
|
||||
mixer.handle_packet(tsclientlib::ClientId(7), packet).unwrap();
|
||||
let sent = encoder.encode(frame).unwrap();
|
||||
assert_eq!(sent.codec, VoiceCodec::Voice);
|
||||
let packet = VoicePacket {
|
||||
talker: TalkerId(7),
|
||||
seq: i as u16,
|
||||
codec: sent.codec,
|
||||
whisper: false,
|
||||
payload: sent.payload,
|
||||
};
|
||||
mixer.handle_packet(packet).unwrap();
|
||||
let mut out = vec![0.0; FRAME_SAMPLES * 2];
|
||||
mixer.fill_buffer(&mut out);
|
||||
decoded.extend(pcm::to_mono(&out, 2));
|
||||
@@ -131,6 +101,24 @@ mod tests {
|
||||
assert!(ratio > 0.8, "tone ratio {ratio}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn end_of_stream_has_no_payload() {
|
||||
let encoder = VoiceEncoder::new(VoiceCodec::Music).unwrap();
|
||||
let end = encoder.end_of_stream();
|
||||
assert_eq!(end, EncodedVoice { codec: VoiceCodec::Music, payload: vec![] });
|
||||
assert!(end.is_end());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn encoded_frames_carry_codec_and_audio() {
|
||||
let mut voice = VoiceEncoder::new(VoiceCodec::Voice).unwrap();
|
||||
let mut music = VoiceEncoder::new(VoiceCodec::Music).unwrap();
|
||||
let a = voice.encode(&[0.1; FRAME_SAMPLES]).unwrap();
|
||||
let b = music.encode(&[0.1; FRAME_SAMPLES * 2]).unwrap();
|
||||
assert_eq!((a.codec, b.codec), (VoiceCodec::Voice, VoiceCodec::Music));
|
||||
assert!(!a.is_end() && !b.is_end());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_wrong_frame_size() {
|
||||
let mut encoder = VoiceEncoder::new(VoiceCodec::Music).unwrap();
|
||||
|
||||
@@ -0,0 +1,879 @@
|
||||
//! Handle receiving audio.
|
||||
//!
|
||||
//! Moved here from the vendored `tsclientlib::audio` and made independent of the
|
||||
//! transport: it reads [`VoicePacket`]s, whatever carried them.
|
||||
//!
|
||||
//! The [`AudioHandler`] collects all incoming audio packets and queues them per
|
||||
//! talker. It decodes the audio, handles out-of-order packets and missing
|
||||
//! packets. It automatically adjusts the queue length based on the jitter of
|
||||
//! incoming packets.
|
||||
|
||||
use std::cmp::Reverse;
|
||||
use std::collections::{HashMap, VecDeque};
|
||||
use std::convert::TryInto;
|
||||
|
||||
use opus2::{Channels, Decoder, packet};
|
||||
use thiserror::Error;
|
||||
use tracing::{Span, debug, info_span, trace, warn};
|
||||
|
||||
use crate::packet::{TalkerId, VoicePacket};
|
||||
|
||||
const SAMPLE_RATE: u32 = 48_000;
|
||||
const CHANNELS: Channels = Channels::Stereo;
|
||||
const CHANNEL_NUM: usize = 2;
|
||||
/// If this amount of packets is lost consecutively, we assume the stream stopped.
|
||||
const MAX_PACKET_LOSSES: usize = 3;
|
||||
/// Store the buffer sizes for the last `LAST_BUFFER_SIZE_COUNT` packets.
|
||||
const LAST_BUFFER_SIZE_COUNT: u8 = 255;
|
||||
/// The amount of samples to maximally buffer. Equivalent to 0.5 s.
|
||||
const MAX_BUFFER_SIZE: usize = 48_000 / 2;
|
||||
/// Maximum number of packets in the queue.
|
||||
const MAX_BUFFER_PACKETS: usize = 50;
|
||||
/// Buffer for maximal 0.5 s without playing anything.
|
||||
const MAX_BUFFER_TIME: usize = 48_000 / 2;
|
||||
/// Duplicate or remove every `step` sample when speeding-up.
|
||||
const SPEED_CHANGE_STEPS: usize = 100;
|
||||
/// The usual amount of samples in a frame.
|
||||
///
|
||||
/// Use 48 kHz, 20 ms frames (50 per second) and mono data (1 channel).
|
||||
/// This means 1920 samples and 7.5 kiB.
|
||||
const USUAL_FRAME_SIZE: usize = 48000 / 50;
|
||||
|
||||
type Result<T> = std::result::Result<T, Error>;
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
#[non_exhaustive]
|
||||
pub enum Error {
|
||||
#[error("Failed to create opus decoder: {0}")]
|
||||
CreateDecoder(#[source] opus2::Error),
|
||||
#[error("Opus decode failed: {error} (packet: {packet:?})")]
|
||||
Decode {
|
||||
#[source]
|
||||
error: opus2::Error,
|
||||
packet: Option<Vec<u8>>,
|
||||
},
|
||||
#[error("Get duplicate packet id {0}")]
|
||||
Duplicate(u16),
|
||||
#[error("Failed to get packet samples: {0}")]
|
||||
GetPacketSample(#[source] opus2::Error),
|
||||
#[error("Audio queue is full, dropping")]
|
||||
QueueFull,
|
||||
#[error("Audio packet is too late, dropping (wanted {wanted}, got {got})")]
|
||||
TooLate { wanted: u16, got: u16 },
|
||||
#[error("Packet has too many samples")]
|
||||
TooManySamples,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
struct SlidingWindowMinimum<T: Copy + Default + Ord> {
|
||||
/// How long a value stays in the sliding window.
|
||||
size: u8,
|
||||
/// This is a sliding window minimum, it contains
|
||||
/// `(insertion time, value)`.
|
||||
///
|
||||
/// When we insert a value, we can remove all bigger sample counts,
|
||||
/// thus the queue always stays sorted with the minimum at the front
|
||||
/// and the maximum at the back (latest entry).
|
||||
///
|
||||
/// Provides amortized O(1) minimum.
|
||||
/// Source: https://people.cs.uct.ac.za/~ksmith/articles/sliding_window_minimum.html#sliding-window-minimum-algorithm
|
||||
queue: VecDeque<(u8, T)>,
|
||||
/// The current insertion time.
|
||||
cur_time: u8,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct QueuePacket {
|
||||
packet: VoicePacket,
|
||||
samples: usize,
|
||||
id: u16,
|
||||
}
|
||||
|
||||
/// A queue for audio packets for one audio stream.
|
||||
pub struct AudioQueue {
|
||||
span: Span,
|
||||
decoder: Decoder,
|
||||
pub volume: f32,
|
||||
/// The id of the next packet that should be decoded.
|
||||
///
|
||||
/// Used to check for packet loss.
|
||||
next_id: u16,
|
||||
/// If the last packet was a whisper packet.
|
||||
whispering: bool,
|
||||
packet_buffer: VecDeque<QueuePacket>,
|
||||
/// Amount of samples in the `packet_buffer`.
|
||||
packet_buffer_samples: usize,
|
||||
/// Temporary buffer that contains the samples of one decoded packet.
|
||||
decoded_buffer: Vec<f32>,
|
||||
/// The number of samples in `decoded_buffer` that have been returned.
|
||||
decoded_pos: usize,
|
||||
/// The number of samples in the last packet.
|
||||
last_packet_samples: usize,
|
||||
/// The last `packet_loss_num` packet decodes were a loss.
|
||||
packet_loss_num: usize,
|
||||
/// The amount of samples to buffer until this queue is ready to play.
|
||||
buffering_samples: usize,
|
||||
/// The amount of packets in the buffer when a packet was decoded.
|
||||
///
|
||||
/// Uses the amount of samples in the `packet_buffer` / `USUAL_PACKET_SAMPLES`.
|
||||
/// Used to expand or reduce the buffer.
|
||||
last_buffer_size_min: SlidingWindowMinimum<u8>,
|
||||
last_buffer_size_max: SlidingWindowMinimum<Reverse<u8>>,
|
||||
/// Buffered for this duration.
|
||||
buffered_for_samples: usize,
|
||||
}
|
||||
|
||||
/// Handles incoming audio, has one [`AudioQueue`] per talker.
|
||||
#[derive(Default)]
|
||||
pub struct AudioHandler {
|
||||
queues: HashMap<TalkerId, AudioQueue>,
|
||||
/// Buffer this amount of samples for new queues before starting to play.
|
||||
///
|
||||
/// Updated when a new queue gets added.
|
||||
avg_buffer_samples: usize,
|
||||
}
|
||||
|
||||
impl<T: Copy + Default + Ord> SlidingWindowMinimum<T> {
|
||||
fn new(size: u8) -> Self {
|
||||
Self { size, queue: Default::default(), cur_time: 0 }
|
||||
}
|
||||
|
||||
fn push(&mut self, value: T) {
|
||||
while self.queue.back().map(|(_, s)| *s >= value).unwrap_or_default() {
|
||||
self.queue.pop_back();
|
||||
}
|
||||
let i = self.cur_time;
|
||||
self.queue.push_back((i, value));
|
||||
while self
|
||||
.queue
|
||||
.front()
|
||||
.map(|(i, _)| self.cur_time.wrapping_sub(*i) >= self.size)
|
||||
.unwrap_or_default()
|
||||
{
|
||||
self.queue.pop_front();
|
||||
}
|
||||
self.cur_time = self.cur_time.wrapping_add(1);
|
||||
}
|
||||
|
||||
fn get_min(&self) -> T {
|
||||
self.queue.front().map(|(_, s)| *s).unwrap_or_default()
|
||||
}
|
||||
}
|
||||
|
||||
impl AudioQueue {
|
||||
fn new(packet: VoicePacket) -> Result<Self> {
|
||||
let last_packet_samples =
|
||||
packet::get_nb_samples(&packet.payload, SAMPLE_RATE).map_err(Error::GetPacketSample)?;
|
||||
if last_packet_samples > MAX_BUFFER_SIZE {
|
||||
return Err(Error::TooManySamples);
|
||||
}
|
||||
|
||||
let last_packet_samples = last_packet_samples * CHANNEL_NUM;
|
||||
let whispering = packet.whisper;
|
||||
let decoder = Decoder::new(SAMPLE_RATE, CHANNELS).map_err(Error::CreateDecoder)?;
|
||||
|
||||
let mut res = Self {
|
||||
span: Span::current(),
|
||||
decoder,
|
||||
volume: 1.0,
|
||||
next_id: packet.seq,
|
||||
whispering,
|
||||
packet_buffer: Default::default(),
|
||||
packet_buffer_samples: 0,
|
||||
decoded_buffer: Default::default(),
|
||||
decoded_pos: 0,
|
||||
last_packet_samples,
|
||||
packet_loss_num: 0,
|
||||
buffering_samples: 0,
|
||||
last_buffer_size_min: SlidingWindowMinimum::new(LAST_BUFFER_SIZE_COUNT),
|
||||
last_buffer_size_max: SlidingWindowMinimum::<Reverse<u8>>::new(LAST_BUFFER_SIZE_COUNT),
|
||||
buffered_for_samples: 0,
|
||||
};
|
||||
res.add_buffer_size(0);
|
||||
res.add_packet(packet)?;
|
||||
Ok(res)
|
||||
}
|
||||
|
||||
pub fn get_decoder(&self) -> &Decoder {
|
||||
&self.decoder
|
||||
}
|
||||
pub fn is_whispering(&self) -> bool {
|
||||
self.whispering
|
||||
}
|
||||
|
||||
/// Size is in samples.
|
||||
fn add_buffer_size(&mut self, size: usize) {
|
||||
if let Ok(size) = (size / USUAL_FRAME_SIZE).try_into() {
|
||||
self.last_buffer_size_min.push(size);
|
||||
self.last_buffer_size_max.push(Reverse(size));
|
||||
} else {
|
||||
warn!(parent: &self.span, size, "Failed to put amount of packets into an u8");
|
||||
}
|
||||
}
|
||||
|
||||
/// The approximate deviation of the buffer size.
|
||||
fn get_deviation(&self) -> u8 {
|
||||
let min = self.last_buffer_size_min.get_min();
|
||||
let max = self.last_buffer_size_max.get_min();
|
||||
max.0 - min
|
||||
}
|
||||
|
||||
fn add_packet(&mut self, packet: VoicePacket) -> Result<()> {
|
||||
let _span = self.span.enter();
|
||||
if self.packet_buffer.len() >= MAX_BUFFER_PACKETS {
|
||||
return Err(Error::QueueFull);
|
||||
}
|
||||
let samples;
|
||||
if packet.is_end() {
|
||||
// End of stream
|
||||
samples = 0;
|
||||
} else {
|
||||
samples = packet::get_nb_samples(&packet.payload, SAMPLE_RATE)
|
||||
.map_err(Error::GetPacketSample)?;
|
||||
if samples > MAX_BUFFER_SIZE {
|
||||
return Err(Error::TooManySamples);
|
||||
}
|
||||
}
|
||||
|
||||
let id = packet.seq;
|
||||
let packet = QueuePacket { packet, samples, id };
|
||||
if id.wrapping_sub(self.next_id) > MAX_BUFFER_PACKETS as u16 {
|
||||
return Err(Error::TooLate { wanted: self.next_id, got: id });
|
||||
}
|
||||
|
||||
// Put into first spot where the id is smaller
|
||||
let i = self.packet_buffer.len()
|
||||
- self
|
||||
.packet_buffer
|
||||
.iter()
|
||||
.enumerate()
|
||||
.rev()
|
||||
.take_while(|(_, p)| p.id.wrapping_sub(id) <= MAX_BUFFER_PACKETS as u16)
|
||||
.count();
|
||||
// Check for duplicate packet
|
||||
if let Some(p) = self.packet_buffer.get(i)
|
||||
&& p.id == packet.id
|
||||
{
|
||||
return Err(Error::Duplicate(p.id));
|
||||
}
|
||||
|
||||
trace!("Insert packet {} at {}", id, i);
|
||||
let last_id = self.packet_buffer.back().map(|p| p.id.wrapping_add(1)).unwrap_or(id);
|
||||
if last_id <= id {
|
||||
self.buffering_samples = self.buffering_samples.saturating_sub(samples);
|
||||
// Reduce buffering counter by lost packets if there are some
|
||||
self.buffering_samples = self
|
||||
.buffering_samples
|
||||
.saturating_sub(usize::from(id - last_id) * self.last_packet_samples);
|
||||
}
|
||||
|
||||
self.packet_buffer_samples += packet.samples;
|
||||
self.packet_buffer.insert(i, packet);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn decode_packet(&mut self, packet: Option<&QueuePacket>, fec: bool) -> Result<()> {
|
||||
let _span = self.span.clone().entered();
|
||||
trace!(has_packet = packet.is_some(), fec, "Decoding packet");
|
||||
let packet_data;
|
||||
let len;
|
||||
if let Some(p) = packet {
|
||||
packet_data = &p.packet.payload[..];
|
||||
len = p.samples;
|
||||
self.whispering = p.packet.whisper;
|
||||
} else {
|
||||
// An empty slice signals packet loss to the decoder
|
||||
packet_data = &[];
|
||||
len = self.last_packet_samples;
|
||||
}
|
||||
self.packet_loss_num += 1;
|
||||
|
||||
let orig_buffer_len = self.decoded_buffer.len();
|
||||
self.decoded_buffer.resize(orig_buffer_len + len * CHANNEL_NUM, 0.0);
|
||||
let len = self
|
||||
.decoder
|
||||
.decode_float(packet_data, &mut self.decoded_buffer[orig_buffer_len..], fec)
|
||||
.map_err(|e| Error::Decode {
|
||||
error: e,
|
||||
packet: packet.map(|p| p.packet.payload.clone()),
|
||||
})?;
|
||||
self.last_packet_samples = len;
|
||||
self.decoded_buffer.truncate(orig_buffer_len + len * CHANNEL_NUM);
|
||||
|
||||
// Update packet_loss_num
|
||||
if packet.is_some() && !fec {
|
||||
self.packet_loss_num = 0;
|
||||
}
|
||||
|
||||
// Update last_buffer_size
|
||||
let mut count = self.packet_buffer_samples;
|
||||
if let Some(last) = self.packet_buffer.back() {
|
||||
// Lost packets
|
||||
trace!(
|
||||
last.id,
|
||||
next_id = self.next_id,
|
||||
first_id = self.packet_buffer.front().unwrap().id,
|
||||
buffer_len = self.packet_buffer.len(),
|
||||
"Ids"
|
||||
);
|
||||
count += (usize::from(last.id.wrapping_sub(self.next_id)) + 1
|
||||
- self.packet_buffer.len())
|
||||
* self.last_packet_samples;
|
||||
}
|
||||
self.add_buffer_size(count);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Decode data and return the requested length of buffered data.
|
||||
///
|
||||
/// Returns `true` in the second return value when the stream ended,
|
||||
/// `false` when it continues normally.
|
||||
pub fn get_next_data(&mut self, len: usize) -> Result<(&[f32], bool)> {
|
||||
let _span = self.span.clone().entered();
|
||||
if self.buffering_samples > 0 {
|
||||
if self.buffered_for_samples >= MAX_BUFFER_TIME {
|
||||
self.buffering_samples = 0;
|
||||
self.buffered_for_samples = 0;
|
||||
trace!(
|
||||
buffered_for_samples = self.buffered_for_samples,
|
||||
buffering_samples = self.buffering_samples,
|
||||
"Buffered for too long"
|
||||
);
|
||||
} else {
|
||||
self.buffered_for_samples += len;
|
||||
trace!(
|
||||
buffered_for_samples = self.buffered_for_samples,
|
||||
buffering_samples = self.buffering_samples,
|
||||
"Buffering"
|
||||
);
|
||||
return Ok((&[], false));
|
||||
}
|
||||
}
|
||||
// Need to refill buffer
|
||||
self.decoded_buffer.drain(..self.decoded_pos);
|
||||
|
||||
while self.decoded_buffer.len() < len {
|
||||
trace!(decoded_buffer = self.decoded_buffer.len(), len, "get_next_data");
|
||||
|
||||
// Decode a packet
|
||||
if let Some(packet) = self.packet_buffer.pop_front() {
|
||||
if packet.packet.is_end() {
|
||||
// End of stream
|
||||
return Ok((&self.decoded_buffer, true));
|
||||
}
|
||||
|
||||
self.packet_buffer_samples -= packet.samples;
|
||||
let cur_id = self.next_id;
|
||||
self.next_id = self.next_id.wrapping_add(1);
|
||||
if packet.id != cur_id {
|
||||
debug_assert!(
|
||||
packet.id.wrapping_sub(cur_id) < MAX_BUFFER_PACKETS as u16,
|
||||
"Invalid packet queue state: {} < {}",
|
||||
packet.id,
|
||||
cur_id
|
||||
);
|
||||
// Packet loss
|
||||
debug!(need = cur_id, have = packet.id, "Audio packet loss");
|
||||
if packet.id == self.next_id {
|
||||
// Can use forward-error-correction
|
||||
self.decode_packet(Some(&packet), true)?;
|
||||
} else {
|
||||
self.decode_packet(None, false)?;
|
||||
}
|
||||
self.packet_buffer_samples += packet.samples;
|
||||
self.packet_buffer.push_front(packet);
|
||||
} else {
|
||||
self.decode_packet(Some(&packet), false)?;
|
||||
}
|
||||
} else {
|
||||
debug!("No packets in queue");
|
||||
// Packet loss or end of stream
|
||||
self.decode_packet(None, false)?;
|
||||
}
|
||||
|
||||
if self.last_packet_samples == 0 {
|
||||
break;
|
||||
}
|
||||
|
||||
// Check if we should speed-up playback
|
||||
let min = self.last_buffer_size_min.get_min();
|
||||
let dev = self.get_deviation();
|
||||
if min > (MAX_BUFFER_SIZE / USUAL_FRAME_SIZE) as u8 {
|
||||
debug!(min, "Truncating buffer");
|
||||
// Throw out all but min samples
|
||||
let mut keep_samples = 0;
|
||||
let keep = self
|
||||
.packet_buffer
|
||||
.iter()
|
||||
.rev()
|
||||
.take_while(|p| {
|
||||
keep_samples += p.samples;
|
||||
keep_samples < usize::from(min) + USUAL_FRAME_SIZE
|
||||
})
|
||||
.count();
|
||||
let len = self.packet_buffer.len() - keep;
|
||||
self.packet_buffer.drain(..len);
|
||||
self.packet_buffer_samples = self.packet_buffer.iter().map(|p| p.samples).sum();
|
||||
if let Some(p) = self.packet_buffer.front() {
|
||||
self.next_id = p.id;
|
||||
}
|
||||
} else if min > dev {
|
||||
// Speed-up
|
||||
debug!(
|
||||
min,
|
||||
cur_packet_count = self.packet_buffer.len(),
|
||||
last_packet_samples = self.last_packet_samples,
|
||||
dev,
|
||||
"Speed-up buffer"
|
||||
);
|
||||
let start = self.decoded_buffer.len() - self.last_packet_samples * CHANNEL_NUM;
|
||||
for i in 0..(self.last_packet_samples / SPEED_CHANGE_STEPS) {
|
||||
let i = start + i * (SPEED_CHANGE_STEPS - 1) * CHANNEL_NUM;
|
||||
self.decoded_buffer.drain(i..(i + CHANNEL_NUM));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
self.decoded_pos = len;
|
||||
Ok((&self.decoded_buffer[..len], false))
|
||||
}
|
||||
}
|
||||
|
||||
impl AudioHandler {
|
||||
pub fn new() -> Self {
|
||||
Default::default()
|
||||
}
|
||||
|
||||
/// Delete all queues
|
||||
pub fn reset(&mut self) {
|
||||
self.queues.clear();
|
||||
}
|
||||
|
||||
pub fn get_queues(&self) -> &HashMap<TalkerId, AudioQueue> {
|
||||
&self.queues
|
||||
}
|
||||
pub fn get_mut_queues(&mut self) -> &mut HashMap<TalkerId, AudioQueue> {
|
||||
&mut self.queues
|
||||
}
|
||||
|
||||
/// `buf` is not cleared before filling it.
|
||||
///
|
||||
/// Returns the clients that are not talking anymore.
|
||||
pub fn fill_buffer(&mut self, buf: &mut [f32]) -> Vec<TalkerId> {
|
||||
self.fill_buffer_with_proc(buf, |_, _| {})
|
||||
}
|
||||
|
||||
/// `buf` is not cleared before filling it.
|
||||
///
|
||||
/// Same as [`Self::fill_buffer`] but before merging a queue into the output buffer, a preprocessor
|
||||
/// function is called. The queue volume is applied after calling the preprocessor.
|
||||
///
|
||||
/// Returns the clients that are not talking anymore.
|
||||
pub fn fill_buffer_with_proc<F: FnMut(&TalkerId, &[f32])>(
|
||||
&mut self,
|
||||
buf: &mut [f32],
|
||||
mut handle: F,
|
||||
) -> Vec<TalkerId> {
|
||||
trace!(len = buf.len(), "Filling audio buffer");
|
||||
let mut to_remove = Vec::new();
|
||||
for (id, queue) in self.queues.iter_mut() {
|
||||
if queue.packet_loss_num >= MAX_PACKET_LOSSES {
|
||||
debug!(packet_loss_num = queue.packet_loss_num, "Removing talker");
|
||||
to_remove.push(*id);
|
||||
continue;
|
||||
}
|
||||
|
||||
let vol = queue.volume;
|
||||
match queue.get_next_data(buf.len()) {
|
||||
Err(error) => {
|
||||
warn!(%error, "Failed to decode audio packet");
|
||||
}
|
||||
Ok((r, is_end)) => {
|
||||
handle(id, r);
|
||||
for i in 0..r.len() {
|
||||
buf[i] += r[i] * vol;
|
||||
}
|
||||
if is_end {
|
||||
to_remove.push(*id);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for id in &to_remove {
|
||||
self.queues.remove(id);
|
||||
}
|
||||
to_remove
|
||||
}
|
||||
|
||||
/// Add a packet to the queue of its talker.
|
||||
///
|
||||
/// If a new talker started talking, returns its id.
|
||||
pub fn handle_packet(&mut self, packet: VoicePacket) -> Result<Option<TalkerId>> {
|
||||
let id = packet.talker;
|
||||
let empty = packet.is_end();
|
||||
|
||||
if let Some(queue) = self.queues.get_mut(&id) {
|
||||
queue.add_packet(packet)?;
|
||||
Ok(None)
|
||||
} else {
|
||||
if empty {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
let _span = info_span!("audio queue", client = ?id);
|
||||
trace!("Adding talker");
|
||||
let mut queue = AudioQueue::new(packet)?;
|
||||
if !self.queues.is_empty() {
|
||||
// Update avg_buffer_samples
|
||||
let total: usize = self
|
||||
.queues
|
||||
.values()
|
||||
.map(|q| usize::from(q.last_buffer_size_min.get_min()))
|
||||
.sum();
|
||||
self.avg_buffer_samples = USUAL_FRAME_SIZE + total / self.queues.len();
|
||||
}
|
||||
queue.buffering_samples = self.avg_buffer_samples;
|
||||
self.queues.insert(id, queue);
|
||||
Ok(Some(id))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use opus2::Encoder;
|
||||
|
||||
use super::*;
|
||||
use crate::packet::VoiceCodec;
|
||||
|
||||
type TestResult = std::result::Result<(), Box<dyn std::error::Error>>;
|
||||
|
||||
const ID: TalkerId = TalkerId(0);
|
||||
|
||||
fn packet(seq: u16, payload: &[u8]) -> VoicePacket {
|
||||
VoicePacket {
|
||||
talker: ID,
|
||||
seq,
|
||||
codec: VoiceCodec::Music,
|
||||
whisper: false,
|
||||
payload: payload.to_vec(),
|
||||
}
|
||||
}
|
||||
|
||||
enum SimulateAction {
|
||||
CreateEncoder,
|
||||
/// Create packet with id.
|
||||
///
|
||||
/// The `bool` is `false` if packet handling should fail.
|
||||
ReceivePacket(u16, bool),
|
||||
ReceiveRaw(u16, Vec<u8>),
|
||||
/// Fetch audio of this sample count and expect a certain packet id.
|
||||
FillBuffer(usize, Option<u16>),
|
||||
/// Custom check
|
||||
Check(Box<dyn FnOnce(&AudioHandler)>),
|
||||
}
|
||||
|
||||
fn simulate(actions: Vec<SimulateAction>) -> TestResult {
|
||||
let mut encoder = None;
|
||||
let mut opus_output = [0; 1275]; // Max size for an opus packet
|
||||
let mut handler = AudioHandler::new();
|
||||
|
||||
for a in actions {
|
||||
println!("\nCurrent state");
|
||||
for q in &handler.queues {
|
||||
print!("Queue {:?}:", q.0);
|
||||
for p in &q.1.packet_buffer {
|
||||
print!(" {:?},", p);
|
||||
}
|
||||
println!();
|
||||
}
|
||||
|
||||
match a {
|
||||
SimulateAction::CreateEncoder => {
|
||||
encoder = Some(Encoder::new(
|
||||
48_000,
|
||||
opus2::Channels::Mono,
|
||||
opus2::Application::Voip,
|
||||
)?);
|
||||
}
|
||||
SimulateAction::ReceivePacket(i, success) => {
|
||||
let e = encoder.as_mut().unwrap();
|
||||
let data = vec![i as f32; USUAL_FRAME_SIZE];
|
||||
let len = e.encode_float(&data, &mut opus_output[..])?;
|
||||
if handler.handle_packet(packet(i, &opus_output[..len])).is_ok() != success {
|
||||
return Err(format!(
|
||||
"handle_packet returned {:?} but expected {:?}",
|
||||
!success, success
|
||||
)
|
||||
.into());
|
||||
}
|
||||
}
|
||||
SimulateAction::ReceiveRaw(i, data) => {
|
||||
let _ = handler.handle_packet(packet(i, &data));
|
||||
}
|
||||
SimulateAction::FillBuffer(size, expect) => {
|
||||
let mut buf = vec![0.0; size * 2]; // Stereo
|
||||
let cur_packet_id =
|
||||
handler.queues.get(&ID).and_then(|q| q.packet_buffer.front()).map(|p| p.id);
|
||||
handler.fill_buffer(&mut buf);
|
||||
let next_packet_id =
|
||||
handler.queues.get(&ID).and_then(|q| q.packet_buffer.front()).map(|p| p.id);
|
||||
|
||||
if expect.is_some() {
|
||||
assert_eq!(expect, cur_packet_id);
|
||||
assert_ne!(cur_packet_id, next_packet_id);
|
||||
}
|
||||
}
|
||||
SimulateAction::Check(f) => {
|
||||
f(&handler);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sliding_window_minimum() {
|
||||
let data = &[
|
||||
(5, 5),
|
||||
(6, 5),
|
||||
(3, 3),
|
||||
(4, 3),
|
||||
(6, 3),
|
||||
(5, 3),
|
||||
(6, 3),
|
||||
(6, 4),
|
||||
(6, 5),
|
||||
(6, 5),
|
||||
(6, 6),
|
||||
(7, 6),
|
||||
(5, 5),
|
||||
];
|
||||
let mut window = SlidingWindowMinimum::new(5);
|
||||
assert_eq!(window.get_min(), 0);
|
||||
for (i, (val, min)) in data.iter().enumerate() {
|
||||
println!("{:?}", window);
|
||||
window.push(*val);
|
||||
assert_eq!(window.get_min(), *min, "Failed in iteration {} ({:?})", i, window);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sliding_window_minimum_full() {
|
||||
let mut window = SlidingWindowMinimum::new(255);
|
||||
window.push(1);
|
||||
assert_eq!(window.get_min(), 1);
|
||||
for _ in 0..254 {
|
||||
window.push(2);
|
||||
}
|
||||
assert_eq!(window.get_min(), 1);
|
||||
window.push(2);
|
||||
assert_eq!(window.get_min(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn packets_wrapping() {
|
||||
let mut handler = AudioHandler::new();
|
||||
let mut buf = vec![0.0; 48_000 / 100 * 2];
|
||||
|
||||
for i in 0..100 {
|
||||
let seq = 65_500u16.wrapping_add(i);
|
||||
handler.handle_packet(packet(seq, &[0, 0, 0, 0, 0, 0, 0])).unwrap();
|
||||
|
||||
if i > 5 {
|
||||
handler.fill_buffer(&mut buf);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Short and malformed packets of any content are errors, never panics.
|
||||
#[test]
|
||||
fn short_packet_fuzz() {
|
||||
let mut handler = AudioHandler::new();
|
||||
let mut buf = vec![0.0; 48_000 / 100 * 2];
|
||||
let mut state = 0x2545_f491_4f6c_dd1du64;
|
||||
let mut next = move || {
|
||||
state ^= state << 13;
|
||||
state ^= state >> 7;
|
||||
state ^= state << 17;
|
||||
state
|
||||
};
|
||||
|
||||
for _ in 0..3_000 {
|
||||
// Payloads of 0..=100 bytes: empty, a lone TOC byte, and frames of any shape.
|
||||
let len = (next() % 101) as usize;
|
||||
let payload: Vec<u8> = (0..len).map(|_| next() as u8).collect();
|
||||
let _ = handler.handle_packet(packet(30, &payload));
|
||||
|
||||
handler.fill_buffer(&mut buf);
|
||||
handler.fill_buffer(&mut buf);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn packets_wrapping2() -> TestResult {
|
||||
let mut a = vec![SimulateAction::CreateEncoder];
|
||||
for i in 0..100 {
|
||||
let i = 65_500u16.wrapping_add(i);
|
||||
a.push(SimulateAction::ReceivePacket(i, true));
|
||||
a.push(SimulateAction::FillBuffer(USUAL_FRAME_SIZE, Some(i)));
|
||||
}
|
||||
for _ in 0..4 {
|
||||
a.push(SimulateAction::FillBuffer(USUAL_FRAME_SIZE, None));
|
||||
}
|
||||
a.push(SimulateAction::Check(Box::new(|h| assert!(h.queues.is_empty()))));
|
||||
simulate(a)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn silence() -> TestResult {
|
||||
let mut a = vec![SimulateAction::CreateEncoder];
|
||||
for _ in 0..100 {
|
||||
a.push(SimulateAction::FillBuffer(USUAL_FRAME_SIZE, None));
|
||||
}
|
||||
simulate(a)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reversed() -> TestResult {
|
||||
let mut a = vec![SimulateAction::CreateEncoder];
|
||||
for i in 0..5 {
|
||||
a.push(SimulateAction::ReceivePacket(i, true));
|
||||
a.push(SimulateAction::FillBuffer(USUAL_FRAME_SIZE, Some(i)));
|
||||
}
|
||||
a.push(SimulateAction::ReceivePacket(4, false));
|
||||
a.push(SimulateAction::ReceivePacket(3, false));
|
||||
for _ in 0..4 {
|
||||
a.push(SimulateAction::FillBuffer(USUAL_FRAME_SIZE, None));
|
||||
}
|
||||
a.push(SimulateAction::Check(Box::new(|h| assert!(h.queues.is_empty()))));
|
||||
simulate(a)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn duplicate() -> TestResult {
|
||||
let mut a = vec![SimulateAction::CreateEncoder];
|
||||
a.push(SimulateAction::ReceivePacket(0, true));
|
||||
a.push(SimulateAction::ReceivePacket(0, false));
|
||||
a.push(SimulateAction::FillBuffer(USUAL_FRAME_SIZE, Some(0)));
|
||||
a.push(SimulateAction::FillBuffer(USUAL_FRAME_SIZE, None));
|
||||
simulate(a)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn big_whole() -> TestResult {
|
||||
let mut a = vec![SimulateAction::CreateEncoder];
|
||||
for i in 27120..27124 {
|
||||
a.push(SimulateAction::ReceivePacket(i, true));
|
||||
a.push(SimulateAction::FillBuffer(USUAL_FRAME_SIZE, Some(i)));
|
||||
}
|
||||
a.push(SimulateAction::ReceiveRaw(27124, vec![2]));
|
||||
for _ in 0..10 {
|
||||
a.push(SimulateAction::FillBuffer(USUAL_FRAME_SIZE, None));
|
||||
}
|
||||
a.push(SimulateAction::Check(Box::new(|h| assert!(h.queues.is_empty()))));
|
||||
for i in 27339..27349 {
|
||||
a.push(SimulateAction::ReceivePacket(i, true));
|
||||
a.push(SimulateAction::FillBuffer(USUAL_FRAME_SIZE, None));
|
||||
}
|
||||
for _ in 0..4 {
|
||||
a.push(SimulateAction::FillBuffer(USUAL_FRAME_SIZE, None));
|
||||
}
|
||||
a.push(SimulateAction::Check(Box::new(|h| assert!(h.queues.is_empty()))));
|
||||
simulate(a)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn end_packet() -> TestResult {
|
||||
let mut a = vec![SimulateAction::CreateEncoder];
|
||||
for i in 0..10 {
|
||||
a.push(SimulateAction::ReceivePacket(i, true));
|
||||
a.push(SimulateAction::FillBuffer(USUAL_FRAME_SIZE, Some(i)));
|
||||
}
|
||||
a.push(SimulateAction::ReceiveRaw(10, vec![]));
|
||||
for _ in 0..4 {
|
||||
a.push(SimulateAction::FillBuffer(USUAL_FRAME_SIZE, None));
|
||||
}
|
||||
a.push(SimulateAction::Check(Box::new(|h| assert!(h.queues.is_empty()))));
|
||||
simulate(a)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn packet_loss() -> TestResult {
|
||||
let mut a = vec![SimulateAction::CreateEncoder];
|
||||
a.push(SimulateAction::ReceivePacket(50, true));
|
||||
a.push(SimulateAction::ReceivePacket(53, true));
|
||||
for _ in 0..8 {
|
||||
a.push(SimulateAction::FillBuffer(USUAL_FRAME_SIZE, None));
|
||||
}
|
||||
a.push(SimulateAction::Check(Box::new(|h| assert!(h.queues.is_empty()))));
|
||||
simulate(a)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn packet_wrapping_loss() -> TestResult {
|
||||
let mut a = vec![SimulateAction::CreateEncoder];
|
||||
a.push(SimulateAction::ReceivePacket(65534, true));
|
||||
a.push(SimulateAction::ReceivePacket(0, true));
|
||||
for _ in 0..7 {
|
||||
a.push(SimulateAction::FillBuffer(USUAL_FRAME_SIZE, None));
|
||||
}
|
||||
a.push(SimulateAction::Check(Box::new(|h| assert!(h.queues.is_empty()))));
|
||||
simulate(a)
|
||||
}
|
||||
|
||||
/// The talker is the key of the queues, and a new one is reported once.
|
||||
#[test]
|
||||
fn talkers_have_their_own_queues() -> TestResult {
|
||||
let mut encoder = Encoder::new(48_000, opus2::Channels::Mono, opus2::Application::Voip)?;
|
||||
let mut out = [0; 1275];
|
||||
let len = encoder.encode_float(&vec![0.1; USUAL_FRAME_SIZE], &mut out)?;
|
||||
let from = |talker: u16, seq: u16| VoicePacket {
|
||||
talker: TalkerId(talker),
|
||||
seq,
|
||||
codec: VoiceCodec::Voice,
|
||||
whisper: false,
|
||||
payload: out[..len].to_vec(),
|
||||
};
|
||||
let mut handler = AudioHandler::new();
|
||||
assert_eq!(handler.handle_packet(from(7, 100))?, Some(TalkerId(7)));
|
||||
assert_eq!(handler.handle_packet(from(7, 101))?, None);
|
||||
assert_eq!(handler.handle_packet(from(9, 5))?, Some(TalkerId(9)));
|
||||
let mut talkers: Vec<_> = handler.get_queues().keys().map(|t| t.0).collect();
|
||||
talkers.sort_unstable();
|
||||
assert_eq!(talkers, [7, 9]);
|
||||
// A talker that only says goodbye never gets a queue.
|
||||
let end = VoicePacket { payload: vec![], ..from(11, 0) };
|
||||
assert_eq!(handler.handle_packet(end)?, None);
|
||||
assert_eq!(handler.get_queues().len(), 2);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A queue knows whether the last packet it played was a whisper.
|
||||
#[test]
|
||||
fn whisper_flag_follows_the_packets() -> TestResult {
|
||||
let mut encoder = Encoder::new(48_000, opus2::Channels::Mono, opus2::Application::Voip)?;
|
||||
let mut out = [0; 1275];
|
||||
let len = encoder.encode_float(&vec![0.1; USUAL_FRAME_SIZE], &mut out)?;
|
||||
let packet = |seq: u16, whisper: bool| VoicePacket {
|
||||
talker: ID,
|
||||
seq,
|
||||
codec: VoiceCodec::Voice,
|
||||
whisper,
|
||||
payload: out[..len].to_vec(),
|
||||
};
|
||||
let mut handler = AudioHandler::new();
|
||||
handler.handle_packet(packet(0, true))?;
|
||||
assert!(handler.get_queues()[&ID].is_whispering());
|
||||
handler.handle_packet(packet(1, false))?;
|
||||
// One packet is played per call.
|
||||
let mut buf = [0.0; USUAL_FRAME_SIZE * 2];
|
||||
handler.fill_buffer(&mut buf);
|
||||
handler.fill_buffer(&mut buf);
|
||||
assert!(!handler.get_queues()[&ID].is_whispering());
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -1,14 +1,17 @@
|
||||
//! Voice pipeline building blocks.
|
||||
//!
|
||||
//! - [`pcm`]: sample-rate constants, tone generation and detection helpers
|
||||
//! - [`encode`]: Opus encoding of 20 ms frames into TeamSpeak voice packets
|
||||
//! - [`packet`]: the voice packet types the pipeline takes and produces
|
||||
//! ([`VoicePacket`], [`EncodedVoice`]), independent of the transport
|
||||
//! - [`encode`]: Opus encoding of 20 ms frames into [`EncodedVoice`]
|
||||
//! - [`framer`]: slice an arbitrary sample stream into codec frames
|
||||
//! - [`resample`]: sample-rate conversion to the 48 kHz the codec uses
|
||||
//! - [`wav`]: WAV file input/output
|
||||
//! - [`process`]: echo cancellation, noise suppression and gain control
|
||||
//! - [`vad`]: voice activity detection
|
||||
//! - [`mixer`]: per-client jitter buffer, decoder, volume and mixing (on the
|
||||
//! vendored `tsclientlib::audio::AudioHandler`)
|
||||
//! - [`jitter`]: the per-talker jitter buffer and Opus decoder
|
||||
//! - [`mixer`]: per-talker volume, mute and priority dimming over the jitter
|
||||
//! buffer, mixing to stereo
|
||||
//! - [`settings`]: all user audio settings in one serde struct
|
||||
//! - [`tap`]: the processed microphone for other consumers (the stream
|
||||
//! mixer), free while nobody listens
|
||||
@@ -17,7 +20,9 @@
|
||||
|
||||
pub mod encode;
|
||||
pub mod framer;
|
||||
pub mod jitter;
|
||||
pub mod mixer;
|
||||
pub mod packet;
|
||||
pub mod pcm;
|
||||
pub mod process;
|
||||
pub mod resample;
|
||||
@@ -29,12 +34,13 @@ pub mod wav;
|
||||
#[cfg(feature = "device")]
|
||||
pub mod device;
|
||||
|
||||
pub use encode::{VoiceCodec, VoiceEncoder};
|
||||
pub use encode::VoiceEncoder;
|
||||
pub use framer::Framer;
|
||||
pub use jitter::AudioHandler;
|
||||
pub use mixer::Mixer;
|
||||
pub use packet::{EncodedVoice, TalkerId, VoiceCodec, VoicePacket};
|
||||
pub use process::{ProcessingSettings, Processor};
|
||||
pub use settings::AudioSettings;
|
||||
pub use tsclientlib::audio::AudioHandler;
|
||||
pub use vad::{Vad, VadSettings};
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
//! Incoming voice: per-client jitter buffer, decoder and mixer, with a
|
||||
//! volume and mute per client, and everyone else dimmed while a priority
|
||||
//! Incoming voice: per-talker jitter buffer, decoder and mixer, with a
|
||||
//! volume and mute per talker, and everyone else dimmed while a priority
|
||||
//! speaker talks.
|
||||
//!
|
||||
//! The jitter buffer is the vendored `tsclientlib::audio::AudioHandler`. Per
|
||||
//! sender it keeps a queue of Opus packets and adapts its length:
|
||||
//! The jitter buffer is [`AudioHandler`]. Per sender it keeps a queue of Opus
|
||||
//! packets and adapts its length:
|
||||
//!
|
||||
//! - a new talker starts after a pre-buffer derived from the queue lengths of
|
||||
//! the other talkers (none for the first one);
|
||||
@@ -21,13 +21,11 @@
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
use tsclientlib::ClientId;
|
||||
use tsclientlib::audio::{AudioHandler, Error as QueueError};
|
||||
use tsproto_packets::packets::InAudioBuf;
|
||||
|
||||
use crate::jitter::{AudioHandler, Error as QueueError};
|
||||
use crate::packet::{TalkerId, VoicePacket};
|
||||
use crate::pcm::FRAME_SAMPLES;
|
||||
|
||||
/// Loudest per-client volume: +12 dB.
|
||||
/// Loudest per-talker volume: +12 dB.
|
||||
pub const MAX_CLIENT_VOLUME: f32 = 4.0;
|
||||
/// Most a priority speaker dims the others (dB).
|
||||
const MAX_DIMM_DB: f32 = -60.0;
|
||||
@@ -35,14 +33,14 @@ const MAX_DIMM_DB: f32 = -60.0;
|
||||
/// samples (5 frames, 100 ms) instead of jumping.
|
||||
const DIMM_RAMP_SAMPLES: usize = 5 * FRAME_SAMPLES;
|
||||
|
||||
/// Jitter buffer, decoder and mixer for incoming voice, keyed by sender.
|
||||
/// Jitter buffer, decoder and mixer for incoming voice, keyed by talker.
|
||||
/// Output is interleaved stereo at 48 kHz.
|
||||
pub struct Mixer {
|
||||
handler: AudioHandler<ClientId>,
|
||||
volumes: HashMap<ClientId, f32>,
|
||||
muted: HashSet<ClientId>,
|
||||
handler: AudioHandler,
|
||||
volumes: HashMap<TalkerId, f32>,
|
||||
muted: HashSet<TalkerId>,
|
||||
/// While one of them talks, everyone else is dimmed.
|
||||
priority: HashSet<ClientId>,
|
||||
priority: HashSet<TalkerId>,
|
||||
/// Linear gain of the others while a priority speaker talks (1: none).
|
||||
dimm: f32,
|
||||
/// How far the dimming has faded in (0..=1).
|
||||
@@ -70,21 +68,17 @@ impl Mixer {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
/// Queue a voice packet from `id`. Returns `Some(id)` when this client
|
||||
/// just started talking. Late, duplicate and malformed packets are
|
||||
/// errors; on UDP they are expected and can be ignored.
|
||||
pub fn handle_packet(
|
||||
&mut self,
|
||||
id: ClientId,
|
||||
packet: InAudioBuf,
|
||||
) -> Result<Option<ClientId>, QueueError> {
|
||||
self.handler.handle_packet(id, packet)
|
||||
/// Queue a voice packet for its talker. Returns `Some(talker)` when this
|
||||
/// talker just started talking. Late, duplicate and malformed packets are
|
||||
/// errors; on datagrams they are expected and can be ignored.
|
||||
pub fn handle_packet(&mut self, packet: VoicePacket) -> Result<Option<TalkerId>, QueueError> {
|
||||
self.handler.handle_packet(packet)
|
||||
}
|
||||
|
||||
/// Add the next `buf.len() / 2` stereo frames of all talkers to `buf`
|
||||
/// (not cleared first), each scaled by its volume, and dimmed while a
|
||||
/// priority speaker talks. Returns the clients that stopped talking.
|
||||
pub fn fill_buffer(&mut self, buf: &mut [f32]) -> Vec<ClientId> {
|
||||
/// priority speaker talks. Returns the talkers that stopped talking.
|
||||
pub fn fill_buffer(&mut self, buf: &mut [f32]) -> Vec<TalkerId> {
|
||||
let queues = self.handler.get_mut_queues();
|
||||
// A priority speaker with a queue (talking or buffering) dims all
|
||||
// other queues, streams too, unless we muted it.
|
||||
@@ -141,9 +135,9 @@ impl Mixer {
|
||||
stopped
|
||||
}
|
||||
|
||||
/// Linear gain for one client, clamped to `0..=`[`MAX_CLIENT_VOLUME`].
|
||||
/// Kept when the client stops and starts talking again.
|
||||
pub fn set_volume(&mut self, id: ClientId, volume: f32) {
|
||||
/// Linear gain for one talker, clamped to `0..=`[`MAX_CLIENT_VOLUME`].
|
||||
/// Kept when the talker stops and starts talking again.
|
||||
pub fn set_volume(&mut self, id: TalkerId, volume: f32) {
|
||||
let volume = if volume.is_finite() { volume.clamp(0.0, MAX_CLIENT_VOLUME) } else { 1.0 };
|
||||
if volume == 1.0 {
|
||||
self.volumes.remove(&id);
|
||||
@@ -153,15 +147,15 @@ impl Mixer {
|
||||
}
|
||||
|
||||
/// Like [`set_volume`](Self::set_volume), in dB (0 dB = unchanged).
|
||||
pub fn set_volume_db(&mut self, id: ClientId, db: f32) {
|
||||
pub fn set_volume_db(&mut self, id: TalkerId, db: f32) {
|
||||
self.set_volume(id, 10f32.powf(db / 20.0));
|
||||
}
|
||||
|
||||
pub fn volume(&self, id: ClientId) -> f32 {
|
||||
pub fn volume(&self, id: TalkerId) -> f32 {
|
||||
self.volumes.get(&id).copied().unwrap_or(1.0)
|
||||
}
|
||||
|
||||
pub fn set_muted(&mut self, id: ClientId, muted: bool) {
|
||||
pub fn set_muted(&mut self, id: TalkerId, muted: bool) {
|
||||
if muted {
|
||||
self.muted.insert(id);
|
||||
} else {
|
||||
@@ -169,30 +163,30 @@ impl Mixer {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn is_muted(&self, id: ClientId) -> bool {
|
||||
pub fn is_muted(&self, id: TalkerId) -> bool {
|
||||
self.muted.contains(&id)
|
||||
}
|
||||
|
||||
/// The priority speakers, and how much everyone else is dimmed while
|
||||
/// one of them talks: dB, clamped to -60..=0 (NaN: not at all).
|
||||
/// Replaces the previous set; [`forget`](Self::forget) leaves it alone,
|
||||
/// the caller sends a new set when the clients change.
|
||||
pub fn set_priority(&mut self, clients: impl IntoIterator<Item = ClientId>, dimm_db: f32) {
|
||||
self.priority = clients.into_iter().collect();
|
||||
/// the caller sends a new set when the talkers change.
|
||||
pub fn set_priority(&mut self, talkers: impl IntoIterator<Item = TalkerId>, dimm_db: f32) {
|
||||
self.priority = talkers.into_iter().collect();
|
||||
let db = if dimm_db.is_nan() { 0.0 } else { dimm_db.clamp(MAX_DIMM_DB, 0.0) };
|
||||
self.dimm = 10f32.powf(db / 20.0);
|
||||
}
|
||||
|
||||
/// Forget volume and mute of a client (e.g. it left the server; client
|
||||
/// ids are reused).
|
||||
pub fn forget(&mut self, id: ClientId) {
|
||||
/// Forget volume and mute of a talker (e.g. it left the server; ids may
|
||||
/// be reused).
|
||||
pub fn forget(&mut self, id: TalkerId) {
|
||||
self.volumes.remove(&id);
|
||||
self.muted.remove(&id);
|
||||
self.handler.get_mut_queues().remove(&id);
|
||||
}
|
||||
|
||||
/// Clients with a queue, i.e. currently talking or buffering.
|
||||
pub fn talkers(&self) -> impl Iterator<Item = ClientId> + '_ {
|
||||
/// Talkers with a queue, i.e. currently talking or buffering.
|
||||
pub fn talkers(&self) -> impl Iterator<Item = TalkerId> + '_ {
|
||||
self.handler.get_queues().keys().copied()
|
||||
}
|
||||
|
||||
@@ -202,7 +196,7 @@ impl Mixer {
|
||||
}
|
||||
|
||||
/// The underlying jitter buffer.
|
||||
pub fn handler(&self) -> &AudioHandler<ClientId> {
|
||||
pub fn handler(&self) -> &AudioHandler {
|
||||
&self.handler
|
||||
}
|
||||
}
|
||||
@@ -221,23 +215,26 @@ impl std::fmt::Debug for Mixer {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use tsproto_packets::packets::{AudioData, CodecType, Direction, OutAudio};
|
||||
|
||||
use super::*;
|
||||
use crate::VoiceEncoder;
|
||||
use crate::encode::VoiceCodec;
|
||||
use crate::packet::VoiceCodec;
|
||||
use crate::pcm::{self, FRAME_SAMPLES, SAMPLE_RATE};
|
||||
|
||||
fn packet(from: u16, id: u16, data: &[u8]) -> InAudioBuf {
|
||||
let packet = OutAudio::new(&AudioData::S2C { id, codec: CodecType::OpusVoice, from, data });
|
||||
InAudioBuf::try_new(Direction::S2C, packet.into_vec()).unwrap()
|
||||
fn packet(from: u16, seq: u16, data: &[u8]) -> VoicePacket {
|
||||
VoicePacket {
|
||||
talker: TalkerId(from),
|
||||
seq,
|
||||
codec: VoiceCodec::Voice,
|
||||
whisper: false,
|
||||
payload: data.to_vec(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Two clients send tones at the same level; after setting volumes the
|
||||
/// mix carries each at its own gain, and a muted one not at all.
|
||||
#[test]
|
||||
fn volume_per_client() {
|
||||
let (a, b) = (ClientId(3), ClientId(4));
|
||||
let (a, b) = (TalkerId(3), TalkerId(4));
|
||||
let mut enc_a = VoiceEncoder::new(VoiceCodec::Voice).unwrap();
|
||||
let mut enc_b = VoiceEncoder::new(VoiceCodec::Voice).unwrap();
|
||||
let tone_a = pcm::sine(500.0, 2.0, 0.2);
|
||||
@@ -251,11 +248,11 @@ mod tests {
|
||||
let frames = tone_a.chunks_exact(FRAME_SAMPLES).zip(tone_b.chunks_exact(FRAME_SAMPLES));
|
||||
for (i, (fa, fb)) in frames.enumerate() {
|
||||
let id = i as u16;
|
||||
let started = mixer.handle_packet(a, packet(3, id, enc_a.encode_to_bytes(fa).unwrap()));
|
||||
let started = mixer.handle_packet(packet(3, id, enc_a.encode_to_bytes(fa).unwrap()));
|
||||
if i == 0 {
|
||||
assert_eq!(started.unwrap(), Some(a));
|
||||
}
|
||||
mixer.handle_packet(b, packet(4, id, enc_b.encode_to_bytes(fb).unwrap())).unwrap();
|
||||
mixer.handle_packet(packet(4, id, enc_b.encode_to_bytes(fb).unwrap())).unwrap();
|
||||
let mut buf = vec![0.0; FRAME_SAMPLES * 2];
|
||||
mixer.fill_buffer(&mut buf);
|
||||
out.extend(pcm::to_mono(&buf, 2));
|
||||
@@ -274,8 +271,8 @@ mod tests {
|
||||
let id = 100 + i;
|
||||
let fa = &tone_a[..FRAME_SAMPLES];
|
||||
let fb = &tone_b[..FRAME_SAMPLES];
|
||||
let _ = mixer.handle_packet(a, packet(3, id, enc_a.encode_to_bytes(fa).unwrap()));
|
||||
let _ = mixer.handle_packet(b, packet(4, id, enc_b.encode_to_bytes(fb).unwrap()));
|
||||
let _ = mixer.handle_packet(packet(3, id, enc_a.encode_to_bytes(fa).unwrap()));
|
||||
let _ = mixer.handle_packet(packet(4, id, enc_b.encode_to_bytes(fb).unwrap()));
|
||||
let mut buf = vec![0.0; FRAME_SAMPLES * 2];
|
||||
mixer.fill_buffer(&mut buf);
|
||||
out.extend(pcm::to_mono(&buf, 2));
|
||||
@@ -289,7 +286,7 @@ mod tests {
|
||||
/// in and out, but not itself, and not while we muted it.
|
||||
#[test]
|
||||
fn priority_speaker_dims_others() {
|
||||
let (a, p) = (ClientId(3), ClientId(5));
|
||||
let (a, p) = (TalkerId(3), TalkerId(5));
|
||||
let mut enc_a = VoiceEncoder::new(VoiceCodec::Voice).unwrap();
|
||||
let mut enc_p = VoiceEncoder::new(VoiceCodec::Voice).unwrap();
|
||||
let tone_a = pcm::sine(500.0, 4.0, 0.2);
|
||||
@@ -308,14 +305,12 @@ mod tests {
|
||||
let mut out = Vec::new();
|
||||
for _ in 0..frames {
|
||||
let fa = frame(&tone_a, id_a);
|
||||
mixer
|
||||
.handle_packet(a, packet(3, id_a, enc_a.encode_to_bytes(&fa).unwrap()))
|
||||
.unwrap();
|
||||
mixer.handle_packet(packet(3, id_a, enc_a.encode_to_bytes(&fa).unwrap())).unwrap();
|
||||
id_a += 1;
|
||||
if with_p {
|
||||
let fp = frame(&tone_p, id_p);
|
||||
let data = enc_p.encode_to_bytes(&fp).unwrap();
|
||||
mixer.handle_packet(p, packet(5, id_p, data)).unwrap();
|
||||
mixer.handle_packet(packet(5, id_p, data)).unwrap();
|
||||
id_p += 1;
|
||||
}
|
||||
let mut buf = vec![0.0; FRAME_SAMPLES * 2];
|
||||
@@ -359,7 +354,7 @@ mod tests {
|
||||
/// frame: the other talker's level (per period of its tone) never jumps.
|
||||
#[test]
|
||||
fn priority_dimming_ramps_per_sample() {
|
||||
let (a, p) = (ClientId(3), ClientId(5));
|
||||
let p = TalkerId(5);
|
||||
let mut enc_a = VoiceEncoder::new(VoiceCodec::Voice).unwrap();
|
||||
let mut enc_p = VoiceEncoder::new(VoiceCodec::Voice).unwrap();
|
||||
let tone = pcm::sine(500.0, 2.0, 0.2);
|
||||
@@ -371,10 +366,10 @@ mod tests {
|
||||
// p talks from frame 30 to 59.
|
||||
for (i, frame) in tone.chunks_exact(FRAME_SAMPLES).enumerate() {
|
||||
let id = i as u16;
|
||||
mixer.handle_packet(a, packet(3, id, enc_a.encode_to_bytes(frame).unwrap())).unwrap();
|
||||
mixer.handle_packet(packet(3, id, enc_a.encode_to_bytes(frame).unwrap())).unwrap();
|
||||
if let Some(j) = i.checked_sub(30).filter(|j| *j < 30) {
|
||||
let data = enc_p.encode_to_bytes(frame).unwrap();
|
||||
mixer.handle_packet(p, packet(5, j as u16, data)).unwrap();
|
||||
mixer.handle_packet(packet(5, j as u16, data)).unwrap();
|
||||
}
|
||||
let mut buf = vec![0.0; FRAME_SAMPLES * 2];
|
||||
mixer.fill_buffer(&mut buf);
|
||||
@@ -400,17 +395,17 @@ mod tests {
|
||||
fn priority_dimm_bounds() {
|
||||
let mut mixer = Mixer::new();
|
||||
assert_eq!(mixer.dimm, 1.0);
|
||||
mixer.set_priority([ClientId(1)], -18.0);
|
||||
mixer.set_priority([TalkerId(1)], -18.0);
|
||||
assert!((mixer.dimm - 0.1259).abs() < 1e-3);
|
||||
mixer.set_priority([ClientId(1)], 6.0);
|
||||
mixer.set_priority([TalkerId(1)], 6.0);
|
||||
assert_eq!(mixer.dimm, 1.0);
|
||||
mixer.set_priority([ClientId(1)], f32::NEG_INFINITY);
|
||||
mixer.set_priority([TalkerId(1)], f32::NEG_INFINITY);
|
||||
assert!((mixer.dimm - 0.001).abs() < 1e-6);
|
||||
mixer.set_priority([ClientId(1)], f32::NAN);
|
||||
mixer.set_priority([TalkerId(1)], f32::NAN);
|
||||
assert_eq!(mixer.dimm, 1.0);
|
||||
// Forgetting a client keeps the set: the caller replaces it.
|
||||
mixer.forget(ClientId(1));
|
||||
assert!(mixer.priority.contains(&ClientId(1)));
|
||||
mixer.forget(TalkerId(1));
|
||||
assert!(mixer.priority.contains(&TalkerId(1)));
|
||||
mixer.set_priority([], -18.0);
|
||||
assert!(mixer.priority.is_empty());
|
||||
}
|
||||
@@ -418,7 +413,7 @@ mod tests {
|
||||
#[test]
|
||||
fn volume_bounds_and_forget() {
|
||||
let mut mixer = Mixer::new();
|
||||
let id = ClientId(9);
|
||||
let id = TalkerId(9);
|
||||
mixer.set_volume(id, 100.0);
|
||||
assert_eq!(mixer.volume(id), MAX_CLIENT_VOLUME);
|
||||
mixer.set_volume(id, -1.0);
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
//! Voice packets as the audio pipeline sees them, whatever transport carries
|
||||
//! them (the TeamSpeak connection today, a Voelin server later).
|
||||
//!
|
||||
//! The transport adapter turns what it receives into a [`VoicePacket`] and
|
||||
//! what [`VoiceEncoder`](crate::VoiceEncoder) produces ([`EncodedVoice`])
|
||||
//! into its own wire format; nothing in this crate knows either format.
|
||||
|
||||
use crate::pcm::FRAME_SAMPLES;
|
||||
|
||||
/// Who is talking: a sender id, unique among the talkers of one voice
|
||||
/// connection. A transport maps its own client ids onto it (TeamSpeak's
|
||||
/// 16-bit client id is used as is).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
|
||||
pub struct TalkerId(pub u16);
|
||||
|
||||
/// The two Opus flavours voice is sent in.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub enum VoiceCodec {
|
||||
/// Mono, tuned for speech.
|
||||
Voice,
|
||||
/// Stereo, tuned for music.
|
||||
Music,
|
||||
}
|
||||
|
||||
impl VoiceCodec {
|
||||
pub fn channels(self) -> usize {
|
||||
match self {
|
||||
VoiceCodec::Voice => 1,
|
||||
VoiceCodec::Music => 2,
|
||||
}
|
||||
}
|
||||
|
||||
/// Samples (all channels) in one 20 ms frame.
|
||||
pub fn frame_len(self) -> usize {
|
||||
FRAME_SAMPLES * self.channels()
|
||||
}
|
||||
}
|
||||
|
||||
/// A voice packet received from a talker.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct VoicePacket {
|
||||
pub talker: TalkerId,
|
||||
/// Packet number of this talker, counting up by one per 20 ms frame and
|
||||
/// wrapping at 65536; the jitter buffer orders by it and finds gaps.
|
||||
pub seq: u16,
|
||||
pub codec: VoiceCodec,
|
||||
/// Sent to us as a whisper instead of to the whole channel.
|
||||
pub whisper: bool,
|
||||
/// One Opus packet. An empty one ends the talk (a single byte counts as
|
||||
/// empty too: some servers send one).
|
||||
pub payload: Vec<u8>,
|
||||
}
|
||||
|
||||
impl VoicePacket {
|
||||
/// Whether this packet only ends the talk and carries no audio.
|
||||
pub fn is_end(&self) -> bool {
|
||||
self.payload.len() <= 1
|
||||
}
|
||||
}
|
||||
|
||||
/// One encoded frame to send. The transport assigns the packet number.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct EncodedVoice {
|
||||
pub codec: VoiceCodec,
|
||||
/// One Opus packet; empty: the transmission ended.
|
||||
pub payload: Vec<u8>,
|
||||
}
|
||||
|
||||
impl EncodedVoice {
|
||||
/// Whether this only tells listeners the transmission ended.
|
||||
pub fn is_end(&self) -> bool {
|
||||
self.payload.is_empty()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn codec_frames() {
|
||||
assert_eq!(VoiceCodec::Voice.frame_len(), FRAME_SAMPLES);
|
||||
assert_eq!(VoiceCodec::Music.frame_len(), FRAME_SAMPLES * 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn end_of_talk() {
|
||||
let voice = |payload: &[u8]| VoicePacket {
|
||||
talker: TalkerId(1),
|
||||
seq: 0,
|
||||
codec: VoiceCodec::Voice,
|
||||
whisper: false,
|
||||
payload: payload.to_vec(),
|
||||
};
|
||||
assert!(voice(&[]).is_end());
|
||||
assert!(voice(&[2]).is_end());
|
||||
assert!(!voice(&[2, 3]).is_end());
|
||||
assert!(EncodedVoice { codec: VoiceCodec::Voice, payload: vec![] }.is_end());
|
||||
assert!(!EncodedVoice { codec: VoiceCodec::Voice, payload: vec![0] }.is_end());
|
||||
}
|
||||
}
|
||||
@@ -7,10 +7,8 @@
|
||||
//! 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 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};
|
||||
use voelin_audio::{Mixer, TalkerId, VoiceCodec, VoiceEncoder, VoicePacket};
|
||||
|
||||
/// The receiver pulls 10 ms at a time, like a playback loop.
|
||||
const PULL: usize = SAMPLE_RATE as usize / 100;
|
||||
@@ -38,7 +36,7 @@ fn simulate(ppm: f64, hours: f64) -> Vec<f64> {
|
||||
|
||||
let mut rng = Rng(ppm.to_bits());
|
||||
let mut mixer = Mixer::new();
|
||||
let client = ClientId(5);
|
||||
let talker = TalkerId(5);
|
||||
let total = (hours * 3600.0 * SAMPLE_RATE as f64) as u64;
|
||||
// Sender frame n is made at n * 20 ms of the sender's clock.
|
||||
let frame_time = |n: u64| n as f64 * FRAME_SAMPLES as f64 / (1.0 + ppm * 1e-6);
|
||||
@@ -68,15 +66,15 @@ fn simulate(ppm: f64, hours: f64) -> Vec<f64> {
|
||||
let arrived = in_flight.partition_point(|&(t, _)| t <= now as f64);
|
||||
for (_, n) in in_flight.drain(..arrived) {
|
||||
let data = if n % MARKER_EVERY == MARKER_EVERY / 2 { &marker } else { &quiet };
|
||||
let packet = OutAudio::new(&AudioData::S2C {
|
||||
id: n as u16,
|
||||
codec: CodecType::OpusVoice,
|
||||
from: 5,
|
||||
data,
|
||||
});
|
||||
let packet = InAudioBuf::try_new(Direction::S2C, packet.into_vec()).unwrap();
|
||||
let packet = VoicePacket {
|
||||
talker,
|
||||
seq: n as u16,
|
||||
codec: VoiceCodec::Voice,
|
||||
whisper: false,
|
||||
payload: data.clone(),
|
||||
};
|
||||
// Late packets are dropped by the jitter buffer, as on a real network.
|
||||
let _ = mixer.handle_packet(client, packet);
|
||||
let _ = mixer.handle_packet(packet);
|
||||
}
|
||||
|
||||
out.fill(0.0);
|
||||
|
||||
@@ -14,8 +14,9 @@ default = ["audio-device"]
|
||||
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"]
|
||||
# source on Android), and the studio's WHIP output. The crate itself is always
|
||||
# there: the stream types in the API (`EncodedFrame`, `LayerSpec`) are its.
|
||||
media = ["voelin-media/whip"]
|
||||
# `media` with voelin-media's desktop backends: libvpx, dav1d, OpenH264 and
|
||||
# FFmpeg loaded at runtime, X11 and PipeWire on Linux. Not for Android
|
||||
# (libvpx does not cross-compile there).
|
||||
@@ -24,6 +25,8 @@ media-desktop = ["media", "voelin-media/default"]
|
||||
[dependencies]
|
||||
anyhow = "1"
|
||||
base64 = "0.22"
|
||||
# The RTP packets of the session seam (`voelin_proto::link::MediaPacket`).
|
||||
bytes = "1"
|
||||
dirs = "6"
|
||||
futures = "0.3"
|
||||
# Finding a server's gateway in DNS (the voice resolver's version).
|
||||
@@ -49,11 +52,17 @@ toml = "1.1.6"
|
||||
tracing = "0.1"
|
||||
voelin-audio = { path = "../voelin-audio", default-features = false }
|
||||
voelin-gateway-proto = { path = "../voelin-gateway-proto", features = ["client"] }
|
||||
voelin-media = { path = "../voelin-media", default-features = false, features = ["str0m", "whip"], optional = true }
|
||||
voelin-model = { path = "../voelin-model" }
|
||||
# `IdentityBlob`, the identity of the API (a TeamSpeak identity as the key store
|
||||
# keeps it, or a Voelin key).
|
||||
voelin-identity = { workspace = true }
|
||||
voelin-media = { path = "../voelin-media", default-features = false }
|
||||
voelin-model = { workspace = true }
|
||||
voelin-observer = { path = "../voelin-observer" }
|
||||
# Paths only (the cache directory).
|
||||
voelin-platform = { path = "../voelin-platform", default-features = false }
|
||||
# The backend-neutral session seam the engine consumes (`voelin_proto::link`)
|
||||
# and the v1 messages it speaks.
|
||||
voelin-proto = { workspace = true }
|
||||
voelin-query = { path = "../voelin-query" }
|
||||
voelin-store = { path = "../voelin-store" }
|
||||
voelin-stream = { path = "../voelin-stream" }
|
||||
@@ -64,13 +73,15 @@ tsproto-packets = { path = "../proto/tsproto-packets" }
|
||||
tsproto-types = { path = "../proto/tsproto-types" }
|
||||
|
||||
[dev-dependencies]
|
||||
# An HTTP/2 connection in a test (both already in the tree through h2).
|
||||
bytes = "1"
|
||||
# An HTTP/2 connection in a test (already in the tree through h2).
|
||||
http = "1"
|
||||
# Already in the app's graph (reqwest); for one_rustls_crypto_provider.
|
||||
rustls = { version = "0.23", default-features = false }
|
||||
# `process`: the browser interop test drives Chromium through Node.js.
|
||||
tokio = { version = "1", features = ["macros", "net", "process", "rt-multi-thread", "test-util"] }
|
||||
# The fakes of the session seam (`FakeHost`, `FakeSession`, the conformance
|
||||
# suite).
|
||||
voelin-proto = { workspace = true, features = ["test-util"] }
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -16,16 +16,18 @@ use std::time::{Duration, Instant};
|
||||
|
||||
use tokio::sync::mpsc;
|
||||
use tracing::{debug, warn};
|
||||
use tsclientlib::ClientId;
|
||||
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::tap;
|
||||
use voelin_audio::vad::SILENCE_DB;
|
||||
use voelin_audio::{AudioSettings, Framer, Mixer, Processor, Vad, VoiceCodec, VoiceEncoder};
|
||||
use voelin_audio::{
|
||||
AudioSettings, EncodedVoice, Framer, Mixer, Processor, TalkerId, Vad, VoiceCodec, VoiceEncoder,
|
||||
VoicePacket,
|
||||
};
|
||||
|
||||
pub(crate) enum AudioIn {
|
||||
Packet(InAudioBuf),
|
||||
/// Voice of a talker, from the voice connection.
|
||||
Packet(VoicePacket),
|
||||
Transmit(bool),
|
||||
InputMuted(bool),
|
||||
OutputMuted(bool),
|
||||
@@ -33,19 +35,19 @@ pub(crate) enum AudioIn {
|
||||
Settings(Box<AudioSettings>),
|
||||
/// Playback volume of one client, linear (1 = unchanged, up to 4).
|
||||
ClientVolume {
|
||||
client: ClientId,
|
||||
client: TalkerId,
|
||||
volume: f32,
|
||||
},
|
||||
ClientMuted {
|
||||
client: ClientId,
|
||||
client: TalkerId,
|
||||
muted: bool,
|
||||
},
|
||||
/// The client left; client ids are reused, so forget its volume.
|
||||
ClientLeft(ClientId),
|
||||
ClientLeft(TalkerId),
|
||||
/// The priority speakers: while one talks, everyone else (streams too)
|
||||
/// is dimmed by `dimm_db` (the server's setting, e.g. -18).
|
||||
PrioritySpeakers {
|
||||
clients: Vec<ClientId>,
|
||||
clients: Vec<TalkerId>,
|
||||
dimm_db: f32,
|
||||
},
|
||||
/// An Opus frame (48 kHz) of a watched stream; `time` is its RTP time
|
||||
@@ -111,10 +113,10 @@ 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.
|
||||
/// Start the audio thread. Encoded voice goes to `outgoing`; problems (e.g.
|
||||
/// no device) and the microphone level are reported through `events`.
|
||||
pub(crate) fn spawn(
|
||||
outgoing: mpsc::UnboundedSender<OutPacket>,
|
||||
outgoing: mpsc::UnboundedSender<EncodedVoice>,
|
||||
events: mpsc::UnboundedSender<AudioEvent>,
|
||||
settings: AudioSettings,
|
||||
) -> AudioHandle {
|
||||
@@ -126,9 +128,9 @@ pub(crate) fn spawn(
|
||||
AudioHandle { tx }
|
||||
}
|
||||
|
||||
/// Audio of a watched stream in the mixer, under a made-up client id.
|
||||
/// Audio of a watched stream in the mixer, under a made-up talker id.
|
||||
struct StreamAudio {
|
||||
client: ClientId,
|
||||
client: TalkerId,
|
||||
/// RTP time and packet id of the last packet.
|
||||
last: Option<(u64, u64)>,
|
||||
}
|
||||
@@ -190,11 +192,7 @@ impl Pipeline {
|
||||
fn handle(&mut self, msg: AudioIn) {
|
||||
match msg {
|
||||
AudioIn::Packet(packet) => {
|
||||
let from = match packet.data().data() {
|
||||
AudioData::S2C { from, .. } | AudioData::S2CWhisper { from, .. } => *from,
|
||||
_ => return,
|
||||
};
|
||||
if let Err(error) = self.mixer.handle_packet(ClientId(from), packet) {
|
||||
if let Err(error) = self.mixer.handle_packet(packet) {
|
||||
debug!(%error, "dropped voice packet");
|
||||
}
|
||||
}
|
||||
@@ -241,8 +239,8 @@ impl Pipeline {
|
||||
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))
|
||||
let used: Vec<TalkerId> = self.streams.values().map(|s| s.client).collect();
|
||||
let Some(client) = (0..=u16::MAX).rev().map(TalkerId).find(|c| !used.contains(c))
|
||||
else {
|
||||
return;
|
||||
};
|
||||
@@ -263,19 +261,15 @@ impl Pipeline {
|
||||
}
|
||||
};
|
||||
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"),
|
||||
let packet = VoicePacket {
|
||||
talker: client,
|
||||
seq: id as u16,
|
||||
codec: VoiceCodec::Music,
|
||||
whisper: false,
|
||||
payload: data.to_vec(),
|
||||
};
|
||||
if let Err(error) = self.mixer.handle_packet(packet) {
|
||||
debug!(%error, "dropped stream audio packet");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -286,7 +280,7 @@ impl Pipeline {
|
||||
|
||||
/// 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)) {
|
||||
fn capture(&mut self, samples: &[f32], delay_ms: u32, send: &mut impl FnMut(EncodedVoice)) {
|
||||
self.processor.set_delay_ms(delay_ms);
|
||||
self.processed.clear();
|
||||
self.processor.capture(samples, &mut self.processed);
|
||||
@@ -308,7 +302,7 @@ impl Pipeline {
|
||||
}
|
||||
}
|
||||
|
||||
fn transmit(&mut self, frame: Vec<f32>, send: &mut impl FnMut(OutPacket)) {
|
||||
fn transmit(&mut self, frame: Vec<f32>, send: &mut impl FnMut(EncodedVoice)) {
|
||||
// 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);
|
||||
@@ -369,7 +363,7 @@ fn sanitize(mut settings: AudioSettings) -> AudioSettings {
|
||||
|
||||
fn run(
|
||||
rx: std_mpsc::Receiver<AudioIn>,
|
||||
outgoing: mpsc::UnboundedSender<OutPacket>,
|
||||
outgoing: mpsc::UnboundedSender<EncodedVoice>,
|
||||
events: mpsc::UnboundedSender<AudioEvent>,
|
||||
settings: AudioSettings,
|
||||
) {
|
||||
@@ -445,11 +439,10 @@ fn run(
|
||||
#[cfg(feature = "audio-device")]
|
||||
mod devices {
|
||||
use tracing::debug;
|
||||
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 voelin_audio::{AudioSettings, EncodedVoice};
|
||||
|
||||
use super::{DEVICE_LATENCY_MS, PLAYBACK_CAPACITY_MS, Pipeline};
|
||||
|
||||
@@ -509,7 +502,7 @@ mod devices {
|
||||
pub fn step(
|
||||
&mut self,
|
||||
pipeline: &mut Pipeline,
|
||||
send: &mut impl FnMut(OutPacket),
|
||||
send: &mut impl FnMut(EncodedVoice),
|
||||
error: &impl Fn(String),
|
||||
) -> bool {
|
||||
if let Some(event) = self.playback.poll() {
|
||||
@@ -575,16 +568,20 @@ mod tests {
|
||||
/// end-of-stream packets).
|
||||
fn capture(p: &mut Pipeline, samples: &[f32]) -> (usize, usize) {
|
||||
let (mut voice, mut end) = (0, 0);
|
||||
p.capture(samples, 0, &mut |packet: OutPacket| {
|
||||
// Header of 3 bytes (id + codec) for C2S audio.
|
||||
if packet.content().len() > 3 { voice += 1 } else { end += 1 }
|
||||
p.capture(samples, 0, &mut |packet: EncodedVoice| {
|
||||
if packet.is_end() { end += 1 } else { voice += 1 }
|
||||
});
|
||||
(voice, end)
|
||||
}
|
||||
|
||||
fn incoming(from: u16, id: u16, data: &[u8]) -> AudioIn {
|
||||
let packet = OutAudio::new(&AudioData::S2C { id, codec: CodecType::OpusVoice, from, data });
|
||||
AudioIn::Packet(InAudioBuf::try_new(Direction::S2C, packet.into_vec()).unwrap())
|
||||
fn incoming(from: u16, seq: u16, data: &[u8]) -> AudioIn {
|
||||
AudioIn::Packet(VoicePacket {
|
||||
talker: TalkerId(from),
|
||||
seq,
|
||||
codec: VoiceCodec::Voice,
|
||||
whisper: false,
|
||||
payload: data.to_vec(),
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -667,14 +664,14 @@ mod tests {
|
||||
energy(&out[out.len() / 2..])
|
||||
};
|
||||
let full = play(&mut p, 1);
|
||||
p.handle(AudioIn::ClientVolume { client: ClientId(2), volume: 0.5 });
|
||||
p.handle(AudioIn::ClientVolume { client: TalkerId(2), volume: 0.5 });
|
||||
let half = play(&mut p, 2);
|
||||
let ratio_db = 10.0 * (half / full).log10();
|
||||
assert!((ratio_db + 6.0).abs() < 1.0, "volume 0.5 gave {ratio_db} dB");
|
||||
p.handle(AudioIn::ClientMuted { client: ClientId(3), muted: true });
|
||||
p.handle(AudioIn::ClientMuted { client: TalkerId(3), muted: true });
|
||||
assert!(play(&mut p, 3) < 1e-8);
|
||||
p.handle(AudioIn::ClientLeft(ClientId(3)));
|
||||
assert!(!p.mixer.is_muted(ClientId(3)));
|
||||
p.handle(AudioIn::ClientLeft(TalkerId(3)));
|
||||
assert!(!p.mixer.is_muted(TalkerId(3)));
|
||||
}
|
||||
|
||||
/// While a priority speaker talks, another talker and a watched stream
|
||||
@@ -682,7 +679,7 @@ mod tests {
|
||||
#[test]
|
||||
fn priority_speaker() {
|
||||
let mut p = pipeline(TransmitMode::PushToTalk);
|
||||
p.handle(AudioIn::PrioritySpeakers { clients: vec![ClientId(2)], dimm_db: -12.0 });
|
||||
p.handle(AudioIn::PrioritySpeakers { clients: vec![TalkerId(2)], dimm_db: -12.0 });
|
||||
let mut voice = VoiceEncoder::new(VoiceCodec::Voice).unwrap();
|
||||
let mut priority = VoiceEncoder::new(VoiceCodec::Voice).unwrap();
|
||||
let mut music = VoiceEncoder::new(VoiceCodec::Music).unwrap();
|
||||
|
||||
@@ -4,21 +4,21 @@
|
||||
//! id (the CRC32 of the image, as TeamSpeak assigns them), so a lookup is a
|
||||
//! map access, and the same image seen on several servers or under
|
||||
//! several clients is one file. Pictures from the web (banners,
|
||||
//! [`crate::web`]) are named by the MD5 hash of their address. Keys are
|
||||
//! `web`) are named by the MD5 hash of their address. Keys are
|
||||
//! relative paths (`avatars/<md5>`, `icons/<id>`, `pictures/<md5>`).
|
||||
//!
|
||||
//! The cache is bounded by `cache.max_mb` (read on every insert; 0: no
|
||||
//! limit): the least recently used files go first. Use times survive
|
||||
//! restarts as the files' modification times.
|
||||
//!
|
||||
//! Downloads are deduplicated: [`Cache::fetch`] tells the first asker to
|
||||
//! Downloads are deduplicated: `Cache::fetch` tells the first asker to
|
||||
//! download (into a temporary path), later askers wait for the same
|
||||
//! download ([`Cache::finish`] answers them all).
|
||||
//! download (`Cache::finish` answers them all).
|
||||
//!
|
||||
//! A picture from the web keeps its host's validators (`ETag`,
|
||||
//! `Last-Modified`) next to it, in `validators/pictures/<md5>`: asked for
|
||||
//! again, it is downloaded only if it changed ([`Cache::validators`],
|
||||
//! [`Arrived::Unchanged`]).
|
||||
//! again, it is downloaded only if it changed (`Cache::validators`,
|
||||
//! `Arrived::Unchanged`).
|
||||
|
||||
use std::collections::{BTreeMap, HashMap};
|
||||
use std::fmt;
|
||||
@@ -184,6 +184,17 @@ pub(crate) const MAX_PICTURE_BYTES: u64 = 128 << 20;
|
||||
/// does not hold a download slot.
|
||||
pub(crate) const MIN_PICTURE_RATE: u64 = 8 << 10;
|
||||
|
||||
/// How long a picture of `size` bytes may take to arrive: a minute, plus
|
||||
/// its size at [`MIN_PICTURE_RATE`], so large banners arrive on slow
|
||||
/// links while a stalled transfer still ends.
|
||||
pub(crate) fn image_download_time(size: u64) -> std::time::Duration {
|
||||
std::time::Duration::from_secs(60 + size / MIN_PICTURE_RATE)
|
||||
}
|
||||
|
||||
/// How long the server may take to start an image transfer (a busy server
|
||||
/// answers the requests of a large channel tree in turn).
|
||||
pub(crate) const IMAGE_NEGOTIATION: std::time::Duration = std::time::Duration::from_secs(30);
|
||||
|
||||
/// The cache key of a picture on the web: only `http` and `https`
|
||||
/// addresses (blanks around one are not part of it).
|
||||
pub(crate) fn picture_key(url: &str) -> Option<String> {
|
||||
@@ -489,6 +500,15 @@ mod tests {
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn large_pictures_get_time_to_arrive() {
|
||||
let secs = std::time::Duration::from_secs;
|
||||
assert_eq!(image_download_time(0), secs(60));
|
||||
assert_eq!(image_download_time(100 << 10), secs(72));
|
||||
// The largest picture, at the slowest rate allowed.
|
||||
assert_eq!(image_download_time(MAX_PICTURE_BYTES), secs(60 + 16384));
|
||||
}
|
||||
|
||||
fn temp_dir(tag: &str) -> PathBuf {
|
||||
let dir = std::env::temp_dir().join(format!(
|
||||
"voelin-cache-{tag}-{}-{:?}",
|
||||
|
||||
@@ -453,10 +453,15 @@ mod tests {
|
||||
lookups
|
||||
}
|
||||
|
||||
/// `lookups` asking the real `/.well-known/tsgw` at `port`.
|
||||
/// `lookups` asking the real `/.well-known/tsgw` at `port`. A name is
|
||||
/// connected to through the system's resolver, except `localhost`: the
|
||||
/// servers of the tests listen on 127.0.0.1, and some machines resolve
|
||||
/// `localhost` to `::1` only. (The test cares that the gateway is asked at
|
||||
/// the name `localhost`, not what the resolver makes of it.)
|
||||
fn probing(mut lookups: Lookups, port: u16) -> Lookups {
|
||||
lookups.probe = Arc::new(move |name| {
|
||||
async move { timeout(PROBE_TIMEOUT, well_known(&name, port)).await.ok()?.ok() }.boxed()
|
||||
let host = if name == "localhost" { "127.0.0.1".to_owned() } else { name };
|
||||
async move { timeout(PROBE_TIMEOUT, well_known(&host, port)).await.ok()?.ok() }.boxed()
|
||||
});
|
||||
lookups
|
||||
}
|
||||
|
||||
@@ -32,13 +32,13 @@
|
||||
//! never downloaded). [`crate::Command::SetAvatar`] uploads our own.
|
||||
|
||||
use std::fmt;
|
||||
use std::future::Future;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use serde::Serialize;
|
||||
use tokio::io::{AsyncReadExt, AsyncSeekExt, AsyncWriteExt};
|
||||
use tokio::net::TcpStream;
|
||||
use tokio::io::{AsyncRead, AsyncReadExt, AsyncSeekExt, AsyncWrite, AsyncWriteExt};
|
||||
|
||||
/// Picked by the caller; the answer carries it back.
|
||||
pub type RequestId = u64;
|
||||
@@ -106,11 +106,11 @@ impl TransferState {
|
||||
}
|
||||
|
||||
/// Reports a transfer's states.
|
||||
pub(crate) type Report = Arc<dyn Fn(TransferState) + Send + Sync>;
|
||||
pub type Report = Arc<dyn Fn(TransferState) + Send + Sync>;
|
||||
|
||||
/// Where a running download writes.
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) enum Sink {
|
||||
pub enum Sink {
|
||||
/// Write `part` (appending with `append`), then rename it to `dest`.
|
||||
File {
|
||||
part: PathBuf,
|
||||
@@ -168,9 +168,10 @@ impl Progress<'_> {
|
||||
const CHUNK: usize = 64 * 1024;
|
||||
|
||||
/// Receive a file: `size` bytes in total, `offset` of them already in the
|
||||
/// sink. Reports `Started`, `Progress` and the final state.
|
||||
pub(crate) async fn download(
|
||||
mut stream: TcpStream,
|
||||
/// sink; `stream` carries the rest. Reports `Started`, `Progress` and the
|
||||
/// final state.
|
||||
pub(crate) async fn download<R: AsyncRead + Unpin>(
|
||||
mut stream: R,
|
||||
size: u64,
|
||||
offset: u64,
|
||||
sink: Sink,
|
||||
@@ -185,8 +186,8 @@ pub(crate) async fn download(
|
||||
});
|
||||
}
|
||||
|
||||
async fn receive(
|
||||
stream: &mut TcpStream,
|
||||
async fn receive<R: AsyncRead + Unpin>(
|
||||
stream: &mut R,
|
||||
size: u64,
|
||||
offset: u64,
|
||||
sink: &Sink,
|
||||
@@ -198,19 +199,22 @@ async fn receive(
|
||||
let mut done = offset;
|
||||
match sink {
|
||||
Sink::File { part, dest, append } => {
|
||||
// The directory and the file are made in one step, without a pause in
|
||||
// which the task could be stopped: a cancel stops the task, waits for
|
||||
// it and then removes the part file, so what the task made must be
|
||||
// there by then (a pending open on the blocking pool would not be).
|
||||
if let Some(dir) = part.parent().filter(|d| !d.as_os_str().is_empty()) {
|
||||
tokio::fs::create_dir_all(dir)
|
||||
.await
|
||||
.map_err(|e| format!("{}: {e}", dir.display()))?;
|
||||
std::fs::create_dir_all(dir).map_err(|e| format!("{}: {e}", dir.display()))?;
|
||||
}
|
||||
let mut file = tokio::fs::OpenOptions::new()
|
||||
.create(true)
|
||||
.write(true)
|
||||
.append(*append)
|
||||
.truncate(!*append)
|
||||
.open(part)
|
||||
.await
|
||||
.map_err(|e| format!("{}: {e}", part.display()))?;
|
||||
let mut file = tokio::fs::File::from_std(
|
||||
std::fs::OpenOptions::new()
|
||||
.create(true)
|
||||
.write(true)
|
||||
.append(*append)
|
||||
.truncate(!*append)
|
||||
.open(part)
|
||||
.map_err(|e| format!("{}: {e}", part.display()))?,
|
||||
);
|
||||
let received = async {
|
||||
while done < size {
|
||||
let n = stream.read(&mut buf).await.map_err(|e| e.to_string())?;
|
||||
@@ -253,26 +257,34 @@ async fn receive(
|
||||
}
|
||||
}
|
||||
|
||||
/// Send `file` from `offset` (`size` bytes in total). Reports `Started`,
|
||||
/// `Progress` and the final state.
|
||||
pub(crate) async fn upload(
|
||||
mut stream: TcpStream,
|
||||
/// Send `file` from `offset` (`size` bytes in total) into `writer`, then end
|
||||
/// it and wait for `stored`, which resolves once the server has the file.
|
||||
/// Reports `Started`, `Progress` and the final state.
|
||||
pub(crate) async fn upload_to<W, F>(
|
||||
mut writer: W,
|
||||
stored: F,
|
||||
file: PathBuf,
|
||||
size: u64,
|
||||
offset: u64,
|
||||
progress_every: Duration,
|
||||
report: Report,
|
||||
) {
|
||||
) where
|
||||
W: AsyncWrite + Unpin,
|
||||
F: Future<Output = Result<(), String>>,
|
||||
{
|
||||
report(TransferState::Started { size, offset });
|
||||
let result = send(&mut stream, &file, size, offset, progress_every, &report).await;
|
||||
let result = match send(&mut writer, &file, size, offset, progress_every, &report).await {
|
||||
Ok(()) => stored.await,
|
||||
Err(e) => Err(e),
|
||||
};
|
||||
report(match result {
|
||||
Ok(()) => TransferState::Done { size, path: Some(file), data: None },
|
||||
Err(e) => TransferState::Failed(e),
|
||||
});
|
||||
}
|
||||
|
||||
async fn send(
|
||||
stream: &mut TcpStream,
|
||||
async fn send<W: AsyncWrite + Unpin>(
|
||||
stream: &mut W,
|
||||
path: &Path,
|
||||
size: u64,
|
||||
offset: u64,
|
||||
@@ -300,8 +312,6 @@ async fn send(
|
||||
}
|
||||
stream.flush().await.map_err(|e| e.to_string())?;
|
||||
stream.shutdown().await.map_err(|e| e.to_string())?;
|
||||
// The server closes the connection once it has everything.
|
||||
let _ = tokio::time::timeout(Duration::from_secs(30), stream.read(&mut buf[..1])).await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -421,7 +431,7 @@ fn percent_decode(text: &str) -> Option<String> {
|
||||
mod tests {
|
||||
use std::sync::Mutex;
|
||||
|
||||
use tokio::net::TcpListener;
|
||||
use tokio::net::{TcpListener, TcpStream};
|
||||
|
||||
use super::*;
|
||||
|
||||
@@ -562,7 +572,8 @@ mod tests {
|
||||
});
|
||||
let (report, states) = recorder();
|
||||
let stream = TcpStream::connect(addr).await.unwrap();
|
||||
upload(stream, file.clone(), 10, 4, Duration::ZERO, report).await;
|
||||
let (_, write) = tokio::io::split(stream);
|
||||
upload_to(write, async { Ok(()) }, file.clone(), 10, 4, Duration::ZERO, report).await;
|
||||
assert_eq!(server.await.unwrap(), b"456789");
|
||||
assert!(matches!(states.lock().unwrap().last(), Some(TransferState::Done { .. })));
|
||||
assert_eq!(md5_file(&file).unwrap(), "781e5e245d69b566979b86e28d23f2c7");
|
||||
|
||||
@@ -61,6 +61,7 @@ use voelin_gateway_proto::{
|
||||
HistoryEntry, HistoryQuery, PermRule, PermRuleInfo, PinInfo, RsvpStatus, StreamEntry,
|
||||
StreamSpec, TopicInfo, UserRef,
|
||||
};
|
||||
use voelin_identity::IdentityBlob;
|
||||
use voelin_model::{ChannelId, ChatTarget, Presence};
|
||||
use voelin_store::WriteOutcome;
|
||||
|
||||
@@ -91,13 +92,23 @@ pub(crate) enum GatewayEvent {
|
||||
Disconnected(Option<String>),
|
||||
}
|
||||
|
||||
/// The TeamSpeak identity of a blob, or why a gateway cannot be logged in to
|
||||
/// with it.
|
||||
fn login_identity(blob: &IdentityBlob) -> Result<tsclientlib::Identity, String> {
|
||||
crate::ts::identity::from_blob(blob).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
/// Connect to a gateway (`ws://…/v1` or `wss://…/v1`) and log in with a
|
||||
/// TeamSpeak identity.
|
||||
/// TeamSpeak identity (a blob of kind `teamspeak`, see
|
||||
/// [`crate::ts::identity::to_blob`]; one that is none is refused as
|
||||
/// [`ErrorCode::AuthFailed`], the way the gateway would).
|
||||
pub async fn connect(
|
||||
url: &str,
|
||||
identity: &tsclientlib::Identity,
|
||||
identity: &IdentityBlob,
|
||||
) -> Result<(GatewayClient, mpsc::UnboundedReceiver<Push>), ClientError> {
|
||||
connect_watched(url, identity, &Progress::default()).await
|
||||
let identity = login_identity(identity)
|
||||
.map_err(|message| ClientError::Gateway { code: ErrorCode::AuthFailed, message })?;
|
||||
connect_watched(url, &identity, &Progress::default()).await
|
||||
}
|
||||
|
||||
/// [`connect`], telling `progress` each step (for the log).
|
||||
@@ -114,10 +125,19 @@ async fn connect_watched(
|
||||
/// logs in.
|
||||
pub(crate) async fn run(
|
||||
mut urls: Vec<String>,
|
||||
identity: tsclientlib::Identity,
|
||||
identity: IdentityBlob,
|
||||
mut commands: mpsc::UnboundedReceiver<GatewayCmd>,
|
||||
events: mpsc::UnboundedSender<GatewayEvent>,
|
||||
) {
|
||||
// An identity that cannot be read will not be tomorrow: like a refused login.
|
||||
let identity = match login_identity(&identity) {
|
||||
Ok(identity) => identity,
|
||||
Err(reason) => {
|
||||
debug!(%reason, "gateway: the identity cannot be read");
|
||||
let _ = events.send(GatewayEvent::Disconnected(Some(reason)));
|
||||
return;
|
||||
}
|
||||
};
|
||||
// A gateway that is away (down, restarting, a network change, a proxy
|
||||
// in front of it that fails) or cannot log us in yet (it does not know
|
||||
// the identity before voice connected once, its server is restarting)
|
||||
@@ -274,20 +294,24 @@ pub(crate) struct Observed {
|
||||
}
|
||||
|
||||
impl Observed {
|
||||
pub(crate) fn new(urls: &[String], identity: &tsclientlib::Identity) -> Self {
|
||||
Self {
|
||||
urls: urls.to_vec(),
|
||||
key: identity.key().to_pub().to_ts(),
|
||||
counter: identity.counter(),
|
||||
nudged: None,
|
||||
pub(crate) fn new(urls: &[String], identity: &IdentityBlob) -> Self {
|
||||
let (key, counter) = Self::of(identity);
|
||||
Self { urls: urls.to_vec(), key, counter, nudged: None }
|
||||
}
|
||||
|
||||
/// The public key and the counter of an identity: an identity that cannot be
|
||||
/// read has neither (and so is the same as any other that cannot).
|
||||
fn of(identity: &IdentityBlob) -> (String, u64) {
|
||||
match login_identity(identity) {
|
||||
Ok(identity) => (identity.key().to_pub().to_ts(), identity.counter()),
|
||||
Err(_) => (String::new(), 0),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether this is what is observed with.
|
||||
pub(crate) fn same(&self, urls: &[String], identity: &tsclientlib::Identity) -> bool {
|
||||
self.urls == urls
|
||||
&& self.counter == identity.counter()
|
||||
&& self.key == identity.key().to_pub().to_ts()
|
||||
pub(crate) fn same(&self, urls: &[String], identity: &IdentityBlob) -> bool {
|
||||
let (key, counter) = Self::of(identity);
|
||||
self.urls == urls && self.counter == counter && self.key == key
|
||||
}
|
||||
|
||||
/// Whether to try again now ([`GatewayCmd::RetryNow`]): not twice
|
||||
@@ -1182,15 +1206,16 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn the_same_observation_is_nudged_at_most_every_5_s() {
|
||||
let blob = crate::ts::identity::to_blob;
|
||||
let identity = tsclientlib::Identity::create();
|
||||
let urls = vec!["ws://gw.example.test:7788/v1".to_owned()];
|
||||
let mut observed = Observed::new(&urls, &identity);
|
||||
assert!(observed.same(&urls, &identity));
|
||||
assert!(!observed.same(&["wss://gw.example.test/v1".to_owned()], &identity));
|
||||
assert!(!observed.same(&urls, &tsclientlib::Identity::create()));
|
||||
let mut observed = Observed::new(&urls, &blob(&identity));
|
||||
assert!(observed.same(&urls, &blob(&identity)));
|
||||
assert!(!observed.same(&["wss://gw.example.test/v1".to_owned()], &blob(&identity)));
|
||||
assert!(!observed.same(&urls, &blob(&tsclientlib::Identity::create())));
|
||||
// Its security level raised: logged in with the new counter.
|
||||
let raised = tsclientlib::Identity::new(identity.key().clone(), identity.counter() + 1);
|
||||
assert!(!observed.same(&urls, &raised));
|
||||
assert!(!observed.same(&urls, &blob(&raised)));
|
||||
let now = Instant::now();
|
||||
assert!(observed.nudge_at(now));
|
||||
assert!(!observed.nudge_at(now + Duration::from_secs(4)));
|
||||
|
||||
@@ -3,7 +3,10 @@
|
||||
//! The UI talks to an [`Engine`] with [`Command`]s and receives [`Event`]s.
|
||||
//! Each server the user works with is a session with up to three sources:
|
||||
//!
|
||||
//! - **voice**: a normal client connection (visible, can talk)
|
||||
//! - **voice**: a normal client connection (visible, can talk): a
|
||||
//! `voelin_proto::link::Session` that the connector of the server's address
|
||||
//! makes ([`Backends`], and [`ts::TsConnector`] for TeamSpeak servers; see
|
||||
//! [`link`])
|
||||
//! - **gateway**: a `tsgw` gateway (invisible presence, relayed chat)
|
||||
//! - **query**: the user's own ServerQuery credentials (same, without a gateway)
|
||||
//!
|
||||
@@ -16,9 +19,9 @@
|
||||
//! [`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`), and the Stream Studio (scenes of
|
||||
//! are in `media` (feature `media`), and the Stream Studio (scenes of
|
||||
//! sources composited into one stream, recording, a replay buffer, WHIP) in
|
||||
//! [`studio`].
|
||||
//! `studio`.
|
||||
//!
|
||||
//! Settings are a [`settings::Settings`] service: typed keys, runtime
|
||||
//! values stored in the client database ahead of command line, config file
|
||||
@@ -45,14 +48,13 @@
|
||||
//! volume) are engine-wide ([`contacts`]).
|
||||
|
||||
mod audio;
|
||||
mod book;
|
||||
pub mod cache;
|
||||
pub mod contacts;
|
||||
pub mod discover;
|
||||
pub mod files;
|
||||
pub mod gateway;
|
||||
pub mod history;
|
||||
pub mod identity;
|
||||
pub mod link;
|
||||
#[cfg(feature = "media")]
|
||||
pub mod media;
|
||||
pub mod offline;
|
||||
@@ -61,22 +63,21 @@ mod route;
|
||||
mod session;
|
||||
pub mod settings;
|
||||
pub mod stream;
|
||||
mod stream_types;
|
||||
#[cfg(feature = "media")]
|
||||
pub mod studio;
|
||||
pub mod versions;
|
||||
mod voice;
|
||||
pub mod ts;
|
||||
mod web;
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
|
||||
use tokio::sync::{broadcast, mpsc, watch};
|
||||
use tokio::sync::{broadcast, mpsc};
|
||||
pub use voelin_audio::settings::TransmitMode;
|
||||
pub use voelin_audio::{AudioSettings, ProcessingSettings, VadSettings};
|
||||
use voelin_model::{
|
||||
Capabilities, ChannelId, ChatMessage, ChatTarget, FileRef, GroupInfo, Presence, ServerDetails,
|
||||
ServerFlavor,
|
||||
};
|
||||
|
||||
use crate::audio::{AudioEvent, AudioHandle, AudioIn};
|
||||
@@ -88,14 +89,14 @@ pub use files::{Bytes, DownloadTo, FileEntry, RequestId, TransferId, TransferSta
|
||||
pub use gateway::{GatewayRequest, GatewayUpdate};
|
||||
use history::SharedHistory;
|
||||
pub use history::{History, HistoryMessage, HistorySource};
|
||||
pub use link::{Backends, VoiceOptions};
|
||||
pub use offline::{OfflineMessage, OfflineMessageInfo};
|
||||
pub use query::{QueryLogin, QueryTransport};
|
||||
pub use route::{ChatRoute, Dedup, route_chat};
|
||||
use settings::{SettingChange, Settings, SharedSettings};
|
||||
use stream::{EncodedFrame, LayerId, LayerSpec, StreamInfo, StreamSetup, ViewerInfo};
|
||||
pub use stream::{StreamFrame, StreamSink, StreamState, WatchState};
|
||||
use voelin_stream::{
|
||||
EncodedFrame, LayerId, LayerSpec, SrtpProfile, StreamInfo, StreamSetup, ViewerInfo,
|
||||
};
|
||||
pub use voice::VoiceOptions;
|
||||
pub use voelin_identity::IdentityBlob;
|
||||
/// Banners are downloaded and shown by the same rule.
|
||||
pub use web::is_svg;
|
||||
/// Pictures from the web go through the desktop's proxy (set at startup).
|
||||
@@ -110,13 +111,6 @@ pub const POKE_MESSAGE_MAX: usize = 100;
|
||||
/// What the UI asks for.
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum Command {
|
||||
/// Main account proof for every current and future voice connection.
|
||||
SetMytsIdentity(Option<Arc<tsproto::myts::Identity>>),
|
||||
/// What voice servers are shown of the main account (its avatar and
|
||||
/// badges with their certificates, its User Tag; TeamSpeak 6): sent to
|
||||
/// every connection that presents the account's myTS ID, once connected
|
||||
/// and when it changes; cleared on a sign-out.
|
||||
SetMytsData(Option<Arc<tsclientlib::MytsData>>),
|
||||
ConnectVoice {
|
||||
session: SessionId,
|
||||
options: Box<VoiceOptions>,
|
||||
@@ -132,12 +126,15 @@ pub enum Command {
|
||||
ObserveGateway {
|
||||
session: SessionId,
|
||||
urls: Vec<String>,
|
||||
identity: Box<tsclientlib::Identity>,
|
||||
/// The TeamSpeak identity to log in with ([`ts::identity::to_blob`]).
|
||||
/// One that is none, or cannot be read, ends the observation with
|
||||
/// its reason.
|
||||
identity: Box<IdentityBlob>,
|
||||
},
|
||||
/// Invisible presence and relay chat with own ServerQuery credentials.
|
||||
ObserveQuery {
|
||||
session: SessionId,
|
||||
connect: Box<voelin_query::Connect>,
|
||||
connect: Box<QueryLogin>,
|
||||
},
|
||||
StopObserving {
|
||||
session: SessionId,
|
||||
@@ -248,11 +245,13 @@ pub enum Command {
|
||||
session: SessionId,
|
||||
layers: Vec<LayerSpec>,
|
||||
},
|
||||
/// SRTP protection profiles for stream connections, in order of
|
||||
/// preference (a user setting; empty: the default,
|
||||
/// `SrtpProfile::DEFAULT_ORDER`). Applies to connections made from now
|
||||
/// on, in all sessions and those started later.
|
||||
SetSrtpProfiles(Vec<SrtpProfile>),
|
||||
/// SRTP protection profiles for stream connections by name (RFC 5764 and
|
||||
/// RFC 7714: `AEAD_AES_128_GCM`, `AES128_CM_SHA1_80`, ...; names the stream
|
||||
/// transport does not know are left out), in order of preference (the
|
||||
/// `stream.srtp_profiles` setting). Empty: the transport's default order.
|
||||
/// Applies to connections made from now on, in all sessions and those
|
||||
/// started later.
|
||||
SetSrtpProfiles(Vec<String>),
|
||||
/// Watch a stream from [`Event::StreamsChanged`]. Frames arrive through
|
||||
/// [`Engine::subscribe_frames`].
|
||||
WatchStream {
|
||||
@@ -270,7 +269,7 @@ pub enum Command {
|
||||
},
|
||||
/// The video of a watched stream arrives, but none of it decodes: watch
|
||||
/// it in another codec the streamer offered, if there is one (a new
|
||||
/// connection without this one). [`media::Viewer`] sends it.
|
||||
/// connection without this one). `media::Viewer` sends it.
|
||||
StreamUndecodable {
|
||||
session: SessionId,
|
||||
stream_id: String,
|
||||
@@ -507,6 +506,30 @@ pub enum JoinFailure {
|
||||
Other(String),
|
||||
}
|
||||
|
||||
/// The software on the other end of a session, as its link names it. It is
|
||||
/// for people to read; nothing branches on it (what the server can do is
|
||||
/// [`Capabilities`]).
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct BackendInfo {
|
||||
/// What it is called ("TeamSpeak 6"); empty when it was not recognised.
|
||||
pub product: String,
|
||||
/// Its version as the product shows it ("6.0.0-beta13.1"); what the
|
||||
/// server said, as it is, when `product` is empty.
|
||||
pub version: String,
|
||||
}
|
||||
|
||||
impl BackendInfo {
|
||||
/// For a sentence: the product and the version, whichever there are
|
||||
/// ("TeamSpeak 6 6.0.0-beta13.1", "TeamSpeak 3", "custom 9").
|
||||
pub fn label(&self) -> String {
|
||||
match (self.product.is_empty(), self.version.is_empty()) {
|
||||
(false, false) => format!("{} {}", self.product, self.version),
|
||||
(false, true) => self.product.clone(),
|
||||
(true, _) => self.version.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What the engine reports.
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum Event {
|
||||
@@ -514,10 +537,12 @@ pub enum Event {
|
||||
session: SessionId,
|
||||
state: SessionState,
|
||||
},
|
||||
/// The server answered: its name, the software it runs and what that
|
||||
/// software can do (the UI hides what it cannot).
|
||||
ServerInfo {
|
||||
session: SessionId,
|
||||
name: String,
|
||||
flavor: ServerFlavor,
|
||||
backend: BackendInfo,
|
||||
capabilities: Capabilities,
|
||||
},
|
||||
/// Full presence of the session (the UI rebuilds its view from it).
|
||||
@@ -760,8 +785,18 @@ impl Engine {
|
||||
}
|
||||
|
||||
/// Start the engine on the current tokio runtime with `settings` and
|
||||
/// chat `history`.
|
||||
/// chat `history`, connecting voice with the engine's own connectors
|
||||
/// ([`Backends::default`]: TeamSpeak 3 and 6).
|
||||
pub fn start_with(settings: Settings, history: History) -> Self {
|
||||
Self::start_with_backends(settings, history, Backends::default())
|
||||
}
|
||||
|
||||
/// Start the engine on the current tokio runtime with `settings` and
|
||||
/// chat `history`, connecting voice with the connectors in `backends`:
|
||||
/// the one for the scheme of a session's address makes its
|
||||
/// `voelin_proto::link::Session`.
|
||||
pub fn start_with_backends(settings: Settings, history: History, backends: Backends) -> Self {
|
||||
let link = Arc::new(link::SessionLink::new(backends));
|
||||
let (commands, rx) = mpsc::unbounded_channel();
|
||||
let (events, _) = broadcast::channel(4096);
|
||||
// About a minute of one watched stream.
|
||||
@@ -773,7 +808,7 @@ impl Engine {
|
||||
history,
|
||||
cache: SharedCache::new(Cache::new(Cache::default_dir())),
|
||||
};
|
||||
tokio::spawn(run(rx, events.clone(), frames.clone(), shared.clone()));
|
||||
tokio::spawn(run(rx, events.clone(), frames.clone(), shared.clone(), link));
|
||||
Self { commands, events, frames, runtime: tokio::runtime::Handle::current(), shared }
|
||||
}
|
||||
|
||||
@@ -857,19 +892,18 @@ async fn run(
|
||||
events: broadcast::Sender<Event>,
|
||||
frames: broadcast::Sender<StreamFrame>,
|
||||
engine: Shared,
|
||||
link: Arc<link::SessionLink>,
|
||||
) {
|
||||
let Shared { settings: shared, history, cache, contacts } = engine.clone();
|
||||
// Before any command: a contact set meanwhile would be lost.
|
||||
contacts.load().await;
|
||||
let mut sessions: HashMap<SessionId, session::SessionHandle> = HashMap::new();
|
||||
let (myts_identity, _) = watch::channel(None);
|
||||
let (myts_data, _) = watch::channel(None);
|
||||
let mut current = shared.current();
|
||||
// Pruning: at start, then hourly (and when the setting changes).
|
||||
let mut prune = tokio::time::interval(std::time::Duration::from_secs(3600));
|
||||
let mut changes = current.subscribe();
|
||||
let mut settings = AudioSettings::default();
|
||||
let mut srtp_profiles: Option<Vec<SrtpProfile>> = None;
|
||||
let mut srtp_profiles: Option<Vec<String>> = None;
|
||||
let mut mic_test: Option<AudioHandle> = None;
|
||||
loop {
|
||||
let input = tokio::select! {
|
||||
@@ -908,29 +942,6 @@ async fn run(
|
||||
},
|
||||
};
|
||||
let id = match command {
|
||||
Command::SetMytsIdentity(identity) => {
|
||||
// Still no account is no change: every notification restarts
|
||||
// handshakes and sends `updatemytsid` on every connection. Any
|
||||
// account is (each connection's proof is signed anew).
|
||||
myts_identity.send_if_modified(|current| {
|
||||
if current.is_none() && identity.is_none() {
|
||||
return false;
|
||||
}
|
||||
*current = identity;
|
||||
true
|
||||
});
|
||||
continue;
|
||||
}
|
||||
Command::SetMytsData(data) => {
|
||||
myts_data.send_if_modified(|current| {
|
||||
if *current == data {
|
||||
return false;
|
||||
}
|
||||
*current = data;
|
||||
true
|
||||
});
|
||||
continue;
|
||||
}
|
||||
Command::SetAudioSettings(new) => {
|
||||
settings = (*new).clone();
|
||||
for s in sessions.values() {
|
||||
@@ -1006,8 +1017,7 @@ async fn run(
|
||||
frames.clone(),
|
||||
settings.clone(),
|
||||
engine.clone(),
|
||||
myts_identity.subscribe(),
|
||||
myts_data.subscribe(),
|
||||
link.clone(),
|
||||
);
|
||||
if let Some(profiles) = &srtp_profiles {
|
||||
s.send(Command::SetSrtpProfiles(profiles.clone()));
|
||||
@@ -1086,9 +1096,7 @@ fn command_session(command: &Command) -> SessionId {
|
||||
| Command::DeleteOfflineMessage { session, .. }
|
||||
| Command::SetOfflineMessageRead { session, .. }
|
||||
| Command::CloseSession { session } => *session,
|
||||
Command::SetMytsIdentity(_)
|
||||
| Command::SetMytsData(_)
|
||||
| Command::SetAudioSettings(_)
|
||||
Command::SetAudioSettings(_)
|
||||
| Command::SetSrtpProfiles(_)
|
||||
| Command::TestMicrophone { .. }
|
||||
| Command::SetSetting { .. }
|
||||
@@ -1111,3 +1119,21 @@ fn command_session(command: &Command) -> SessionId {
|
||||
fn one_rustls_crypto_provider() {
|
||||
let _ = rustls::ClientConfig::builder();
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::BackendInfo;
|
||||
|
||||
#[test]
|
||||
fn a_backend_reads_as_its_product_and_version() {
|
||||
let backend = |product: &str, version: &str| BackendInfo {
|
||||
product: product.into(),
|
||||
version: version.into(),
|
||||
};
|
||||
assert_eq!(backend("TeamSpeak 6", "6.0.0-beta13.1").label(), "TeamSpeak 6 6.0.0-beta13.1");
|
||||
assert_eq!(backend("TeamSpeak 3", "").label(), "TeamSpeak 3");
|
||||
// Not recognised: the version string alone, or nothing.
|
||||
assert_eq!(backend("", "custom 9").label(), "custom 9");
|
||||
assert_eq!(BackendInfo::default().label(), "");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,265 @@
|
||||
//! The registry of the engine's connectors, by address scheme.
|
||||
//!
|
||||
//! A session's voice source is a `voelin_proto::link::Session`
|
||||
//! (`docs/session-seam.md` section 4.1). Which backend makes it is the
|
||||
//! scheme of the address: [`Backends`] holds the plain connectors of
|
||||
//! `voelin_proto::link::Connectors` (the Voelin protocol's QUIC connector
|
||||
//! later, `FakeConnector` in tests) and the in-process connectors, which
|
||||
//! also hand the engine what a `Session` has no room for yet (the TeamSpeak 6
|
||||
//! stream task, [`StreamPort`]).
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use tokio::sync::mpsc;
|
||||
use voelin_proto::link::{
|
||||
AccountAgent, BoxFuture, ConnectParams, Connected, Connector, Connectors, HostIdentity,
|
||||
HostTrust, SessionError,
|
||||
};
|
||||
use voelin_stream::PeerConfig;
|
||||
|
||||
use super::LinkCtx;
|
||||
use crate::stream::{OwnStreamEvent, StreamCmd};
|
||||
use crate::ts::TsConnector;
|
||||
|
||||
/// The scheme of the TeamSpeak servers a bookmark names without one.
|
||||
pub(crate) const TEAMSPEAK_SCHEME: &str = "ts3server";
|
||||
|
||||
/// What comes back from the stream task of a connection that has one.
|
||||
#[derive(Debug)]
|
||||
pub(crate) enum StreamEvent {
|
||||
/// Our own stream's life, for the gateway directory.
|
||||
OwnStream(OwnStreamEvent),
|
||||
/// An Opus frame of a watched stream, for the audio thread.
|
||||
Audio { stream: String, time: u64, data: Arc<[u8]> },
|
||||
/// A watched stream ended.
|
||||
AudioEnded(String),
|
||||
}
|
||||
|
||||
/// The in-process channel of TeamSpeak 6 streams past the `Session` trait
|
||||
/// (`docs/session-seam.md` section 6.4): TeamSpeak 6 streams are peer to peer
|
||||
/// and not v1 entities yet, so the commands go to the connection's stream
|
||||
/// task and its events come back here.
|
||||
pub(crate) struct StreamPort {
|
||||
send: Box<dyn Fn(StreamCmd) + Send + Sync>,
|
||||
/// What the stream task reports.
|
||||
pub(crate) events: mpsc::UnboundedReceiver<StreamEvent>,
|
||||
}
|
||||
|
||||
impl StreamPort {
|
||||
/// A port whose commands go to `send`.
|
||||
pub(crate) fn new(
|
||||
send: impl Fn(StreamCmd) + Send + Sync + 'static,
|
||||
events: mpsc::UnboundedReceiver<StreamEvent>,
|
||||
) -> Self {
|
||||
Self { send: Box::new(send), events }
|
||||
}
|
||||
|
||||
/// Give the stream task a command.
|
||||
pub(crate) fn send(&self, cmd: StreamCmd) {
|
||||
(self.send)(cmd);
|
||||
}
|
||||
}
|
||||
|
||||
/// What an in-process backend needs besides the connect parameters.
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct LocalCtx {
|
||||
/// The session's side of the engine: its id, event bus, frames and
|
||||
/// settings.
|
||||
pub(crate) link: LinkCtx,
|
||||
/// Open the audio devices (the stream task plays what streams carry).
|
||||
pub(crate) audio: bool,
|
||||
/// Network settings for stream peer connections.
|
||||
pub(crate) stream_peer: PeerConfig,
|
||||
}
|
||||
|
||||
impl LocalCtx {
|
||||
pub(crate) fn new(link: LinkCtx, audio: bool, stream_peer: PeerConfig) -> Self {
|
||||
Self { link, audio, stream_peer }
|
||||
}
|
||||
|
||||
/// A context for a connection made outside an engine (a test or a tool
|
||||
/// that calls a connector itself): a session of its own that nobody
|
||||
/// listens to.
|
||||
pub(crate) fn standalone() -> Self {
|
||||
let (events, _) = tokio::sync::broadcast::channel(16);
|
||||
let (frames, _) = tokio::sync::broadcast::channel(16);
|
||||
let link = LinkCtx {
|
||||
session: 0,
|
||||
events,
|
||||
frames,
|
||||
settings: crate::settings::SharedSettings::new(crate::settings::Settings::in_memory()),
|
||||
};
|
||||
Self { link, audio: false, stream_peer: PeerConfig::default() }
|
||||
}
|
||||
}
|
||||
|
||||
/// A connection an in-process connector made.
|
||||
pub(crate) struct LocalConnected {
|
||||
pub(crate) connected: Connected,
|
||||
/// The stream task's port, for a backend that runs one.
|
||||
pub(crate) streams: Option<StreamPort>,
|
||||
}
|
||||
|
||||
/// A connector that runs in this process and can use the engine's context
|
||||
/// ([`LocalCtx`]); its sessions may come with a [`StreamPort`].
|
||||
pub(crate) trait LocalConnector: Connector {
|
||||
/// Whether this connector serves addresses of `scheme`. By default, the
|
||||
/// schemes it names.
|
||||
fn accepts(&self, scheme: &str) -> bool {
|
||||
self.schemes().contains(&scheme)
|
||||
}
|
||||
|
||||
/// Connect with the engine's context.
|
||||
fn connect_local(
|
||||
&self,
|
||||
params: ConnectParams,
|
||||
ctx: LocalCtx,
|
||||
) -> BoxFuture<Result<LocalConnected, SessionError>>;
|
||||
}
|
||||
|
||||
/// The connectors of an engine, found by the scheme of an address.
|
||||
///
|
||||
/// A scheme served by an in-process connector goes to it, one served by a
|
||||
/// plain connector ([`Backends::register`]) to that. An address without a
|
||||
/// scheme is a TeamSpeak bookmark and is taken for a `ts3server` one.
|
||||
#[derive(Clone)]
|
||||
pub struct Backends {
|
||||
connectors: Connectors,
|
||||
locals: Vec<Arc<dyn LocalConnector>>,
|
||||
account: Option<Arc<dyn AccountAgent>>,
|
||||
/// The connections' trust in hosts that are neither valid nor pinned.
|
||||
trust: Option<Arc<dyn HostTrust>>,
|
||||
}
|
||||
|
||||
impl Default for Backends {
|
||||
/// The engine's connectors: TeamSpeak 3 and 6 (`ts3server://` and
|
||||
/// `teamspeak://`, and an address without a scheme).
|
||||
fn default() -> Self {
|
||||
let mut backends = Self::empty();
|
||||
backends.register_teamspeak(TsConnector::new());
|
||||
backends
|
||||
}
|
||||
}
|
||||
|
||||
impl Backends {
|
||||
/// No connector at all. ([`Backends::default`] has the TeamSpeak one.)
|
||||
pub fn empty() -> Self {
|
||||
Self { connectors: Connectors::default(), locals: Vec::new(), account: None, trust: None }
|
||||
}
|
||||
|
||||
/// Register a connector for the schemes it names.
|
||||
pub fn register(&mut self, connector: Arc<dyn Connector>) {
|
||||
self.connectors.register(connector);
|
||||
}
|
||||
|
||||
pub(crate) fn register_local(&mut self, connector: Arc<dyn LocalConnector>) {
|
||||
self.locals.push(connector);
|
||||
}
|
||||
|
||||
/// Register the TeamSpeak connector for the schemes it names
|
||||
/// (`ts3server`, `teamspeak`, and addresses without a scheme).
|
||||
/// [`Backends::default`] registers one of its own; register yours to keep a
|
||||
/// clone of it, whose [`TsConnector::set_myts_identity`] and
|
||||
/// [`TsConnector::set_myts_data`] set the main myTeamSpeak account for every
|
||||
/// connection it makes.
|
||||
pub fn register_teamspeak(&mut self, connector: TsConnector) {
|
||||
self.register_local(Arc::new(connector));
|
||||
}
|
||||
|
||||
/// The device's Voelin account, which every connect hands the connector as
|
||||
/// `ConnectParams::account`. No connector reads it yet: the TeamSpeak
|
||||
/// connector takes the myTeamSpeak account it presents from its own setters
|
||||
/// ([`TsConnector::set_myts_identity`], [`TsConnector::set_myts_data`]), and a
|
||||
/// Voelin host's connector (the QUIC one, for its certificate) does not exist
|
||||
/// yet. Follow-up H4 of `docs/session-seam.md` (11.2) moves the myTeamSpeak
|
||||
/// proof from those setters to this hook. None is the default.
|
||||
pub fn set_account(&mut self, agent: Option<Arc<dyn AccountAgent>>) {
|
||||
self.account = agent;
|
||||
}
|
||||
|
||||
/// The account agent, if one was set ([`Backends::set_account`]).
|
||||
pub fn account(&self) -> Option<Arc<dyn AccountAgent>> {
|
||||
self.account.clone()
|
||||
}
|
||||
|
||||
/// Decide about hosts that are neither valid nor pinned. The default
|
||||
/// refuses them: there is no trust dialog yet, and TeamSpeak has no host
|
||||
/// key.
|
||||
pub fn set_trust(&mut self, trust: Option<Arc<dyn HostTrust>>) {
|
||||
self.trust = trust;
|
||||
}
|
||||
|
||||
pub(crate) fn trust(&self) -> Arc<dyn HostTrust> {
|
||||
self.trust.clone().unwrap_or_else(|| Arc::new(RefuseUnknownHosts))
|
||||
}
|
||||
|
||||
/// The scheme of an address, lowercase; a TeamSpeak bookmark's when there
|
||||
/// is none.
|
||||
pub(crate) fn scheme(address: &str) -> String {
|
||||
match address.split_once("://") {
|
||||
Some((scheme, _)) => scheme.to_ascii_lowercase(),
|
||||
None => TEAMSPEAK_SCHEME.to_owned(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Open a session to `params.address` with the connector of its scheme.
|
||||
pub(crate) fn connect(
|
||||
&self,
|
||||
params: ConnectParams,
|
||||
ctx: LocalCtx,
|
||||
) -> BoxFuture<Result<LocalConnected, SessionError>> {
|
||||
let scheme = Self::scheme(¶ms.address);
|
||||
if let Some(local) = self.locals.iter().find(|c| c.accepts(&scheme)) {
|
||||
return local.connect_local(params, ctx);
|
||||
}
|
||||
// Not `Connectors::connect`, which names the whole address when none serves it:
|
||||
// the text is shown, and a TeamSpeak link carries a channel password.
|
||||
let Some(connector) = self.connectors.for_address(¶ms.address) else {
|
||||
let shown = without_query(¶ms.address).to_owned();
|
||||
return Box::pin(async move {
|
||||
Err(SessionError::Protocol(format!("no connector for {shown}")))
|
||||
});
|
||||
};
|
||||
let connect = connector.connect(params);
|
||||
Box::pin(async move {
|
||||
let connected = connect.await?;
|
||||
Ok(LocalConnected { connected, streams: None })
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// An address as it may be shown or logged: without its query and fragment,
|
||||
/// where a link keeps a channel password or a host pin.
|
||||
pub(crate) fn without_query(address: &str) -> &str {
|
||||
address.split(['?', '#']).next().unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Refuses every host that asks to be trusted.
|
||||
struct RefuseUnknownHosts;
|
||||
|
||||
impl HostTrust for RefuseUnknownHosts {
|
||||
fn confirm(&self, _host: HostIdentity) -> BoxFuture<bool> {
|
||||
Box::pin(async { false })
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_bookmark_without_a_scheme_is_a_teamspeak_server() {
|
||||
assert_eq!(Backends::scheme("ts.example.com:9987"), "ts3server");
|
||||
assert_eq!(Backends::scheme("[::1]:9987"), "ts3server");
|
||||
assert_eq!(Backends::scheme("TS3Server://ts.example.com"), "ts3server");
|
||||
assert_eq!(Backends::scheme("teamspeak://x"), "teamspeak");
|
||||
assert_eq!(Backends::scheme("voelin://host/i/code"), "voelin");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_address_is_shown_without_its_secrets() {
|
||||
assert_eq!(without_query("ts3server://h?port=1&channelpassword=hunter2"), "ts3server://h");
|
||||
assert_eq!(without_query("voelin://h/i/code#h=abcd"), "voelin://h/i/code");
|
||||
assert_eq!(without_query("host:9987"), "host:9987");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,261 @@
|
||||
//! What a session hands the connector of an address: the `ConnectParams` of
|
||||
//! a [`VoiceOptions`] (`docs/session-seam.md` section 4.2).
|
||||
//!
|
||||
//! The options are the engine's own, and a connector reads them back: the
|
||||
//! address is the link of the bookmark (a `ts3server://` link for a
|
||||
//! bookmark that names a TeamSpeak server by `host[:port]`), the nickname,
|
||||
//! the server password and the privilege key are in the hello, the identity
|
||||
//! is the credential. What v1 has no field for yet (the channel to join and
|
||||
//! its password, the client version a TeamSpeak server is shown) rides in
|
||||
//! the address, as parameters of the link.
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use base64::Engine as _;
|
||||
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
|
||||
use bytes::Bytes;
|
||||
use voelin_identity::{IdentityBlob, KIND_TEAMSPEAK};
|
||||
use voelin_model::Link;
|
||||
use voelin_proto::link::{ConnectParams, Credential, IssuerTrust, MediaSink, SessionError};
|
||||
use voelin_proto::v1;
|
||||
|
||||
use super::{Backends, VoiceOptions, without_query};
|
||||
|
||||
/// The link parameter that carries the client version to impersonate: the
|
||||
/// user's spec (`VoiceOptions::client_version`), in unpadded URL-safe base64.
|
||||
/// The connector for TeamSpeak resolves it; other connectors never read it.
|
||||
pub(crate) const VERSION_PARAM: &str = "client_version";
|
||||
|
||||
/// The connect parameters of a connection, from the options the session was
|
||||
/// asked to connect with.
|
||||
///
|
||||
/// The address is the link of the bookmark (the channel and its password
|
||||
/// ride in it, and so does the client version to claim, until v1 has fields
|
||||
/// for them), the server password is `Hello.password` and the privilege key
|
||||
/// `Hello.invite_code`. The identity goes as the credential of its kind; no
|
||||
/// account is used yet.
|
||||
///
|
||||
/// An address a link cannot carry is refused here ([`bookmark`]), and so is
|
||||
/// an identity that is of no kind a connector can use.
|
||||
pub(crate) fn connect_params(
|
||||
options: &VoiceOptions,
|
||||
media: Arc<dyn MediaSink>,
|
||||
backends: &Backends,
|
||||
) -> Result<ConnectParams, SessionError> {
|
||||
let hello = v1::Hello {
|
||||
version: 1,
|
||||
client: Some(v1::ClientInfo {
|
||||
name: "Voelin".into(),
|
||||
version: voelin_platform::crash::app_version().to_owned(),
|
||||
platform: std::env::consts::OS.into(),
|
||||
kind: v1::ClientKind::User as i32,
|
||||
}),
|
||||
nickname: options.nickname.clone(),
|
||||
password: options.server_password.clone().unwrap_or_default(),
|
||||
invite_code: options.token.clone().unwrap_or_default(),
|
||||
..Default::default()
|
||||
};
|
||||
Ok(ConnectParams {
|
||||
address: address_link(options)?,
|
||||
credential: credential(options.identity.as_ref())?,
|
||||
linked: Vec::new(),
|
||||
account: backends.account(),
|
||||
issuer_trust: IssuerTrust::Unknown,
|
||||
hello,
|
||||
host_pin: None,
|
||||
trust: backends.trust(),
|
||||
media,
|
||||
push_capacity: 1024,
|
||||
timeout: Duration::from_secs(35),
|
||||
})
|
||||
}
|
||||
|
||||
/// The credential of an identity (`docs/session-seam.md` section 7). A
|
||||
/// TeamSpeak identity goes as the JSON the key store keeps, and none at all as
|
||||
/// an empty one, for which the TeamSpeak connector makes an identity up (the
|
||||
/// protocol's convention for "generate one", follow-up P11); a Voelin key
|
||||
/// signs. A TeamSpeak identity that holds no JSON is refused: sent as it is,
|
||||
/// it would be that same empty blob and be taken for the request to make one
|
||||
/// up, which only the absence of an identity may be.
|
||||
fn credential(identity: Option<&IdentityBlob>) -> Result<Credential, SessionError> {
|
||||
let Some(blob) = identity else {
|
||||
return Ok(Credential::Foreign { kind: KIND_TEAMSPEAK, blob: Bytes::new() });
|
||||
};
|
||||
if blob.is_teamspeak() {
|
||||
if blob.json.trim().is_empty() {
|
||||
return Err(SessionError::Protocol(
|
||||
"the TeamSpeak identity cannot be read: it is empty".into(),
|
||||
));
|
||||
}
|
||||
let json = Bytes::copy_from_slice(blob.json.as_bytes());
|
||||
Ok(Credential::Foreign { kind: KIND_TEAMSPEAK, blob: json })
|
||||
} else if blob.is_voelin() {
|
||||
let key = blob.voelin_key().map_err(|e| {
|
||||
SessionError::Protocol(format!("the Voelin identity cannot be read: {e}"))
|
||||
})?;
|
||||
Ok(Credential::Voelin(Arc::new(key)))
|
||||
} else {
|
||||
Err(SessionError::Protocol(format!(
|
||||
"an identity of kind {:?} cannot be used to connect",
|
||||
blob.kind
|
||||
)))
|
||||
}
|
||||
}
|
||||
|
||||
/// The `ts3server://` link of the options' address, with the channel to join
|
||||
/// and the client version to claim.
|
||||
fn address_link(options: &VoiceOptions) -> Result<String, SessionError> {
|
||||
let mut link = match Link::parse(&options.address) {
|
||||
Some(Link::Server(link)) => link,
|
||||
// Not a TeamSpeak link, or none: a bookmark's `host[:port]`.
|
||||
_ if !options.address.contains("://") => bookmark(&options.address)?,
|
||||
// Some other scheme: as given, for the connector of that scheme.
|
||||
_ => return Ok(options.address.clone()),
|
||||
};
|
||||
link.channel = options.channel.clone().filter(|c| !c.is_empty()).or(link.channel);
|
||||
link.channel_password =
|
||||
options.channel_password.clone().filter(|p| !p.is_empty()).or(link.channel_password);
|
||||
let mut url = link.to_url();
|
||||
if let Some(spec) = &options.client_version {
|
||||
url.push(if url.contains('?') { '&' } else { '?' });
|
||||
url.push_str(VERSION_PARAM);
|
||||
url.push('=');
|
||||
url.push_str(&URL_SAFE_NO_PAD.encode(spec));
|
||||
}
|
||||
Ok(url)
|
||||
}
|
||||
|
||||
/// The link to a bookmark's `host[:port]`.
|
||||
///
|
||||
/// A link cannot say everything an address can: it drops a port that is no
|
||||
/// port (`ServerLink::new` takes `host:99999` for the host `host` and joins
|
||||
/// the default port), and it ends the host at a `?`, `#` or `/` and decodes a
|
||||
/// `%` (so that a `?` in the host would hide the channel behind the next
|
||||
/// one). The TeamSpeak library refuses such an address when it resolves it;
|
||||
/// so does this, in words, instead of connecting to something else.
|
||||
fn bookmark(address: &str) -> Result<voelin_model::ServerLink, SessionError> {
|
||||
let address = address.trim();
|
||||
// Without the query: a link keeps secrets in it.
|
||||
let shown = without_query(address);
|
||||
let not_an_address = || SessionError::Protocol(format!("not a server address: {shown}"));
|
||||
if address.is_empty()
|
||||
|| address
|
||||
.chars()
|
||||
.any(|c| matches!(c, '?' | '#' | '/' | '%') || c.is_whitespace() || c.is_control())
|
||||
{
|
||||
return Err(not_an_address());
|
||||
}
|
||||
// The text after the port's colon: `[v6]:port`, or `host:port` with the one
|
||||
// colon (more colons are an IPv6 address without a port).
|
||||
let port = if let Some(rest) = address.strip_prefix('[') {
|
||||
let (_, after) = rest.split_once(']').ok_or_else(not_an_address)?;
|
||||
(!after.is_empty()).then(|| after.strip_prefix(':').unwrap_or(after))
|
||||
} else {
|
||||
address.rsplit_once(':').filter(|(host, _)| !host.contains(':')).map(|(_, port)| port)
|
||||
};
|
||||
if let Some(port) = port
|
||||
&& !port.parse::<u16>().is_ok_and(|port| port != 0)
|
||||
{
|
||||
return Err(SessionError::Protocol(format!(
|
||||
"the port in {shown} is not a number from 1 to 65535"
|
||||
)));
|
||||
}
|
||||
Ok(voelin_model::ServerLink::new(address))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use voelin_identity::IdentityKey;
|
||||
|
||||
fn params(options: &VoiceOptions) -> Result<ConnectParams, SessionError> {
|
||||
let (media, _rx) = voelin_proto::test_util::media_channel();
|
||||
connect_params(options, media, &Backends::empty())
|
||||
}
|
||||
|
||||
/// The identity of the options is the credential of its kind: a TeamSpeak
|
||||
/// identity as the JSON the key store keeps, none as the empty blob a
|
||||
/// connector makes an identity up for, a Voelin key as its signer.
|
||||
#[test]
|
||||
fn an_identity_is_the_credential_of_its_kind() {
|
||||
let mut options = VoiceOptions::new("ts.example.com", "nick");
|
||||
let none = params(&options).unwrap();
|
||||
assert!(matches!(
|
||||
&none.credential,
|
||||
Credential::Foreign { kind: "teamspeak", blob } if blob.is_empty()
|
||||
));
|
||||
|
||||
options.identity = Some(IdentityBlob::teamspeak("uid=", 8, r#"{"key":"k"}"#));
|
||||
let sent = params(&options).unwrap();
|
||||
assert!(matches!(
|
||||
&sent.credential,
|
||||
Credential::Foreign { kind: "teamspeak", blob } if &blob[..] == br#"{"key":"k"}"#
|
||||
));
|
||||
|
||||
let key = IdentityKey::generate().unwrap();
|
||||
options.identity = Some(IdentityBlob::voelin(&key).unwrap());
|
||||
let Credential::Voelin(signer) = params(&options).unwrap().credential else {
|
||||
panic!("a Voelin credential")
|
||||
};
|
||||
assert_eq!(signer.public_key(), key.public_key());
|
||||
assert_eq!(signer.sign(b"hello"), key.sign(b"hello"));
|
||||
|
||||
// A Voelin blob whose key cannot be read, and a kind that connects to
|
||||
// nothing: refused in words, without the JSON.
|
||||
options.identity = Some(IdentityBlob::new("voelin", "x", 0, "hunter2"));
|
||||
let Err(SessionError::Protocol(text)) = params(&options) else { panic!("a refusal") };
|
||||
assert!(
|
||||
text.starts_with("the Voelin identity cannot be read") && !text.contains("hunter2")
|
||||
);
|
||||
options.identity = Some(IdentityBlob::new("account", "x", 0, "hunter2"));
|
||||
let Err(SessionError::Protocol(text)) = params(&options) else { panic!("a refusal") };
|
||||
assert_eq!(text, "an identity of kind \"account\" cannot be used to connect");
|
||||
}
|
||||
|
||||
/// A TeamSpeak identity with no JSON is no identity. The empty blob is
|
||||
/// what asks the TeamSpeak connector to make one up (`identity: None`), so
|
||||
/// it is refused here instead of being sent as that request.
|
||||
#[test]
|
||||
fn a_teamspeak_identity_without_json_is_refused() {
|
||||
let mut options = VoiceOptions::new("ts.example.com", "nick");
|
||||
for json in ["", " \n\t"] {
|
||||
options.identity = Some(IdentityBlob::teamspeak("uid=", 8, json));
|
||||
let Err(SessionError::Protocol(text)) = params(&options) else {
|
||||
panic!("a refusal for {json:?}")
|
||||
};
|
||||
assert_eq!(text, "the TeamSpeak identity cannot be read: it is empty");
|
||||
}
|
||||
// No identity at all is the request to make one up, as before.
|
||||
options.identity = None;
|
||||
assert!(matches!(
|
||||
params(&options).unwrap().credential,
|
||||
Credential::Foreign { kind: "teamspeak", blob } if blob.is_empty()
|
||||
));
|
||||
}
|
||||
|
||||
/// The client version spec rides the link as it was typed, whatever it
|
||||
/// holds, and only for an address that is a TeamSpeak bookmark or link.
|
||||
#[test]
|
||||
fn the_client_version_spec_rides_the_link_unchanged() {
|
||||
let spec = |address: &str, spec: &str| {
|
||||
let mut options = VoiceOptions::new(address, "nick");
|
||||
options.client_version = Some(spec.into());
|
||||
params(&options).unwrap().address
|
||||
};
|
||||
let address = spec("ts.example.com:9988", "windows@3.6.2 [Build: 1]&x=#");
|
||||
let (_, query) = address.split_once('?').unwrap();
|
||||
let text = query
|
||||
.split('&')
|
||||
.find_map(|pair| pair.strip_prefix("client_version="))
|
||||
.expect("the parameter");
|
||||
let decoded = URL_SAFE_NO_PAD.decode(text).unwrap();
|
||||
assert_eq!(decoded, b"windows@3.6.2 [Build: 1]&x=#");
|
||||
// Another scheme is left as it is: its connector has no use for a TeamSpeak
|
||||
// client's version.
|
||||
assert_eq!(spec("voelin://host/i/code", "generic"), "voelin://host/i/code");
|
||||
// No spec, no parameter.
|
||||
let options = VoiceOptions::new("ts.example.com", "nick");
|
||||
assert!(!params(&options).unwrap().address.contains(VERSION_PARAM));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,363 @@
|
||||
//! The session through an in-memory [`ServerLink`]: a `FakeLink` hands each
|
||||
//! connection the test asks for to the test, which plays the server by
|
||||
//! sending scripted [`LinkEvent`]s and reads the [`LinkCmd`]s the session
|
||||
//! gives. These are the tests that need the inner link itself:
|
||||
//!
|
||||
//! - the stream commands, which travel on the in-process port of the link
|
||||
//! and which a `voelin_proto::link::Session` has no part in until the
|
||||
//! stream task moves (`docs/session-seam.md` sections 6.4 and 9.2);
|
||||
//! - the order in which a reconnect shuts the streams and the old connection
|
||||
//! down, which is the order of the one queue `LinkSession` keeps;
|
||||
//! - a link that keeps talking after the engine replaced its connection,
|
||||
//! which a closed `FakeSession` cannot do on purpose.
|
||||
//!
|
||||
//! (They were integration tests while the inner link was public; it is the
|
||||
//! TeamSpeak module's now, and so are these.)
|
||||
//!
|
||||
//! Presence, chat, the dedup of a message that comes twice, history, transfers
|
||||
//! and the rest of what the engine does with a session are tested on the
|
||||
//! protocol repository's fake host in `tests/session_fake.rs`. Nothing here
|
||||
//! needs a TeamSpeak server or a TeamSpeak type.
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::time::{Duration, SystemTime, UNIX_EPOCH};
|
||||
|
||||
use tokio::sync::{broadcast, mpsc};
|
||||
|
||||
use super::{Backends, LinkCmd, LinkCtx, LinkEvent};
|
||||
use crate::settings::Settings;
|
||||
use crate::stream::{StreamCmd, StreamSetup};
|
||||
use crate::ts::ts_session::LinkConnector;
|
||||
use crate::ts::{ConnectOptions, ServerLink};
|
||||
use crate::{
|
||||
BackendInfo, Command, Engine, Event, History, SessionId, SessionState, VoiceOptions, VoiceState,
|
||||
};
|
||||
use voelin_model::{
|
||||
Capabilities, ChannelId, ChannelInfo, ChatMessage, ChatTarget, ClientInfo, Presence,
|
||||
ServerDetails,
|
||||
};
|
||||
|
||||
/// A connection the session asked the link for.
|
||||
struct Conn {
|
||||
cmds: mpsc::UnboundedReceiver<LinkCmd>,
|
||||
events: mpsc::UnboundedSender<LinkEvent>,
|
||||
}
|
||||
|
||||
impl Conn {
|
||||
/// Play `script`, the server's side, in order.
|
||||
fn play(&self, script: impl IntoIterator<Item = LinkEvent>) {
|
||||
for event in script {
|
||||
self.events.send(event).expect("the session listens");
|
||||
}
|
||||
}
|
||||
|
||||
/// The next command the session gave.
|
||||
async fn cmd(&mut self) -> LinkCmd {
|
||||
tokio::time::timeout(Duration::from_secs(10), self.cmds.recv())
|
||||
.await
|
||||
.expect("a command in time")
|
||||
.expect("the session keeps the connection")
|
||||
}
|
||||
}
|
||||
|
||||
/// Hands every connection to the test.
|
||||
struct FakeLink {
|
||||
conns: mpsc::UnboundedSender<Conn>,
|
||||
}
|
||||
|
||||
impl FakeLink {
|
||||
fn new() -> (Self, mpsc::UnboundedReceiver<Conn>) {
|
||||
let (conns, rx) = mpsc::unbounded_channel();
|
||||
(Self { conns }, rx)
|
||||
}
|
||||
}
|
||||
|
||||
impl ServerLink for FakeLink {
|
||||
fn spawn(
|
||||
&self,
|
||||
_options: ConnectOptions,
|
||||
_ctx: LinkCtx,
|
||||
cmds: mpsc::UnboundedReceiver<LinkCmd>,
|
||||
events: mpsc::UnboundedSender<LinkEvent>,
|
||||
) {
|
||||
let _ = self.conns.send(Conn { cmds, events });
|
||||
}
|
||||
}
|
||||
|
||||
const SESSION: SessionId = 1;
|
||||
const SERVER_UID: &str = "fake-server=";
|
||||
const ME: u16 = 7;
|
||||
const ME_UID: &str = "me=";
|
||||
const LOBBY: ChannelId = 1;
|
||||
const GAMES: ChannelId = 2;
|
||||
|
||||
struct Harness {
|
||||
engine: Engine,
|
||||
events: broadcast::Receiver<Event>,
|
||||
conns: mpsc::UnboundedReceiver<Conn>,
|
||||
}
|
||||
|
||||
impl Harness {
|
||||
fn start() -> Self {
|
||||
let (link, conns) = FakeLink::new();
|
||||
let mut backends = Backends::empty();
|
||||
backends.register_local(Arc::new(LinkConnector::any(Arc::new(link))));
|
||||
let engine =
|
||||
Engine::start_with_backends(Settings::in_memory(), History::in_memory(), backends);
|
||||
let events = engine.subscribe();
|
||||
Self { engine, events, conns }
|
||||
}
|
||||
|
||||
/// Ask for a voice connection and take it from the link.
|
||||
async fn connect(&mut self) -> Conn {
|
||||
let options = VoiceOptions::new("fake.test:9987", "tester");
|
||||
self.engine.send(Command::ConnectVoice { session: SESSION, options: Box::new(options) });
|
||||
tokio::time::timeout(Duration::from_secs(10), self.conns.recv())
|
||||
.await
|
||||
.expect("the session spawns the link")
|
||||
.expect("the link lives")
|
||||
}
|
||||
|
||||
/// The next event `f` picks, skipping the others.
|
||||
async fn next<T>(&mut self, mut f: impl FnMut(Event) -> Option<T>) -> T {
|
||||
tokio::time::timeout(Duration::from_secs(10), async {
|
||||
loop {
|
||||
if let Some(t) = f(self.events.recv().await.expect("engine events")) {
|
||||
return t;
|
||||
}
|
||||
}
|
||||
})
|
||||
.await
|
||||
.expect("event in time")
|
||||
}
|
||||
|
||||
/// The next state of the session that `ok` accepts.
|
||||
async fn state(&mut self, mut ok: impl FnMut(&SessionState) -> bool) -> SessionState {
|
||||
self.next(|e| match e {
|
||||
Event::State { state, .. } if ok(&state) => Some(state),
|
||||
_ => None,
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// The next live chat message.
|
||||
async fn chat(&mut self) -> ChatMessage {
|
||||
self.next(|e| match e {
|
||||
Event::Chat { message, .. } => Some(message),
|
||||
_ => None,
|
||||
})
|
||||
.await
|
||||
}
|
||||
}
|
||||
|
||||
fn now_ms() -> i64 {
|
||||
SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_millis() as i64
|
||||
}
|
||||
|
||||
fn capabilities(streams: bool) -> Capabilities {
|
||||
Capabilities { streams, file_transfer: true, ..Default::default() }
|
||||
}
|
||||
|
||||
fn backend() -> BackendInfo {
|
||||
BackendInfo { product: "Fake".into(), version: "1.2".into() }
|
||||
}
|
||||
|
||||
fn connected(streams: bool) -> LinkEvent {
|
||||
LinkEvent::Connected {
|
||||
name: "Fake Server".into(),
|
||||
backend: backend(),
|
||||
capabilities: capabilities(streams),
|
||||
own_client: ME,
|
||||
server_uid: SERVER_UID.into(),
|
||||
own_uid: Some(ME_UID.into()),
|
||||
}
|
||||
}
|
||||
|
||||
/// A client as a TeamSpeak link reports one: with its database id, and not
|
||||
/// talking (who talks comes from the media, which the session derives).
|
||||
fn client(id: u16, nickname: &str, channel: ChannelId) -> ClientInfo {
|
||||
ClientInfo {
|
||||
id,
|
||||
uid: Some(format!("{nickname}=")),
|
||||
nickname: nickname.into(),
|
||||
channel,
|
||||
talking: Some(false),
|
||||
database_id: Some(1_000 + u64::from(id)),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// Two channels, three clients; we are in the second channel. The shape is
|
||||
/// what a TeamSpeak link reports: sibling channels form an order chain, the
|
||||
/// server is named and has its unique id.
|
||||
fn presence() -> Presence {
|
||||
let channel =
|
||||
|id, name: &str, order| ChannelInfo { id, name: name.into(), order, ..Default::default() };
|
||||
let mut presence = Presence { server_name: "Fake Server".into(), ..Default::default() };
|
||||
presence.server = ServerDetails {
|
||||
name: "Fake Server".into(),
|
||||
uid: Some(SERVER_UID.into()),
|
||||
version: backend().version,
|
||||
..Default::default()
|
||||
};
|
||||
presence.channels.insert(LOBBY, channel(LOBBY, "Lobby", 0));
|
||||
presence.channels.insert(GAMES, channel(GAMES, "Games", LOBBY));
|
||||
let me = ClientInfo { uid: Some(ME_UID.into()), ..client(ME, "tester", GAMES) };
|
||||
for c in [me, client(8, "alice", GAMES), client(9, "bob", LOBBY)] {
|
||||
presence.clients.insert(c.id, c);
|
||||
}
|
||||
presence
|
||||
}
|
||||
|
||||
fn message(author: &str, text: &str, ts_ms: i64) -> ChatMessage {
|
||||
ChatMessage {
|
||||
target: ChatTarget::Channel(GAMES),
|
||||
author_name: author.into(),
|
||||
author_uid: Some(format!("{author}=")),
|
||||
author_id: None,
|
||||
text: text.into(),
|
||||
ts_ms,
|
||||
via_relay: false,
|
||||
blocked: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Stream commands reach a link that has streams in its capabilities, and
|
||||
/// end with the connection; a link without them is spared. (The rest of what
|
||||
/// the user asks for is checked on the fake host in `session_fake.rs`.)
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn stream_commands_reach_a_link_with_streams() {
|
||||
let mut h = Harness::start();
|
||||
let mut conn = h.connect().await;
|
||||
conn.play([
|
||||
connected(false),
|
||||
LinkEvent::Presence(Box::new(presence())),
|
||||
LinkEvent::OwnChannel(GAMES),
|
||||
]);
|
||||
h.state(|s| s.own_channel == Some(GAMES)).await;
|
||||
|
||||
// No streams in the capabilities: the session refuses them itself.
|
||||
let engine = h.engine.clone();
|
||||
let setup = || StreamSetup { name: "screen".into(), ..Default::default() };
|
||||
engine.send(Command::StartStream { session: SESSION, setup: setup(), auto_accept: true });
|
||||
let error = h
|
||||
.next(|e| match e {
|
||||
Event::Error { message, .. } => Some(message),
|
||||
_ => None,
|
||||
})
|
||||
.await;
|
||||
assert!(error.contains("streams"), "{error}");
|
||||
assert!(conn.cmds.try_recv().is_err(), "nothing reached the link");
|
||||
|
||||
// A link with streams: stream commands go to it, and end with the connection.
|
||||
let mut with_streams = {
|
||||
let link_engine = h.engine.clone();
|
||||
link_engine.send(Command::ConnectVoice {
|
||||
session: SESSION,
|
||||
options: Box::new(VoiceOptions::new("fake.test:9987", "tester")),
|
||||
});
|
||||
h.conns.recv().await.expect("the second connection")
|
||||
};
|
||||
// The replaced connection is told to go.
|
||||
assert!(matches!(conn.cmd().await, LinkCmd::Disconnect));
|
||||
with_streams.play([connected(true)]);
|
||||
h.next(|e| match e {
|
||||
Event::ServerInfo { capabilities, .. } if capabilities.streams => Some(()),
|
||||
_ => None,
|
||||
})
|
||||
.await;
|
||||
// A connection with streams is given the (empty) stream directory first.
|
||||
let LinkCmd::Stream(StreamCmd::Directory(directory)) = with_streams.cmd().await else {
|
||||
panic!("the stream directory")
|
||||
};
|
||||
assert!(directory.is_empty());
|
||||
engine.send(Command::StartStream { session: SESSION, setup: setup(), auto_accept: true });
|
||||
let LinkCmd::Stream(StreamCmd::Start { setup, auto_accept }) = with_streams.cmd().await else {
|
||||
panic!("a stream start")
|
||||
};
|
||||
assert_eq!((setup.name.as_str(), auto_accept), ("screen", true));
|
||||
engine.send(Command::StopStream { session: SESSION });
|
||||
assert!(matches!(with_streams.cmd().await, LinkCmd::Stream(StreamCmd::Stop)));
|
||||
engine.send(Command::DisconnectVoice { session: SESSION });
|
||||
assert!(matches!(with_streams.cmd().await, LinkCmd::Disconnect));
|
||||
}
|
||||
|
||||
/// A reconnect ends the streams of the connection it replaces through that
|
||||
/// connection, before the connection itself: the old link is given
|
||||
/// `StreamCmd::Shutdown` and only then `Disconnect`. A link that ends its
|
||||
/// connection on `Disconnect` (the TeamSpeak one stops reading commands
|
||||
/// there) relies on this order for the streams to hear of their end.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_reconnect_shuts_the_streams_down_before_the_old_connection() {
|
||||
let mut h = Harness::start();
|
||||
let mut old = h.connect().await;
|
||||
old.play([
|
||||
connected(true),
|
||||
LinkEvent::Presence(Box::new(presence())),
|
||||
LinkEvent::OwnChannel(GAMES),
|
||||
]);
|
||||
h.state(|s| s.own_channel == Some(GAMES)).await;
|
||||
let LinkCmd::Stream(StreamCmd::Directory(directory)) = old.cmd().await else {
|
||||
panic!("the stream directory")
|
||||
};
|
||||
assert!(directory.is_empty());
|
||||
|
||||
// Connecting again replaces the connection.
|
||||
let _new = h.connect().await;
|
||||
let LinkCmd::Stream(StreamCmd::Shutdown(reason)) = old.cmd().await else {
|
||||
panic!("the streams end first")
|
||||
};
|
||||
assert_eq!(reason, "voice reconnecting");
|
||||
assert!(matches!(old.cmd().await, LinkCmd::Disconnect));
|
||||
}
|
||||
|
||||
/// Events of a connection the session replaced do not reach it.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_replaced_connection_is_ignored() {
|
||||
let mut h = Harness::start();
|
||||
let mut old = h.connect().await;
|
||||
old.play([
|
||||
connected(false),
|
||||
LinkEvent::Presence(Box::new(presence())),
|
||||
LinkEvent::OwnChannel(GAMES),
|
||||
]);
|
||||
h.state(|s| s.own_channel == Some(GAMES)).await;
|
||||
|
||||
let new = h.connect().await;
|
||||
assert!(matches!(old.cmd().await, LinkCmd::Disconnect));
|
||||
// The old connection winds down, and says more than it should.
|
||||
let mut stale = presence();
|
||||
stale.clients.insert(10, client(10, "ghost", LOBBY));
|
||||
old.play([
|
||||
LinkEvent::Presence(Box::new(stale)),
|
||||
LinkEvent::Chat(message("ghost", "boo", now_ms())),
|
||||
LinkEvent::Disconnected(None),
|
||||
]);
|
||||
let mut fresh = presence();
|
||||
fresh.clients.remove(&9);
|
||||
// A link that says we are in the lobby shows us in the lobby.
|
||||
fresh.clients.get_mut(&ME).expect("we are on the server").channel = LOBBY;
|
||||
new.play([
|
||||
connected(false),
|
||||
LinkEvent::Presence(Box::new(fresh.clone())),
|
||||
LinkEvent::OwnChannel(LOBBY),
|
||||
]);
|
||||
// Only the new connection's presence is shown (nobody else has 2 clients).
|
||||
let shown = h
|
||||
.next(|e| match e {
|
||||
Event::Presence { presence, .. } if presence.clients.len() == fresh.clients.len() => {
|
||||
Some(presence)
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.await;
|
||||
assert_eq!(*shown, fresh);
|
||||
let state = h.state(|s| s.own_channel == Some(LOBBY)).await;
|
||||
assert_eq!(state.voice, VoiceState::Connected, "the old disconnect did not count");
|
||||
// Channel chat reaches the channel we are in (the lobby, now).
|
||||
new.play([LinkEvent::Chat(ChatMessage {
|
||||
target: ChatTarget::Channel(LOBBY),
|
||||
..message("alice", "hello", now_ms())
|
||||
})]);
|
||||
assert_eq!(h.chat().await.text, "hello", "the old connection's chat never showed");
|
||||
}
|
||||
@@ -0,0 +1,322 @@
|
||||
//! The engine's side of the seam against the protocol repository's fake host
|
||||
//! (`docs/session-seam.md` sections 9.2 and 16): the voice path through a
|
||||
//! `SessionLink` that talks to a `FakeSession`, and the link conformance
|
||||
//! suite run against the session the engine's registry hands over.
|
||||
//!
|
||||
//! The tests that need only the engine's public API are in
|
||||
//! `tests/session_fake.rs`; these need what is private to the crate: the
|
||||
//! `LinkCmd`/`LinkEvent` vocabulary between `session.rs` and `SessionLink`,
|
||||
//! the registry's `connect` and the context of a connector called outside an
|
||||
//! engine.
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use tokio::sync::mpsc;
|
||||
use voelin_audio::{EncodedVoice, VoiceCodec, VoicePacket};
|
||||
use voelin_proto::link::{FlowId, MediaClass, MediaPacket, voice_sub};
|
||||
use voelin_proto::media::payload::{OPUS_20_MS_TICKS, PT_OPUS};
|
||||
use voelin_proto::media::{RtpHeader, RtpView};
|
||||
use voelin_proto::test_util::conformance::{self, Fixture, Verdict};
|
||||
use voelin_proto::test_util::{
|
||||
FAKE_HOST_UID, FakeConnector, FakeHandle, connect_params, eventually,
|
||||
};
|
||||
use voelin_proto::v1::{self, entity::Kind};
|
||||
|
||||
use super::*;
|
||||
|
||||
const WAIT: Duration = Duration::from_secs(10);
|
||||
/// An Opus frame of 20 ms, mono (TOC `0xf8`), and the same as stereo (`0xfc`).
|
||||
const MONO: [u8; 3] = [0xf8, 0xff, 0xfe];
|
||||
const STEREO: [u8; 3] = [0xfc, 0xff, 0xfe];
|
||||
const ALICE: u32 = 50;
|
||||
const ALICE_SLOT: u32 = 90;
|
||||
const BOB: u32 = 51;
|
||||
const BOB_SLOT: u32 = 91;
|
||||
|
||||
fn put(connector: &FakeConnector, kind: Kind) {
|
||||
connector.host().put(v1::Entity { kind: Some(kind) }).expect("the fake host stores it");
|
||||
}
|
||||
|
||||
/// A host with one server, a lobby, and alice and bob talking in it.
|
||||
fn host() -> FakeConnector {
|
||||
let connector = FakeConnector::new();
|
||||
put(
|
||||
&connector,
|
||||
Kind::Server(v1::Server {
|
||||
id: 1,
|
||||
name: "Fake Host".into(),
|
||||
uid: "fake-host".into(),
|
||||
default_channel_id: 10,
|
||||
..Default::default()
|
||||
}),
|
||||
);
|
||||
put(
|
||||
&connector,
|
||||
Kind::Channel(v1::Channel {
|
||||
id: 10,
|
||||
server_id: 1,
|
||||
kind: v1::ChannelKind::Voice as i32,
|
||||
name: "Lobby".into(),
|
||||
..Default::default()
|
||||
}),
|
||||
);
|
||||
for (user, participant, slot, name) in
|
||||
[(2, ALICE, ALICE_SLOT, "alice"), (3, BOB, BOB_SLOT, "bob")]
|
||||
{
|
||||
put(
|
||||
&connector,
|
||||
Kind::User(v1::User {
|
||||
id: user,
|
||||
uid: vec![user as u8; 32].into(),
|
||||
uid_kind: v1::IdKind::Voelin as i32,
|
||||
name: name.into(),
|
||||
..Default::default()
|
||||
}),
|
||||
);
|
||||
put(
|
||||
&connector,
|
||||
Kind::Voice(v1::VoiceState {
|
||||
server_id: 1,
|
||||
participant_id: participant,
|
||||
user_id: user,
|
||||
channel_id: 10,
|
||||
slot,
|
||||
nick: name.into(),
|
||||
..Default::default()
|
||||
}),
|
||||
);
|
||||
}
|
||||
connector
|
||||
}
|
||||
|
||||
/// A `SessionLink` over a fake host, driven the way `session.rs` drives it.
|
||||
struct HostRig {
|
||||
handle: FakeHandle,
|
||||
cmds: mpsc::UnboundedSender<LinkCmd>,
|
||||
events: mpsc::UnboundedReceiver<LinkEvent>,
|
||||
/// Our participant and voice slot, as the host gave them.
|
||||
own_client: u16,
|
||||
own_slot: u32,
|
||||
/// The clients the link told started talking, in order.
|
||||
talking: Vec<u16>,
|
||||
}
|
||||
|
||||
/// The next event `f` picks from `events`, skipping the others.
|
||||
async fn event_of<T>(
|
||||
events: &mut mpsc::UnboundedReceiver<LinkEvent>,
|
||||
mut f: impl FnMut(LinkEvent) -> Option<T>,
|
||||
) -> T {
|
||||
tokio::time::timeout(WAIT, async {
|
||||
loop {
|
||||
if let Some(t) = f(events.recv().await.expect("the link lives")) {
|
||||
return t;
|
||||
}
|
||||
}
|
||||
})
|
||||
.await
|
||||
.expect("an event in time")
|
||||
}
|
||||
|
||||
impl HostRig {
|
||||
async fn connect() -> Self {
|
||||
let connector = host();
|
||||
let mut backends = Backends::empty();
|
||||
backends.register(Arc::new(connector.clone()));
|
||||
let link = SessionLink::new(backends);
|
||||
let (cmds, cmd_rx) = mpsc::unbounded_channel();
|
||||
let (event_tx, mut events) = mpsc::unbounded_channel();
|
||||
let ctx = LocalCtx::standalone().link;
|
||||
link.spawn(VoiceOptions::new("fake://host", "tester"), ctx, cmd_rx, event_tx);
|
||||
let own_client = event_of(&mut events, |e| match e {
|
||||
LinkEvent::Connected { own_client, .. } => Some(own_client),
|
||||
_ => None,
|
||||
})
|
||||
.await;
|
||||
event_of(&mut events, |e| matches!(e, LinkEvent::OwnChannel(10)).then_some(())).await;
|
||||
let own_slot = connector
|
||||
.host()
|
||||
.entities(&v1::Scope { kind: v1::ScopeKind::Live as i32, id: 1 })
|
||||
.into_iter()
|
||||
.find_map(|e| match e.kind? {
|
||||
Kind::Voice(v) if v.participant_id == u32::from(own_client) => Some(v.slot),
|
||||
_ => None,
|
||||
})
|
||||
.expect("the host seated us in voice");
|
||||
let handle = connector.last_session().expect("the connector made a session");
|
||||
Self { handle, cmds, events, own_client, own_slot, talking: Vec::new() }
|
||||
}
|
||||
|
||||
/// The next voice packet the audio thread would get; who started to talk on
|
||||
/// the way is kept in `talking`.
|
||||
async fn audio(&mut self) -> VoicePacket {
|
||||
let talking = &mut self.talking;
|
||||
event_of(&mut self.events, |e| match e {
|
||||
LinkEvent::Talking { client, talking: true } => {
|
||||
talking.push(client);
|
||||
None
|
||||
}
|
||||
LinkEvent::Audio(packet) => Some(packet),
|
||||
_ => None,
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
fn give(&self, cmd: LinkCmd) {
|
||||
self.cmds.send(cmd).expect("the link listens");
|
||||
}
|
||||
}
|
||||
|
||||
/// A voice packet of `slot` on sub-flow `sub`, as a host delivers it.
|
||||
fn voice_packet(slot: u32, sub: u8, sequence: u16, payload: &[u8]) -> MediaPacket {
|
||||
let flow = FlowId::new(slot, sub);
|
||||
let mut out = bytes::BytesMut::new();
|
||||
RtpHeader::new(PT_OPUS, sequence, u32::from(sequence) * 960)
|
||||
.write(flow, &mut out)
|
||||
.expect("a header");
|
||||
out.extend_from_slice(payload);
|
||||
MediaPacket { flow, rtp: out.freeze() }
|
||||
}
|
||||
|
||||
fn voice(payload: &[u8]) -> EncodedVoice {
|
||||
EncodedVoice { codec: VoiceCodec::Voice, payload: payload.to_vec() }
|
||||
}
|
||||
|
||||
/// Our voice leaves as RTP on the slot the host gave us: the sequence counts
|
||||
/// every packet, the timestamp advances by the duration of the previous one,
|
||||
/// the marker is on the first packet of a spurt, the end of a spurt is an
|
||||
/// empty payload sent once, and the SSRC is the flow (protocol section 6).
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn our_voice_is_rtp_on_the_slot_the_host_gave_us() {
|
||||
let rig = HostRig::connect().await;
|
||||
// The fake host loops accepted media back; this test looks at what left.
|
||||
rig.handle.set_loopback(false);
|
||||
for n in 1..=3 {
|
||||
rig.give(LinkCmd::Audio(voice(&[0xf8, 0xff, 0xfe, n])));
|
||||
}
|
||||
rig.give(LinkCmd::Audio(voice(&[])));
|
||||
rig.give(LinkCmd::Audio(voice(&[0xf8, 0xff, 0xfe, 9])));
|
||||
let handle = rig.handle.clone();
|
||||
eventually(WAIT, "the five packets", || handle.sent_media().len() == 5).await;
|
||||
|
||||
let flow = FlowId::new(rig.own_slot, voice_sub::CHANNEL);
|
||||
let sent = rig.handle.sent_media();
|
||||
let seen: Vec<_> = sent
|
||||
.iter()
|
||||
.map(|(class, packet)| {
|
||||
let view = RtpView::parse(&packet.rtp).expect("RTP");
|
||||
assert_eq!(*class, MediaClass::Voice);
|
||||
assert_eq!(packet.flow, flow);
|
||||
assert_eq!((view.payload_type(), view.ssrc()), (PT_OPUS, flow.0));
|
||||
(view.sequence(), view.marker(), view.timestamp(), view.payload().to_vec())
|
||||
})
|
||||
.collect();
|
||||
let ticks = OPUS_20_MS_TICKS;
|
||||
assert_eq!(
|
||||
seen,
|
||||
[
|
||||
(0, true, 0, vec![0xf8, 0xff, 0xfe, 1]),
|
||||
(1, false, ticks, vec![0xf8, 0xff, 0xfe, 2]),
|
||||
(2, false, 2 * ticks, vec![0xf8, 0xff, 0xfe, 3]),
|
||||
// The end of the spurt: no payload, no marker, once.
|
||||
(3, false, 3 * ticks, vec![]),
|
||||
// The next spurt marks its first packet again.
|
||||
(4, true, 3 * ticks, vec![0xf8, 0xff, 0xfe, 9]),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
/// The RTP of other slots becomes the packets of the audio thread: the talker
|
||||
/// is the participant of the slot, a whisper sub-flow is a whisper, a stereo
|
||||
/// Opus frame is music, an empty payload ends the spurt; what is no voice of a
|
||||
/// slot the host told about is dropped.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn the_voice_of_other_slots_reaches_the_audio_thread() {
|
||||
let mut rig = HostRig::connect().await;
|
||||
let handle = rig.handle.clone();
|
||||
|
||||
// A slot nobody has, a probe and feedback: nothing. Then alice, mono.
|
||||
handle.inject_media(voice_packet(777, voice_sub::CHANNEL, 1, &MONO));
|
||||
handle.inject_media(MediaPacket { flow: FlowId::PROBE, rtp: bytes::Bytes::from_static(&[1]) });
|
||||
handle.inject_media(MediaPacket {
|
||||
flow: FlowId::FEEDBACK,
|
||||
rtp: bytes::Bytes::from_static(&[1, 2]),
|
||||
});
|
||||
handle.inject_media(voice_packet(ALICE_SLOT, voice_sub::CHANNEL, 5, &MONO));
|
||||
let packet = rig.audio().await;
|
||||
assert_eq!(
|
||||
(packet.talker.0, packet.seq, packet.codec, packet.whisper, packet.payload.as_slice()),
|
||||
(ALICE as u16, 5, VoiceCodec::Voice, false, MONO.as_slice())
|
||||
);
|
||||
|
||||
// Bob whispers (sub-flow 1) in stereo: music, a whisper.
|
||||
handle.inject_media(voice_packet(BOB_SLOT, 1, 6, &STEREO));
|
||||
let packet = rig.audio().await;
|
||||
assert_eq!(
|
||||
(packet.talker.0, packet.seq, packet.codec, packet.whisper),
|
||||
(BOB as u16, 6, VoiceCodec::Music, true)
|
||||
);
|
||||
|
||||
// Alice stops: an empty payload.
|
||||
handle.inject_media(voice_packet(ALICE_SLOT, voice_sub::CHANNEL, 7, &[]));
|
||||
let packet = rig.audio().await;
|
||||
assert_eq!((packet.talker.0, packet.seq, packet.payload.len()), (ALICE as u16, 7, 0));
|
||||
|
||||
// Who talks comes from the same packets: alice started, then bob, once each
|
||||
// (the slot nobody has started nobody).
|
||||
assert_eq!(rig.talking, [ALICE as u16, BOB as u16]);
|
||||
}
|
||||
|
||||
/// A host whose session loops our own voice back (the fake one does, so that
|
||||
/// the conformance suite can see media move) does not make the engine play us
|
||||
/// our own voice or show us as talking: the engine never plays itself.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn our_own_voice_coming_back_is_not_played_back() {
|
||||
let mut rig = HostRig::connect().await;
|
||||
// The fake host loops accepted media back into the sink (the default).
|
||||
rig.give(LinkCmd::Audio(voice(&MONO)));
|
||||
let handle = rig.handle.clone();
|
||||
eventually(WAIT, "the packet to leave", || handle.sent_media().len() == 1).await;
|
||||
// A packet of alice behind it: when this one is out, ours has been through.
|
||||
handle.inject_media(voice_packet(ALICE_SLOT, voice_sub::CHANNEL, 1, &MONO));
|
||||
let own = rig.own_client;
|
||||
let mut heard = Vec::new();
|
||||
while heard.last().is_none_or(|talker| *talker != ALICE as u16) {
|
||||
heard.push(rig.audio().await.talker.0);
|
||||
}
|
||||
assert!(!heard.contains(&own), "the engine played our own voice back: {heard:?}");
|
||||
}
|
||||
|
||||
/// The link conformance suite of the protocol repository against the session
|
||||
/// the engine's registry hands over: the registry adds nothing to a plain
|
||||
/// connector's session (`Backends::connect` returns it untouched), so the 17
|
||||
/// cases pass as they do in the protocol repository, none skipped.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn the_conformance_suite_passes_on_a_session_of_the_registry() {
|
||||
async fn through_the_registry() -> Fixture {
|
||||
let connector = FakeConnector::new();
|
||||
let mut backends = Backends::empty();
|
||||
backends.register(Arc::new(connector.clone()));
|
||||
let (params, media) = connect_params("fake://conformance");
|
||||
let local = backends
|
||||
.connect(params, LocalCtx::standalone())
|
||||
.await
|
||||
.unwrap_or_else(|e| panic!("the registry connects: {e}"));
|
||||
assert_eq!(local.connected.host_uid, FAKE_HOST_UID, "the connector's own answer");
|
||||
assert!(local.streams.is_none(), "a plain connector has no stream port");
|
||||
let backend = connector.last_session().expect("the connector made a session");
|
||||
// The session is the connector's own, so a request id means the same to both.
|
||||
Fixture {
|
||||
shared_request_ids: true,
|
||||
..Fixture::new(local.connected.session, local.connected.pushes, media, backend)
|
||||
}
|
||||
}
|
||||
let report = conformance::run(&through_the_registry).await;
|
||||
assert_eq!(report.cases.len(), conformance::CASES.len());
|
||||
assert_eq!(report.cases.len(), 17, "the suite of c5bb6b9 has 17 cases");
|
||||
assert!(
|
||||
report.cases.iter().all(|(_, verdict)| *verdict == Verdict::Passed),
|
||||
"{:?}",
|
||||
report.cases
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,310 @@
|
||||
//! Voice across the seam, engine side (`docs/session-seam.md` section 6.1):
|
||||
//! our encoded frames as RTP on our voice slot, the RTP of other slots as
|
||||
//! the audio thread's packets, and who is talking from the media.
|
||||
//!
|
||||
//! `voelin-audio`'s [`EncodedVoice`] and [`VoicePacket`] stay what the audio
|
||||
//! thread speaks; this is the framing in the v1 media codec
|
||||
//! (`voelin_proto::media`, protocol section 6).
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use bytes::BytesMut;
|
||||
use voelin_audio::{EncodedVoice, TalkerId, VoiceCodec, VoicePacket};
|
||||
use voelin_proto::link::{FlowId, MediaPacket, voice_sub};
|
||||
use voelin_proto::media::opus::{self, Toc};
|
||||
use voelin_proto::media::payload::{OPUS_20_MS_TICKS, PT_OPUS};
|
||||
use voelin_proto::media::{RtpHeader, RtpView};
|
||||
|
||||
/// A talker is silent after this long without a packet.
|
||||
pub(crate) const TALK_SILENCE: Duration = Duration::from_millis(400);
|
||||
|
||||
/// Our voice as RTP: the sequence number counts every packet from 0, the
|
||||
/// timestamp starts at 0 and advances by the duration of the previous
|
||||
/// packet, the marker is set on the first packet of a spurt, and the end of a
|
||||
/// spurt is a packet with an empty payload, sent once.
|
||||
#[derive(Default)]
|
||||
pub(crate) struct Uplink {
|
||||
sequence: u16,
|
||||
timestamp: u32,
|
||||
/// The ticks the last voice packet spans.
|
||||
ticks: u32,
|
||||
in_spurt: bool,
|
||||
}
|
||||
|
||||
impl Uplink {
|
||||
/// `voice` as the RTP packet of our voice slot.
|
||||
pub(crate) fn frame(&mut self, slot: u32, voice: &EncodedVoice) -> Option<MediaPacket> {
|
||||
let flow = FlowId::new(slot, voice_sub::CHANNEL);
|
||||
// The previous packet's duration has passed.
|
||||
self.timestamp = self.timestamp.wrapping_add(self.ticks);
|
||||
let end = voice.is_end();
|
||||
let mut header = RtpHeader::new(PT_OPUS, self.sequence, self.timestamp);
|
||||
header.marker = !end && !self.in_spurt;
|
||||
self.ticks =
|
||||
if end { 0 } else { opus::packet_ticks(&voice.payload).unwrap_or(OPUS_20_MS_TICKS) };
|
||||
self.in_spurt = !end;
|
||||
self.sequence = self.sequence.wrapping_add(1);
|
||||
let mut out = BytesMut::with_capacity(header.encoded_len() + voice.payload.len());
|
||||
header.write(flow, &mut out).ok()?;
|
||||
out.extend_from_slice(&voice.payload);
|
||||
Some(MediaPacket { flow, rtp: out.freeze() })
|
||||
}
|
||||
}
|
||||
|
||||
/// A voice packet of some slot, taken from its RTP.
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub(crate) struct Incoming {
|
||||
pub(crate) slot: u32,
|
||||
/// Sent on a whisper sub-flow (1 to 6).
|
||||
pub(crate) whisper: bool,
|
||||
pub(crate) sequence: u16,
|
||||
pub(crate) codec: VoiceCodec,
|
||||
/// Empty: the spurt ends.
|
||||
pub(crate) payload: Vec<u8>,
|
||||
}
|
||||
|
||||
impl Incoming {
|
||||
/// Parse a media packet. `None` for what is not the voice of a slot:
|
||||
/// feedback, probes, a flow that is no media, a packet that is no RTP.
|
||||
pub(crate) fn parse(packet: &MediaPacket) -> Option<Incoming> {
|
||||
if !packet.flow.is_media() {
|
||||
return None;
|
||||
}
|
||||
let view = RtpView::parse(&packet.rtp).ok()?;
|
||||
let payload = view.payload();
|
||||
// Stereo Opus is music; the jitter buffer decodes both the same way.
|
||||
let codec = match Toc::parse(payload) {
|
||||
Ok(toc) if toc.stereo() => VoiceCodec::Music,
|
||||
_ => VoiceCodec::Voice,
|
||||
};
|
||||
Some(Incoming {
|
||||
slot: packet.flow.slot(),
|
||||
whisper: (voice_sub::FIRST_TALK_TARGET..=voice_sub::LAST_TALK_TARGET)
|
||||
.contains(&packet.flow.sub()),
|
||||
sequence: view.sequence(),
|
||||
codec,
|
||||
payload: payload.to_vec(),
|
||||
})
|
||||
}
|
||||
|
||||
/// The packet for the audio thread, from `talker`.
|
||||
pub(crate) fn voice(self, talker: u16) -> VoicePacket {
|
||||
VoicePacket {
|
||||
talker: TalkerId(talker),
|
||||
seq: self.sequence,
|
||||
codec: self.codec,
|
||||
whisper: self.whisper,
|
||||
payload: self.payload,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Who is talking: derived from the media (protocol section 6.4). A talker
|
||||
/// starts with its first packet and stops after [`TALK_SILENCE`] without one.
|
||||
///
|
||||
/// A host can also say that someone talks whose voice it does not carry as
|
||||
/// media (a `Speaking` signal; TeamSpeak's Speex and CELT talkers are such):
|
||||
/// that is a hint, which holds until the host says it is over.
|
||||
#[derive(Default)]
|
||||
pub(crate) struct TalkTracker {
|
||||
last: HashMap<u16, Instant>,
|
||||
hinted: HashSet<u16>,
|
||||
}
|
||||
|
||||
impl TalkTracker {
|
||||
/// A packet of `client` arrived; whether this starts its talking.
|
||||
pub(crate) fn heard(&mut self, client: u16, now: Instant) -> bool {
|
||||
let was = self.is_talking(client);
|
||||
self.last.insert(client, now);
|
||||
!was
|
||||
}
|
||||
|
||||
/// The host says `client` talks or has stopped; whether this changes
|
||||
/// whether it is talking.
|
||||
pub(crate) fn hint(&mut self, client: u16, talking: bool) -> bool {
|
||||
let was = self.is_talking(client);
|
||||
if talking {
|
||||
self.hinted.insert(client);
|
||||
} else {
|
||||
self.hinted.remove(&client);
|
||||
}
|
||||
was != self.is_talking(client)
|
||||
}
|
||||
|
||||
/// Forget the hints about clients `present` does not hold any more: a
|
||||
/// client that left cannot say it stopped.
|
||||
pub(crate) fn retain_hints(&mut self, present: impl Fn(u16) -> bool) {
|
||||
self.hinted.retain(|client| present(*client));
|
||||
}
|
||||
|
||||
/// The talkers that have been silent long enough, no longer talking.
|
||||
pub(crate) fn expire(&mut self, now: Instant) -> Vec<u16> {
|
||||
let mut silent: Vec<u16> = self
|
||||
.last
|
||||
.iter()
|
||||
.filter(|(_, last)| now.saturating_duration_since(**last) >= TALK_SILENCE)
|
||||
.map(|(client, _)| *client)
|
||||
.collect();
|
||||
silent.sort_unstable();
|
||||
for client in &silent {
|
||||
self.last.remove(client);
|
||||
}
|
||||
silent.retain(|client| !self.hinted.contains(client));
|
||||
silent
|
||||
}
|
||||
|
||||
pub(crate) fn is_talking(&self, client: u16) -> bool {
|
||||
self.last.contains_key(&client) || self.hinted.contains(&client)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// 20 ms of CELT, mono, one frame.
|
||||
const OPUS_20_MS: [u8; 3] = [0x98, 0x01, 0x02];
|
||||
|
||||
fn voice(payload: &[u8]) -> EncodedVoice {
|
||||
EncodedVoice { codec: VoiceCodec::Voice, payload: payload.to_vec() }
|
||||
}
|
||||
|
||||
fn view(packet: &MediaPacket) -> RtpView<'_> {
|
||||
RtpView::parse(&packet.rtp).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn our_voice_is_sequenced_stamped_and_marked() {
|
||||
let mut up = Uplink::default();
|
||||
let first = up.frame(8, &voice(&OPUS_20_MS)).unwrap();
|
||||
let second = up.frame(8, &voice(&OPUS_20_MS)).unwrap();
|
||||
assert_eq!((first.flow.slot(), first.flow.sub()), (8, 0));
|
||||
let (a, b) = (view(&first), view(&second));
|
||||
assert_eq!((a.sequence(), a.timestamp(), a.marker()), (0, 0, true));
|
||||
assert_eq!((b.sequence(), b.timestamp(), b.marker()), (1, OPUS_20_MS_TICKS, false));
|
||||
assert_eq!((a.ssrc(), a.payload_type()), (first.flow.0, PT_OPUS));
|
||||
assert_eq!(a.payload(), OPUS_20_MS);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_end_is_one_empty_packet_and_the_next_spurt_has_a_marker() {
|
||||
let mut up = Uplink::default();
|
||||
up.frame(8, &voice(&OPUS_20_MS)).unwrap();
|
||||
let end = up.frame(8, &voice(&[])).unwrap();
|
||||
assert!(view(&end).payload().is_empty() && !view(&end).marker());
|
||||
assert_eq!(view(&end).sequence(), 1);
|
||||
let next = up.frame(8, &voice(&OPUS_20_MS)).unwrap();
|
||||
assert!(view(&next).marker());
|
||||
assert_eq!(view(&next).sequence(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_sequence_wraps() {
|
||||
let mut up = Uplink { sequence: u16::MAX, ..Default::default() };
|
||||
up.frame(8, &voice(&OPUS_20_MS)).unwrap();
|
||||
let wrapped = up.frame(8, &voice(&OPUS_20_MS)).unwrap();
|
||||
assert_eq!(view(&wrapped).sequence(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn received_voice_is_split_into_slot_sub_flow_sequence_and_codec() {
|
||||
let flow = FlowId::new(9, 0);
|
||||
let mut header = RtpHeader::new(PT_OPUS, 513, 0);
|
||||
header.marker = true;
|
||||
let mut rtp = BytesMut::new();
|
||||
header.write(flow, &mut rtp).unwrap();
|
||||
rtp.extend_from_slice(&OPUS_20_MS);
|
||||
let packet = MediaPacket { flow, rtp: rtp.freeze() };
|
||||
let got = Incoming::parse(&packet).unwrap();
|
||||
assert_eq!(
|
||||
got,
|
||||
Incoming {
|
||||
slot: 9,
|
||||
whisper: false,
|
||||
sequence: 513,
|
||||
codec: VoiceCodec::Voice,
|
||||
payload: OPUS_20_MS.to_vec()
|
||||
}
|
||||
);
|
||||
let voice = got.voice(8);
|
||||
assert_eq!((voice.talker, voice.seq, voice.whisper), (TalkerId(8), 513, false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn whispers_stereo_ends_and_what_is_no_voice() {
|
||||
let packet = |flow: FlowId, payload: &[u8]| {
|
||||
let mut rtp = BytesMut::new();
|
||||
RtpHeader::new(PT_OPUS, 1, 0).write(flow, &mut rtp).unwrap();
|
||||
rtp.extend_from_slice(payload);
|
||||
MediaPacket { flow, rtp: rtp.freeze() }
|
||||
};
|
||||
assert!(Incoming::parse(&packet(FlowId::new(9, 3), &OPUS_20_MS)).unwrap().whisper);
|
||||
assert!(!Incoming::parse(&packet(FlowId::new(9, 7), &OPUS_20_MS)).unwrap().whisper);
|
||||
let stereo = [OPUS_20_MS[0] | 0x04, 1, 2];
|
||||
assert_eq!(
|
||||
Incoming::parse(&packet(FlowId::new(9, 0), &stereo)).unwrap().codec,
|
||||
VoiceCodec::Music
|
||||
);
|
||||
let end = Incoming::parse(&packet(FlowId::new(9, 0), &[])).unwrap();
|
||||
assert!(end.payload.is_empty() && end.voice(8).is_end());
|
||||
// Feedback and probes are no voice.
|
||||
assert!(
|
||||
Incoming::parse(&MediaPacket { flow: FlowId::FEEDBACK, rtp: Default::default() })
|
||||
.is_none()
|
||||
);
|
||||
assert!(
|
||||
Incoming::parse(&MediaPacket { flow: FlowId::PROBE, rtp: Default::default() })
|
||||
.is_none()
|
||||
);
|
||||
assert!(
|
||||
Incoming::parse(&MediaPacket { flow: FlowId::new(9, 0), rtp: vec![1, 2].into() })
|
||||
.is_none()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_talker_starts_with_a_packet_and_stops_400_ms_after_its_last() {
|
||||
let mut talk = TalkTracker::default();
|
||||
let t0 = Instant::now();
|
||||
assert!(talk.heard(8, t0));
|
||||
assert!(!talk.heard(8, t0 + Duration::from_millis(100)), "already talking");
|
||||
assert!(talk.heard(9, t0 + Duration::from_millis(150)));
|
||||
assert!(talk.is_talking(8));
|
||||
// 399 ms after 8's last packet: still talking.
|
||||
assert!(talk.expire(t0 + Duration::from_millis(499)).is_empty());
|
||||
assert_eq!(talk.expire(t0 + Duration::from_millis(500)), [8]);
|
||||
assert!(!talk.is_talking(8) && talk.is_talking(9));
|
||||
assert_eq!(talk.expire(t0 + Duration::from_millis(551)), [9]);
|
||||
// A packet after the silence starts it again.
|
||||
assert!(talk.heard(8, t0 + Duration::from_secs(2)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_host_that_says_someone_talks_is_believed_until_it_says_otherwise() {
|
||||
let mut talk = TalkTracker::default();
|
||||
let t0 = Instant::now();
|
||||
// A talker whose voice is no media: on, and no silence ends it.
|
||||
assert!(talk.hint(8, true));
|
||||
assert!(!talk.hint(8, true), "already talking");
|
||||
assert!(talk.is_talking(8));
|
||||
assert!(talk.expire(t0 + Duration::from_secs(60)).is_empty());
|
||||
assert!(talk.hint(8, false));
|
||||
assert!(!talk.is_talking(8));
|
||||
// A talker with media that the host also names: the media ends it, when
|
||||
// the host has said it is over (in either order).
|
||||
assert!(talk.heard(9, t0));
|
||||
assert!(!talk.hint(9, true), "heard already");
|
||||
assert!(talk.expire(t0 + Duration::from_millis(500)).is_empty(), "the host still says so");
|
||||
assert!(talk.is_talking(9));
|
||||
assert!(talk.hint(9, false));
|
||||
assert!(!talk.is_talking(9));
|
||||
assert!(talk.heard(10, t0));
|
||||
assert!(!talk.hint(10, false), "the media goes on");
|
||||
assert_eq!(talk.expire(t0 + Duration::from_millis(500)), [10]);
|
||||
// A hint about somebody who is gone is forgotten.
|
||||
assert!(talk.hint(11, true));
|
||||
talk.retain_hints(|client| client != 11);
|
||||
assert!(!talk.is_talking(11));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,330 @@
|
||||
//! The engine's seam to the server its voice source talks to.
|
||||
//!
|
||||
//! A session merges up to three sources (voice, gateway, query). The *voice*
|
||||
//! source is the connection that is visible on the server, can talk and
|
||||
//! carries chat, files, pokes, offline messages and streams. The engine holds
|
||||
//! it as a `voelin_proto::link::Session`, the backend-neutral interface of the
|
||||
//! protocol repository, and knows nothing else of the server software behind
|
||||
//! it: which backend makes the `Session` is the scheme of the address, and
|
||||
//! [`Backends`] is the registry of connectors by scheme
|
||||
//! ([`Backends::default`] has the TeamSpeak one,
|
||||
//! [`crate::ts::TsConnector`]; a Voelin host's QUIC connector will be
|
||||
//! another). [`VoiceOptions`] says what to connect to and as whom.
|
||||
//!
|
||||
//! Inside the crate `session.rs` merges and routes, and an adapter below it
|
||||
//! turns what it asks into `Session` calls and what the `Session` pushes into
|
||||
//! what it hears (`link/session_link.rs`, with `project.rs` and `media.rs`);
|
||||
//! `docs/session-seam.md` describes the mapping row by row.
|
||||
|
||||
mod backends;
|
||||
mod connect;
|
||||
#[cfg(test)]
|
||||
mod fake_link_tests;
|
||||
#[cfg(test)]
|
||||
mod fake_tests;
|
||||
pub(crate) mod media;
|
||||
pub(crate) mod project;
|
||||
mod session_link;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
pub use backends::Backends;
|
||||
pub(crate) use backends::{
|
||||
LocalConnected, LocalConnector, LocalCtx, StreamEvent, StreamPort, without_query,
|
||||
};
|
||||
pub(crate) use connect::{VERSION_PARAM, connect_params};
|
||||
pub(crate) use session_link::SessionLink;
|
||||
|
||||
use std::path::PathBuf;
|
||||
use std::pin::Pin;
|
||||
use std::sync::Arc;
|
||||
|
||||
use tokio::io::{AsyncRead, AsyncWrite};
|
||||
use tokio::sync::{broadcast, oneshot};
|
||||
use voelin_audio::{EncodedVoice, VoicePacket};
|
||||
use voelin_identity::IdentityBlob;
|
||||
use voelin_model::{Capabilities, ChannelId, ChatMessage, ChatTarget, Presence};
|
||||
use voelin_stream::PeerConfig;
|
||||
|
||||
use crate::files::{Report, RequestId, Sink, TransferId};
|
||||
use crate::settings::SharedSettings;
|
||||
use crate::stream::{OwnStreamEvent, StreamCmd, StreamFrame};
|
||||
use crate::{BackendInfo, Event, SessionId};
|
||||
|
||||
/// What a voice connection needs to know: the server, who to be, where to
|
||||
/// join ([`Command::ConnectVoice`](crate::Command::ConnectVoice)).
|
||||
///
|
||||
/// Nothing in it belongs to one kind of server: what a connector needs of it
|
||||
/// that is its own (a TeamSpeak identity, the client version to claim) is in
|
||||
/// the `identity` blob and the `client_version` spec, which the connector of
|
||||
/// the address reads.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct VoiceOptions {
|
||||
/// The server: `host[:port]` of a TeamSpeak bookmark, or an address with a
|
||||
/// scheme (`ts3server://`, `teamspeak://`, a Voelin host's `voelin://`)
|
||||
/// that picks the connector ([`Backends`]).
|
||||
pub address: String,
|
||||
/// The name shown on the server: `Hello.nickname` to a Voelin host, the
|
||||
/// client name on a TeamSpeak server (which may refuse or change it). When
|
||||
/// it is empty, the `nickname` parameter of an `address` that is a
|
||||
/// TeamSpeak link applies.
|
||||
pub nickname: String,
|
||||
/// The identity to connect with: a TeamSpeak identity
|
||||
/// ([`crate::ts::identity::to_blob`]) for a TeamSpeak server, a Voelin key
|
||||
/// for a Voelin host. None lets the connector make one up (a TeamSpeak
|
||||
/// connection generates an identity, which a server then knows as a new
|
||||
/// client).
|
||||
pub identity: Option<IdentityBlob>,
|
||||
/// The client version a TeamSpeak server is shown, as a spec for
|
||||
/// [`crate::ts::versions::resolve`] (`default`, `generic`, an index, or
|
||||
/// `<platform>@<version>`); `None` is the native platform's. A spec that is
|
||||
/// none ends the connect with the reason. Other backends ignore it.
|
||||
pub client_version: Option<String>,
|
||||
/// The password of the server (`Hello.password`), for one that has a
|
||||
/// password. When it is `None` or empty, the `password` parameter of an
|
||||
/// `address` that is a TeamSpeak link applies. Not the password of
|
||||
/// `channel` (that is `channel_password`).
|
||||
pub server_password: Option<String>,
|
||||
/// Channel path to join, e.g. `Lobby/Sub`, or `/<id>`.
|
||||
pub channel: Option<String>,
|
||||
/// The password of `channel`.
|
||||
pub channel_password: Option<String>,
|
||||
/// A privilege key to use when connecting.
|
||||
pub token: Option<String>,
|
||||
/// Open the audio devices (capture and playback).
|
||||
pub audio: bool,
|
||||
/// Network settings for stream peer connections (TeamSpeak 6).
|
||||
pub stream_peer: PeerConfig,
|
||||
}
|
||||
|
||||
impl VoiceOptions {
|
||||
/// Options for `address` and `nickname`; everything else is left to the
|
||||
/// connector.
|
||||
pub fn new(address: impl Into<String>, nickname: impl Into<String>) -> Self {
|
||||
Self {
|
||||
address: address.into(),
|
||||
nickname: nickname.into(),
|
||||
identity: None,
|
||||
client_version: None,
|
||||
server_password: None,
|
||||
channel: None,
|
||||
channel_password: None,
|
||||
token: None,
|
||||
audio: false,
|
||||
stream_peer: PeerConfig::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What the engine gives a link besides the options: where the connection
|
||||
/// answers the requests the session need not see, and what it shares with
|
||||
/// the session's other parts.
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct LinkCtx {
|
||||
pub(crate) session: SessionId,
|
||||
pub(crate) events: broadcast::Sender<Event>,
|
||||
/// The frames of watched streams (kept off the event bus).
|
||||
pub(crate) frames: broadcast::Sender<StreamFrame>,
|
||||
pub(crate) settings: SharedSettings,
|
||||
}
|
||||
|
||||
impl LinkCtx {
|
||||
/// The session this connection belongs to.
|
||||
pub(crate) fn session(&self) -> SessionId {
|
||||
self.session
|
||||
}
|
||||
|
||||
/// Tell the engine's event bus something (a request's answer, a
|
||||
/// transfer's progress).
|
||||
pub(crate) fn emit(&self, event: Event) {
|
||||
let _ = self.events.send(event);
|
||||
}
|
||||
|
||||
pub(crate) fn done(&self, request: RequestId, result: Result<(), String>) {
|
||||
self.emit(Event::RequestDone { session: self.session, request, result });
|
||||
}
|
||||
}
|
||||
|
||||
/// A file on the server: channel, its password, path.
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) struct Remote {
|
||||
pub channel: ChannelId,
|
||||
pub password: Option<String>,
|
||||
pub path: String,
|
||||
}
|
||||
|
||||
/// A boxed stream of bytes to read: the body of a file the server sends.
|
||||
pub(crate) type BoxRead = Pin<Box<dyn AsyncRead + Send>>;
|
||||
|
||||
/// A connection that can be read and written: a file transfer connection.
|
||||
pub(crate) trait Duplex: AsyncRead + AsyncWrite + Send {}
|
||||
|
||||
impl<T: AsyncRead + AsyncWrite + Send> Duplex for T {}
|
||||
|
||||
/// A boxed [`Duplex`].
|
||||
pub(crate) type BoxDuplex = Pin<Box<dyn Duplex>>;
|
||||
|
||||
/// What the session asks of a connection.
|
||||
pub(crate) enum LinkCmd {
|
||||
SendChat(ChatTarget, String),
|
||||
Move(ChannelId, Option<String>),
|
||||
SetInputMuted(bool),
|
||||
SetOutputMuted(bool),
|
||||
/// An encoded voice frame from the audio thread.
|
||||
Audio(EncodedVoice),
|
||||
/// A stream command; the link answers on the event bus. Only sent while
|
||||
/// the connection's capabilities include streams.
|
||||
Stream(StreamCmd),
|
||||
Poke {
|
||||
client: u16,
|
||||
message: String,
|
||||
},
|
||||
ListFiles {
|
||||
request: RequestId,
|
||||
dir: Remote,
|
||||
},
|
||||
/// Download `file`; `transfer` if the user can cancel it.
|
||||
Download {
|
||||
transfer: Option<TransferId>,
|
||||
file: Remote,
|
||||
sink: Sink,
|
||||
report: Report,
|
||||
},
|
||||
Upload {
|
||||
transfer: Option<TransferId>,
|
||||
file: Remote,
|
||||
from: PathBuf,
|
||||
overwrite: bool,
|
||||
resume: bool,
|
||||
report: Report,
|
||||
},
|
||||
CancelTransfer(TransferId),
|
||||
/// Open a file of the server for reading, from `offset`: the transfer
|
||||
/// connection itself, and the file's size in all, once the server has
|
||||
/// agreed (the text of the failure otherwise). The engine copies the
|
||||
/// bytes, reports the progress and cancels by dropping the connection, so
|
||||
/// this does not use [`LinkCmd::Download`]'s sink and report.
|
||||
OpenRead {
|
||||
file: Remote,
|
||||
offset: u64,
|
||||
reply: oneshot::Sender<Result<(u64, BoxRead), String>>,
|
||||
},
|
||||
/// Open a file of the server for writing: the transfer connection and the
|
||||
/// position the server wants the bytes from (the size it already has, if
|
||||
/// `resume`). The engine writes the bytes and ends the connection.
|
||||
OpenWrite {
|
||||
file: Remote,
|
||||
/// The file's size in all.
|
||||
size: u64,
|
||||
overwrite: bool,
|
||||
resume: bool,
|
||||
reply: oneshot::Sender<Result<(u64, BoxDuplex), String>>,
|
||||
},
|
||||
DeleteFiles {
|
||||
/// `None`: best effort, nobody waits for the answer.
|
||||
request: Option<RequestId>,
|
||||
channel: ChannelId,
|
||||
password: Option<String>,
|
||||
paths: Vec<String>,
|
||||
},
|
||||
RenameFile {
|
||||
request: RequestId,
|
||||
from: Remote,
|
||||
to: Remote,
|
||||
},
|
||||
CreateDirectory {
|
||||
request: RequestId,
|
||||
dir: Remote,
|
||||
},
|
||||
/// Announce our avatar's hash (empty: no avatar).
|
||||
SetAvatarHash {
|
||||
request: Option<RequestId>,
|
||||
hash: String,
|
||||
},
|
||||
OfflineList {
|
||||
request: RequestId,
|
||||
},
|
||||
OfflineGet {
|
||||
request: RequestId,
|
||||
id: u32,
|
||||
},
|
||||
OfflineAdd {
|
||||
request: RequestId,
|
||||
to_uid: String,
|
||||
subject: String,
|
||||
text: String,
|
||||
},
|
||||
OfflineDelete {
|
||||
request: RequestId,
|
||||
id: u32,
|
||||
},
|
||||
OfflineFlag {
|
||||
request: RequestId,
|
||||
id: u32,
|
||||
read: bool,
|
||||
},
|
||||
Disconnect,
|
||||
}
|
||||
|
||||
/// What a connection tells the session.
|
||||
pub(crate) enum LinkEvent {
|
||||
Connected {
|
||||
name: String,
|
||||
/// The server software, and what it can do (the connection knows
|
||||
/// both from the server's version).
|
||||
backend: BackendInfo,
|
||||
capabilities: Capabilities,
|
||||
/// Our client id when the link connected. TeamSpeak's own reconnect gives
|
||||
/// a new one, which is not announced; the engine follows it in the
|
||||
/// snapshots by our unique id.
|
||||
own_client: u16,
|
||||
/// The server's unique id.
|
||||
server_uid: String,
|
||||
/// Our unique id as the server knows it.
|
||||
own_uid: Option<String>,
|
||||
},
|
||||
/// The server's channels and clients as they are now.
|
||||
Presence(Box<Presence>),
|
||||
/// The channel we are in, after every [`LinkEvent::Presence`]. The engine
|
||||
/// derives it itself, from our own voice state in the snapshots of the
|
||||
/// `Session` it talks to, and so follows us when TeamSpeak's reconnect makes
|
||||
/// us another client. What an in-process link such as `TsLink` says here only
|
||||
/// tells the TeamSpeak `Session` made of it that a move has arrived.
|
||||
OwnChannel(ChannelId),
|
||||
Chat(ChatMessage),
|
||||
Poke {
|
||||
from: u16,
|
||||
from_uid: Option<String>,
|
||||
from_name: String,
|
||||
message: String,
|
||||
},
|
||||
/// Incoming voice for the audio thread.
|
||||
Audio(VoicePacket),
|
||||
/// Who is talking (on, and off again when it stopped). The engine derives
|
||||
/// it from the media of its `Session` (protocol section 6.4). What an
|
||||
/// in-process link such as `TsLink` says here reaches the engine as a
|
||||
/// speaking hint next to the media: that is what shows the talkers whose
|
||||
/// packets the link does not forward as Opus (Speex, CELT).
|
||||
Talking {
|
||||
client: u16,
|
||||
talking: bool,
|
||||
},
|
||||
/// Our own stream's life, for the gateway directory.
|
||||
OwnStream(OwnStreamEvent),
|
||||
/// An Opus frame (48 kHz) of a watched stream, for the audio thread
|
||||
/// ([`VoiceOptions::audio`]); `time` is its RTP time on the 48 kHz
|
||||
/// clock.
|
||||
StreamAudio {
|
||||
stream: String,
|
||||
time: u64,
|
||||
data: Arc<[u8]>,
|
||||
},
|
||||
/// A watched stream ended: its audio leaves the mixer.
|
||||
StreamAudioEnded(String),
|
||||
/// A command failed (the connection stays).
|
||||
Error(String),
|
||||
/// The connection ended; the reason if it was not asked for. Sent once;
|
||||
/// the stream task's closing reports may still follow (see the module
|
||||
/// documentation).
|
||||
Disconnected(Option<String>),
|
||||
}
|
||||
@@ -0,0 +1,214 @@
|
||||
//! The engine's view of a session's replica, in the client's older model
|
||||
//! (`docs/session-seam.md` section 5.3).
|
||||
//!
|
||||
//! The UI and `session.rs` still speak `Presence`, `ChannelInfo`,
|
||||
//! `ClientInfo`, `ServerDetails` and `ChatMessage`. [`presence`] and
|
||||
//! [`chat_message`] project the replica into them with
|
||||
//! `voelin_model::replica::convert`, and fix up where that says less than the
|
||||
//! older model does (F1 to F10 of the design). The fix-ups apply the
|
||||
//! TeamSpeak gateway's id rules of protocol section 11.1, so the UI keeps the
|
||||
//! ids it has; they go when the UI reads the replica.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use voelin_model::replica::{Replica, convert};
|
||||
use voelin_model::{ChatMessage, ChatTarget, GroupInfo, Presence, ServerDetails};
|
||||
use voelin_proto::link::Features;
|
||||
use voelin_proto::v1::{self, ChannelKind, MessageFlag, RoleScope};
|
||||
|
||||
use super::media::TalkTracker;
|
||||
use crate::ts::ts_session::entities::user_uid;
|
||||
use crate::ts::ts_session::ids::{self, FOREIGN_SYSTEM};
|
||||
|
||||
/// What the projection needs to know besides the replica.
|
||||
pub(crate) struct View<'a> {
|
||||
pub(crate) replica: &'a Replica,
|
||||
/// The server of the session.
|
||||
pub(crate) server: u64,
|
||||
/// The backend is TeamSpeak (`Welcome.host.backend.product`): its id rules
|
||||
/// (channel groups) are undone.
|
||||
pub(crate) teamspeak: bool,
|
||||
/// The version the host said (`Welcome.host.backend.version`).
|
||||
pub(crate) version: &'a str,
|
||||
pub(crate) features: &'a Features,
|
||||
/// Whether the connection has streams (a port, not just the feature).
|
||||
pub(crate) streams: bool,
|
||||
pub(crate) talking: &'a TalkTracker,
|
||||
}
|
||||
|
||||
/// What a `Foreign` of TeamSpeak holds under `key`.
|
||||
fn foreign_value(
|
||||
foreign: Option<&v1::Foreign>,
|
||||
kind: &str,
|
||||
key: &str,
|
||||
) -> Option<serde_json::Value> {
|
||||
let foreign = foreign.filter(|f| f.system == FOREIGN_SYSTEM && f.kind == kind)?;
|
||||
serde_json::from_slice::<serde_json::Value>(&foreign.json).ok()?.get(key).cloned()
|
||||
}
|
||||
|
||||
/// The server's unique id as the client keys its history and aliases by it:
|
||||
/// the host's without the `ts:` of protocol section 11.2 (F3).
|
||||
pub(crate) fn server_key(uid: &str) -> String {
|
||||
uid.strip_prefix("ts:").unwrap_or(uid).to_owned()
|
||||
}
|
||||
|
||||
/// The client's older model of the server (what `LinkEvent::Presence` holds).
|
||||
pub(crate) fn presence(view: &View<'_>) -> Presence {
|
||||
let replica = view.replica;
|
||||
let server = view.server;
|
||||
// F1: only what the older model calls channels.
|
||||
let channels: Vec<&v1::Channel> = replica
|
||||
.channels(server)
|
||||
.filter(|channel| {
|
||||
!matches!(
|
||||
ChannelKind::try_from(channel.kind),
|
||||
Ok(ChannelKind::ServerChat
|
||||
| ChannelKind::Dm
|
||||
| ChannelKind::GroupDm
|
||||
| ChannelKind::Thread)
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
let by_id: BTreeMap<u64, &v1::Channel> = channels.iter().map(|c| (c.id, *c)).collect();
|
||||
let channel_infos = convert::channel_infos(&channels)
|
||||
.into_iter()
|
||||
.map(|mut info| {
|
||||
// F7: a limit of 0 is a limit, not "unlimited".
|
||||
let zero = by_id
|
||||
.get(&info.id)
|
||||
.and_then(|c| foreign_value(c.foreign.as_ref(), "channel", "max_clients"));
|
||||
if zero.and_then(|v| v.as_i64()) == Some(0) {
|
||||
info.max_clients = Some(0);
|
||||
}
|
||||
(info.id, info)
|
||||
})
|
||||
.collect();
|
||||
|
||||
let clients = replica
|
||||
.voice_states(server)
|
||||
.filter_map(|voice| {
|
||||
let user = replica.user(voice.user_id);
|
||||
let member = replica.member(server, voice.user_id);
|
||||
let mut client =
|
||||
convert::client_info(voice, user, member, replica.presence_of(voice.user_id))?;
|
||||
// F10: a unique id that is no base64 rides in `Foreign`.
|
||||
client.uid = user.and_then(user_uid);
|
||||
// F2: the client's channel group is TeamSpeak's own number.
|
||||
if view.teamspeak {
|
||||
client.channel_group = client.channel_group.map(ids::channel_group);
|
||||
}
|
||||
// F6: the client's icon.
|
||||
client.icon = foreign_value(member.and_then(|m| m.foreign.as_ref()), "client", "icon")
|
||||
.and_then(|v| v.as_u64())
|
||||
.and_then(|v| u32::try_from(v).ok())
|
||||
.unwrap_or(0);
|
||||
// F8: who is talking comes from the media.
|
||||
client.talking = view.features.has("voice").then(|| view.talking.is_talking(client.id));
|
||||
// F9: the stream flag only where there are streams.
|
||||
if !view.streams {
|
||||
client.streaming = None;
|
||||
}
|
||||
Some((client.id, client))
|
||||
})
|
||||
.collect();
|
||||
|
||||
let mut server_groups: BTreeMap<u64, GroupInfo> = BTreeMap::new();
|
||||
let mut channel_groups: BTreeMap<u64, GroupInfo> = BTreeMap::new();
|
||||
for role in replica.roles(server) {
|
||||
let mut info = convert::group_info(role);
|
||||
if role.scope == RoleScope::Channel as i32 {
|
||||
if view.teamspeak {
|
||||
info.id = ids::channel_group(info.id);
|
||||
}
|
||||
channel_groups.insert(info.id, info);
|
||||
} else {
|
||||
server_groups.insert(info.id, info);
|
||||
}
|
||||
}
|
||||
|
||||
let details = replica.server(server).map(|stub| server_details(view, stub)).unwrap_or_default();
|
||||
Presence {
|
||||
server_name: details.name.clone(),
|
||||
channels: channel_infos,
|
||||
clients,
|
||||
server: details,
|
||||
server_groups,
|
||||
channel_groups,
|
||||
}
|
||||
}
|
||||
|
||||
/// `convert::server_details` with F2 to F5.
|
||||
fn server_details(view: &View<'_>, server: &v1::Server) -> ServerDetails {
|
||||
let mut details = convert::server_details(server);
|
||||
// F3: the unique id as the client keys it.
|
||||
details.uid = details.uid.as_deref().map(server_key);
|
||||
let foreign = server.foreign.as_ref();
|
||||
// F4: the version the server sent, else the one the host reports.
|
||||
details.version = foreign_value(foreign, "server", "version")
|
||||
.and_then(|v| v.as_str().map(str::to_owned))
|
||||
.filter(|v| !v.is_empty())
|
||||
.unwrap_or_else(|| view.version.to_owned());
|
||||
// F5: the server's platform.
|
||||
details.platform = foreign_value(foreign, "server", "platform")
|
||||
.and_then(|v| v.as_str().map(str::to_owned))
|
||||
.unwrap_or_default();
|
||||
// F2: the default channel group is TeamSpeak's own number.
|
||||
if view.teamspeak {
|
||||
details.default_channel_group = details.default_channel_group.map(ids::channel_group);
|
||||
}
|
||||
details
|
||||
}
|
||||
|
||||
/// Where the older model files the messages of a channel (the replica's
|
||||
/// `chat_target`, with the unique id of F10).
|
||||
fn chat_target(replica: &Replica, channel: u64) -> ChatTarget {
|
||||
let Some(info) = replica.channel(channel) else { return ChatTarget::Channel(channel) };
|
||||
match ChannelKind::try_from(info.kind) {
|
||||
Ok(ChannelKind::ServerChat) => ChatTarget::Server,
|
||||
Ok(ChannelKind::Dm | ChannelKind::GroupDm) => {
|
||||
let own = replica.own_user();
|
||||
info.recipients
|
||||
.iter()
|
||||
.copied()
|
||||
.find(|id| *id != own)
|
||||
.and_then(|id| replica.user(id))
|
||||
.and_then(user_uid)
|
||||
.map_or(ChatTarget::Channel(channel), ChatTarget::Private)
|
||||
}
|
||||
_ => ChatTarget::Channel(channel),
|
||||
}
|
||||
}
|
||||
|
||||
/// A message of the replica as the older model has it.
|
||||
pub(crate) fn chat_message(replica: &Replica, channel: u64, id: u64) -> Option<ChatMessage> {
|
||||
let message = replica.message(channel, id)?;
|
||||
let author = replica.user(message.author_id);
|
||||
let name = Some(message.author_name.as_str())
|
||||
.filter(|name| !name.is_empty())
|
||||
.or_else(|| author.map(|u| u.name.as_str()).filter(|name| !name.is_empty()))
|
||||
.unwrap_or_default();
|
||||
Some(ChatMessage {
|
||||
target: chat_target(replica, channel),
|
||||
author_name: name.to_owned(),
|
||||
author_uid: author.and_then(user_uid),
|
||||
author_id: (message.author_participant != 0)
|
||||
.then(|| u16::try_from(message.author_participant).ok())
|
||||
.flatten(),
|
||||
text: message.text.clone(),
|
||||
ts_ms: message.ts_ms,
|
||||
via_relay: message.flags & MessageFlag::Relayed as u32 != 0,
|
||||
blocked: false,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn the_ts_prefix_of_a_server_uid_goes() {
|
||||
assert_eq!(server_key("ts:abc="), "abc=");
|
||||
assert_eq!(server_key("abc="), "abc=");
|
||||
assert_eq!(server_key(""), "");
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
+141
-54
@@ -56,16 +56,16 @@ use voelin_media::mix::{
|
||||
};
|
||||
pub use voelin_media::mix::{Level, SourceState};
|
||||
use voelin_media::scale::Pyramid;
|
||||
use voelin_media::stream::EncodedFrame;
|
||||
use voelin_media::studio::Studio;
|
||||
use voelin_media::studio::output::{Packet, Track};
|
||||
use voelin_media::{
|
||||
Codec, Codecs, ContentHint, EncodedChunk, EncoderConfig, FrameRef, GpuFrame, H264Profile,
|
||||
VideoEncoder, VideoFrame,
|
||||
LayerId, LayerSet, LayerSpec, VideoEncoder, VideoFrame,
|
||||
};
|
||||
pub use voelin_media::{DecoderBackend, DecoderPreference, EncoderBackend, EncoderPreference};
|
||||
use voelin_stream::{
|
||||
EncodedFrame, FrameSource, Frequency, LayerId, LayerSet, LayerSpec, MediaFrame, MediaKind,
|
||||
MediaTime, PeerConfig, VideoCodec, VideoFormat,
|
||||
FrameSource, Frequency, MediaFrame, MediaKind, MediaTime, PeerConfig, VideoCodec, VideoFormat,
|
||||
};
|
||||
|
||||
use crate::settings::{AudioSourceKindSetting, AudioSourceSetting};
|
||||
@@ -127,13 +127,7 @@ fn spawn(name: &str, f: impl FnOnce() + Send + 'static) -> Result<JoinHandle<()>
|
||||
|
||||
/// The `voelin_media` codec of a negotiated video codec.
|
||||
pub fn media_codec(codec: VideoCodec) -> Codec {
|
||||
match codec {
|
||||
VideoCodec::Vp8 => Codec::Vp8,
|
||||
VideoCodec::Vp9 => Codec::Vp9,
|
||||
VideoCodec::H264 => Codec::H264,
|
||||
VideoCodec::Av1 => Codec::Av1,
|
||||
VideoCodec::H265 => Codec::H265,
|
||||
}
|
||||
crate::stream::media_codec(codec)
|
||||
}
|
||||
|
||||
/// The H.264 profile an encoder of `format` makes (Constrained High for
|
||||
@@ -2686,7 +2680,7 @@ pub struct DecodeStats {
|
||||
pub bytes: u64,
|
||||
/// Pictures decoded per second and video received in bit/s, over the
|
||||
/// time since the previous [`VideoPipeline::stats`] (at least
|
||||
/// [`RATE_WINDOW`]; the watch screen asks once a second).
|
||||
/// `RATE_WINDOW`; the watch screen asks once a second).
|
||||
pub fps: u32,
|
||||
pub bitrate: u64,
|
||||
}
|
||||
@@ -3263,9 +3257,13 @@ impl LocalPreview {
|
||||
}
|
||||
|
||||
/// The first and last column of the rectangle in the middle row of a
|
||||
/// decoded test pattern. Checks that pixels further than two columns from
|
||||
/// its edges (which the codec blurs) have the colour of the rectangle or
|
||||
/// the background.
|
||||
/// decoded test pattern, after checking the row's structure: background, one
|
||||
/// run of the rectangle, background. A pixel is whichever of the pattern's two
|
||||
/// colours it is nearer to; it is not asked to be within some distance of one,
|
||||
/// because an encoder that falls behind lowers its quality (the VP8 speed
|
||||
/// control of the streamer does) and then moves a flat colour by 30 and more
|
||||
/// per channel, still nowhere near the other colour. The two columns at each
|
||||
/// edge, which the codec blurs, may be either.
|
||||
#[cfg(all(test, feature = "media-desktop"))]
|
||||
pub(crate) fn rectangle_span(picture: &VideoFrame) -> (u32, u32) {
|
||||
use voelin_media::capture::synthetic::{BACKGROUND, RECT_COLOR};
|
||||
@@ -3276,15 +3274,23 @@ pub(crate) fn rectangle_span(picture: &VideoFrame) -> (u32, u32) {
|
||||
let i = ((y * picture.width + x) * 4) as usize;
|
||||
[rgba[i], rgba[i + 1], rgba[i + 2]]
|
||||
};
|
||||
let close = |p: [u8; 3], c: [u8; 3]| p.iter().zip(c).all(|(a, b)| a.abs_diff(b) <= 24);
|
||||
let inside: Vec<u32> = (0..picture.width).filter(|&x| close(pixel(x), RECT_COLOR)).collect();
|
||||
let (&a, &b) = inside.first().zip(inside.last()).expect("no rectangle in the middle row");
|
||||
for x in 0..picture.width {
|
||||
if x + 2 < a || x > b + 2 {
|
||||
assert!(close(pixel(x), BACKGROUND), "pixel {x},{y} is {:?}", pixel(x));
|
||||
} else if (a + 2..=b.saturating_sub(2)).contains(&x) {
|
||||
assert!(close(pixel(x), RECT_COLOR), "pixel {x},{y} is {:?}", pixel(x));
|
||||
}
|
||||
let distance = |p: [u8; 3], c: [u8; 3]| -> u32 {
|
||||
p.iter().zip(c).map(|(a, b)| u32::from(a.abs_diff(b)).pow(2)).sum()
|
||||
};
|
||||
let rectangle = |x: u32| {
|
||||
let p = pixel(x);
|
||||
distance(p, RECT_COLOR) < distance(p, BACKGROUND)
|
||||
};
|
||||
let a = (0..picture.width).find(|&x| rectangle(x)).expect("no rectangle in the middle row");
|
||||
let b = (0..picture.width).rfind(|&x| rectangle(x)).unwrap();
|
||||
// One run: everything between its ends, but the blurred edges, is the
|
||||
// rectangle's. Whatever is outside is the background by the choice of a and b.
|
||||
for x in a + 2..=b.saturating_sub(2) {
|
||||
assert!(
|
||||
rectangle(x),
|
||||
"pixel {x},{y} is {:?}, in the middle of the rectangle (columns {a} to {b})",
|
||||
pixel(x)
|
||||
);
|
||||
}
|
||||
(a, b)
|
||||
}
|
||||
@@ -3416,7 +3422,14 @@ mod tests {
|
||||
assert!(all.is_hardware(backend), "{codec} offered in software");
|
||||
}
|
||||
if all.encoder_codecs().contains(&Codec::H264) && !offer.contains(&Codec::H264) {
|
||||
assert_eq!(offer_codecs(&all, Codec::H264)[..2], [Codec::H264, Codec::Vp8]);
|
||||
// H.264 in software only (so not in `offer`): it leads the same
|
||||
// codecs as with VP8 as the stream codec, whichever hardware
|
||||
// encoders this machine has (a hardware AV1 or VP9 encoder ranks
|
||||
// before VP8, so VP8 is not always second).
|
||||
let h264 = offer_codecs(&all, Codec::H264);
|
||||
assert_eq!(h264[0], Codec::H264, "{h264:?}");
|
||||
assert_eq!(h264.len(), offer.len() + 1, "{h264:?} against {offer:?}");
|
||||
assert!(offer.iter().all(|c| h264.contains(c)), "{h264:?} against {offer:?}");
|
||||
}
|
||||
// Whatever this machine has: codecs every TeamSpeak client decodes
|
||||
// come before H.264, HEVC last, and the automatic stream codec is
|
||||
@@ -3429,10 +3442,23 @@ mod tests {
|
||||
let ranks: Vec<_> = offer[1..].iter().map(rank).collect();
|
||||
assert!(ranks.is_sorted(), "{offer:?}");
|
||||
assert!(preferred_codec(&all, None).is_some_and(decoded_everywhere), "{all:?}");
|
||||
assert_eq!(
|
||||
preferred_codec(&all, Some(Codec::H264)).is_some(),
|
||||
all.encoder_codecs().contains(&Codec::H264)
|
||||
);
|
||||
// A configured codec is the stream codec when this machine can encode
|
||||
// it; otherwise the result is the automatic choice,
|
||||
// `preferred_codec(&all, None)` (some codec on any machine that
|
||||
// encodes anything). Whether H.264 is encodable depends on the
|
||||
// machine (a desktop with FFmpeg or a GPU has an encoder, a CI
|
||||
// runner has none), so the expectation follows `all.encoder_codecs()`.
|
||||
let h264 = preferred_codec(&all, Some(Codec::H264));
|
||||
if all.encoder_codecs().contains(&Codec::H264) {
|
||||
assert_eq!(h264, Some(Codec::H264), "{all:?}");
|
||||
} else {
|
||||
assert_eq!(h264, preferred_codec(&all, None), "{all:?}");
|
||||
}
|
||||
// The built-in codecs are the same everywhere (no OpenH264 loaded):
|
||||
// VP9 is encodable and wins, H.264 is not and falls back to VP8.
|
||||
assert_eq!(preferred_codec(&codecs, Some(Codec::Vp9)), Some(Codec::Vp9));
|
||||
assert_eq!(preferred_codec(&codecs, Some(Codec::H264)), preferred_codec(&codecs, None));
|
||||
assert_eq!(preferred_codec(&codecs, None), Some(Codec::Vp8));
|
||||
}
|
||||
|
||||
/// A sink whose viewers chose `codecs`; keeps every video frame with its
|
||||
@@ -3522,11 +3548,30 @@ mod tests {
|
||||
};
|
||||
told(30).await;
|
||||
assert_eq!(streamer.bitrate_kbps(), 1105);
|
||||
// Not per frame.
|
||||
let count = lock(&sink.formats).len();
|
||||
tokio::time::sleep(Duration::from_millis(200)).await;
|
||||
assert_eq!(lock(&sink.formats).len(), count);
|
||||
assert_eq!(streamer.stats().layers[0].bitrate, auto_bitrate(640, 480, 30));
|
||||
// Not per frame. The sink is told when it is attached and again by the
|
||||
// encoder before its first frame (the same format twice), so the count is
|
||||
// taken once a frame has been handed over and compared after more have;
|
||||
// the frames, not a pause, are what "per frame" counts.
|
||||
let frames_by = |frames: u64| {
|
||||
let streamer = &streamer;
|
||||
async move {
|
||||
let deadline = Instant::now() + Duration::from_secs(30);
|
||||
while streamer.stats().layers[0].frames < frames {
|
||||
assert!(Instant::now() < deadline, "{frames} frames: {:?}", streamer.stats());
|
||||
tokio::time::sleep(Duration::from_millis(20)).await;
|
||||
}
|
||||
}
|
||||
};
|
||||
frames_by(1).await;
|
||||
let (count, seen) = (lock(&sink.formats).len(), streamer.stats().layers[0].frames);
|
||||
frames_by(seen + 5).await;
|
||||
assert_eq!(lock(&sink.formats).len(), count, "told again within five frames");
|
||||
// The stats follow the sink's being told, not the other way round.
|
||||
let deadline = Instant::now() + Duration::from_secs(10);
|
||||
while streamer.stats().layers[0].bitrate != auto_bitrate(640, 480, 30) {
|
||||
assert!(Instant::now() < deadline, "{:?}", streamer.stats().layers);
|
||||
tokio::time::sleep(Duration::from_millis(20)).await;
|
||||
}
|
||||
let update = StreamerConfigUpdate { fps: Some(15), ..StreamerConfigUpdate::default() };
|
||||
streamer.reconfigure(&codecs, update).unwrap();
|
||||
told(15).await;
|
||||
@@ -3697,15 +3742,35 @@ mod tests {
|
||||
assert!((60..=68).contains(&(b - a + 1)), "{spans:?}");
|
||||
}
|
||||
assert_ne!(spans.first(), spans.last(), "the rectangle moves");
|
||||
let stats = preview.stats();
|
||||
assert!(stats.decoded >= 10 && stats.error.is_none(), "{stats:?}");
|
||||
assert_eq!(stats.codec, Some(Codec::Vp8));
|
||||
let (before_first, first) = (Instant::now(), preview.stats());
|
||||
let after_first = Instant::now();
|
||||
assert!(first.decoded >= 10 && first.error.is_none(), "{first:?}");
|
||||
assert_eq!(first.codec, Some(Codec::Vp8));
|
||||
assert_eq!(preview.streamer().backend(), "synthetic");
|
||||
// Rates over the second since: the pattern's rate, its bitrate.
|
||||
// The rates are the counters over the time since the call before. How
|
||||
// long that was the test does not say (a busy machine stretches a second,
|
||||
// and the rate of pictures it manages is not what is tested), but it lies
|
||||
// between the two spans the test timed around it.
|
||||
tokio::time::sleep(Duration::from_secs(1)).await;
|
||||
let stats = preview.stats();
|
||||
assert!((20..=40).contains(&stats.fps), "{stats:?}");
|
||||
assert!((100_000..5_000_000).contains(&stats.bitrate), "{stats:?}");
|
||||
let before_second = Instant::now();
|
||||
let second = preview.stats();
|
||||
let after_second = Instant::now();
|
||||
let longest = after_second.duration_since(before_first).as_secs_f64();
|
||||
let shortest = before_second.duration_since(after_first).as_secs_f64();
|
||||
let frames = (second.decoded - first.decoded) as f64;
|
||||
let bits = (second.bytes - first.bytes) as f64 * 8.0;
|
||||
assert!(frames > 0.0, "no picture in the second: {first:?} {second:?}");
|
||||
// (The pictures per second are rounded, the bits per second cut off.)
|
||||
let fps = f64::from(second.fps);
|
||||
assert!(
|
||||
(frames / longest - 0.5..=frames / shortest + 0.5).contains(&fps),
|
||||
"{frames} pictures in {shortest} to {longest} s are not {fps} a second"
|
||||
);
|
||||
let bitrate = second.bitrate as f64;
|
||||
assert!(
|
||||
(bits / longest - 1.0..=bits / shortest).contains(&bitrate),
|
||||
"{bits} bits in {shortest} to {longest} s are not {bitrate} a second"
|
||||
);
|
||||
}
|
||||
|
||||
/// A VP8 decoder for the pipeline tests: fails (with errors, or giving
|
||||
@@ -4129,7 +4194,8 @@ mod tests {
|
||||
};
|
||||
let streamer = Streamer::start(&codecs, config).await.unwrap();
|
||||
let wait = |what: &str, done: &dyn Fn(&StreamerStats) -> bool| {
|
||||
let deadline = Instant::now() + Duration::from_secs(5);
|
||||
// What is waited for is a state; the deadline only ends a hang.
|
||||
let deadline = Instant::now() + Duration::from_secs(30);
|
||||
loop {
|
||||
let stats = streamer.stats();
|
||||
if done(&stats) {
|
||||
@@ -4139,15 +4205,18 @@ mod tests {
|
||||
std::thread::sleep(Duration::from_millis(20));
|
||||
}
|
||||
};
|
||||
// The SineSource tone is 0.05; the second at half gain.
|
||||
// The SineSource tone is 0.05; the second at half gain. The sources are metered
|
||||
// before the mixer has made anything of them: the mix and the state of the
|
||||
// sources are waited for too, not taken to be there with the meters.
|
||||
let near = |level: f32, want: f32| (level - want).abs() < want * 0.1;
|
||||
let stats = wait("both tones", &|s| {
|
||||
let stats = wait("both tones, mixed", &|s| {
|
||||
s.audio_sources.len() == 2
|
||||
&& near(s.audio_sources[0].level.peak, 0.05)
|
||||
&& near(s.audio_sources[1].level.peak, 0.025)
|
||||
&& s.audio_sources.iter().all(|s| s.state == SourceState::Playing)
|
||||
&& s.audio_level.peak > 0.05
|
||||
&& s.audio_limiter == 1.0
|
||||
});
|
||||
assert!(stats.audio_sources.iter().all(|s| s.state == SourceState::Playing));
|
||||
assert!(stats.audio_level.peak > 0.05 && stats.audio_limiter == 1.0, "{stats:?}");
|
||||
let first = stats.audio_sources[0].id;
|
||||
|
||||
// Mute the first (kept: same id), drop the second, add the
|
||||
@@ -4163,19 +4232,31 @@ mod tests {
|
||||
streamer.reconfigure(&codecs, update).unwrap();
|
||||
assert_eq!(streamer.audio_sources().len(), 3);
|
||||
let publisher = tap::publisher_id();
|
||||
let speak = std::thread::spawn(move || {
|
||||
// 20 ms of a 0.2 tone every 20 ms, for a second.
|
||||
let chunk: Vec<f32> = (0..960).map(|i| 0.2 * (i as f32 * 0.1).sin()).collect();
|
||||
for _ in 0..50 {
|
||||
tap::microphone().publish(publisher, &chunk);
|
||||
std::thread::sleep(Duration::from_millis(20));
|
||||
let heard = Arc::new(AtomicBool::new(false));
|
||||
let speak = std::thread::spawn({
|
||||
let heard = heard.clone();
|
||||
move || {
|
||||
// 20 ms of a 0.2 tone every 20 ms, until the test has heard it: the
|
||||
// source takes what is published only from when it runs, which a
|
||||
// busy machine delays by any time (the cap ends a thread whose test
|
||||
// failed first).
|
||||
let cap = Instant::now() + Duration::from_secs(120);
|
||||
let chunk: Vec<f32> = (0..960).map(|i| 0.2 * (i as f32 * 0.1).sin()).collect();
|
||||
while !heard.load(Ordering::Relaxed) && Instant::now() < cap {
|
||||
tap::microphone().publish(publisher, &chunk);
|
||||
std::thread::sleep(Duration::from_millis(20));
|
||||
}
|
||||
}
|
||||
});
|
||||
let stats = wait("microphone in, tone muted", &|s| {
|
||||
s.audio_sources.len() == 3
|
||||
&& s.audio_sources[1].level.peak > 0.15
|
||||
&& s.audio_level.peak > 0.15
|
||||
&& s.audio_sources[2].error.as_deref().is_some_and(|e| e.contains("no window"))
|
||||
// Muted, and still metered: the tone's own level is read again.
|
||||
&& near(s.audio_sources[0].level.peak, 0.05)
|
||||
});
|
||||
heard.store(true, Ordering::Relaxed);
|
||||
speak.join().unwrap();
|
||||
assert_eq!(stats.audio_sources[0].id, first, "the kept tone keeps its source");
|
||||
assert!(stats.audio_sources[0].spec.muted);
|
||||
@@ -4207,9 +4288,15 @@ mod tests {
|
||||
assert!(streamer.has_audio(), "{:?}", streamer.audio_error());
|
||||
let mut source = EncodedSource::new(streamer);
|
||||
let mut frames = Vec::new();
|
||||
let deadline = Instant::now() + Duration::from_secs(5);
|
||||
while frames.iter().filter(|f: &&EncodedFrame| f.kind == MediaKind::Audio).count() < 10 {
|
||||
assert!(Instant::now() < deadline, "no audio");
|
||||
// Ten frames of audio and one of video, whichever the encoders make first:
|
||||
// 20 ms of audio is quickly made, and a busy machine can keep the video
|
||||
// encoder from its first frame for longer than that. The deadline only ends
|
||||
// a hang.
|
||||
let deadline = Instant::now() + Duration::from_secs(30);
|
||||
let count =
|
||||
|frames: &[EncodedFrame], kind| frames.iter().filter(|f| f.kind == kind).count();
|
||||
while count(&frames, MediaKind::Audio) < 10 || count(&frames, MediaKind::Video) < 1 {
|
||||
assert!(Instant::now() < deadline, "no audio or no video in {} frames", frames.len());
|
||||
tokio::time::sleep(Duration::from_millis(20)).await;
|
||||
source.poll_frames(Instant::now(), &mut frames);
|
||||
}
|
||||
|
||||
@@ -1,11 +1,94 @@
|
||||
//! The query source: own ServerQuery credentials, in-process observer and relays.
|
||||
|
||||
use std::fmt;
|
||||
|
||||
use tokio::sync::{broadcast, mpsc};
|
||||
use voelin_model::{ChatMessage, ChatTarget, Presence};
|
||||
use voelin_observer::{
|
||||
Observer, ObserverConfig, ObserverEvent, RelayConfig, RelayEvent, RelayPool,
|
||||
};
|
||||
|
||||
/// How a ServerQuery connection talks to the server.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum QueryTransport {
|
||||
/// The raw text protocol (TeamSpeak 3; port 10011).
|
||||
Raw,
|
||||
/// SSH.
|
||||
Ssh,
|
||||
/// The HTTP query (TeamSpeak 6; a WebQuery API key is the secret).
|
||||
Http,
|
||||
}
|
||||
|
||||
/// The user's own ServerQuery credentials for a server
|
||||
/// ([`Command::ObserveQuery`](crate::Command::ObserveQuery)): what the
|
||||
/// engine logs in with to observe a server invisibly and to relay its
|
||||
/// channels' chat. The connection's own tuning (flood protection, timeouts)
|
||||
/// is the engine's.
|
||||
#[derive(Clone, PartialEq, Eq)]
|
||||
pub struct QueryLogin {
|
||||
/// The protocol of the query interface at `address`.
|
||||
pub transport: QueryTransport,
|
||||
/// `host:port` of the query interface.
|
||||
pub address: String,
|
||||
/// The login name (raw and SSH; ignored for HTTP).
|
||||
pub user: String,
|
||||
/// The password (raw and SSH) or API key (HTTP, optional for guest access).
|
||||
pub secret: Option<String>,
|
||||
/// Select the virtual server by its voice port...
|
||||
pub server_port: Option<u16>,
|
||||
/// ...or by id (the first server when neither is given).
|
||||
pub server_id: Option<u32>,
|
||||
/// This machine's address is on the server's query allowlist, which the
|
||||
/// server's flood protection skips: the engine then sends its commands
|
||||
/// without the limit it keeps for a server that has not said so (a command
|
||||
/// the server refuses as a flood slows the connection down all the same).
|
||||
/// The application usually cannot know, and says `false`; the development
|
||||
/// servers of the tests allowlist their clients.
|
||||
pub allowlisted: bool,
|
||||
}
|
||||
|
||||
impl fmt::Debug for QueryLogin {
|
||||
// The secret is kept out of logs.
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.debug_struct("QueryLogin")
|
||||
.field("transport", &self.transport)
|
||||
.field("address", &self.address)
|
||||
.field("user", &self.user)
|
||||
.field("secret", &self.secret.as_ref().map(|_| "[secret]"))
|
||||
.field("server_port", &self.server_port)
|
||||
.field("server_id", &self.server_id)
|
||||
.field("allowlisted", &self.allowlisted)
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
impl QueryLogin {
|
||||
/// The connection the observer and the relays open.
|
||||
fn connect(&self) -> voelin_query::Connect {
|
||||
voelin_query::Connect {
|
||||
transport: match self.transport {
|
||||
QueryTransport::Raw => voelin_query::Transport::Raw,
|
||||
QueryTransport::Ssh => voelin_query::Transport::Ssh,
|
||||
QueryTransport::Http => voelin_query::Transport::Http,
|
||||
},
|
||||
addr: self.address.clone(),
|
||||
user: self.user.clone(),
|
||||
secret: self.secret.clone(),
|
||||
server_port: self.server_port,
|
||||
server_id: self.server_id,
|
||||
line: voelin_query::LineOptions {
|
||||
// Off the client-side limit only where the server skips it.
|
||||
rate_limit: if self.allowlisted {
|
||||
None
|
||||
} else {
|
||||
voelin_query::LineOptions::default().rate_limit
|
||||
},
|
||||
..Default::default()
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) enum QueryCmd {
|
||||
OpenChat(ChatTarget),
|
||||
CloseChat(ChatTarget),
|
||||
@@ -21,10 +104,11 @@ pub(crate) enum QueryEvent {
|
||||
}
|
||||
|
||||
pub(crate) async fn run(
|
||||
connect: voelin_query::Connect,
|
||||
login: QueryLogin,
|
||||
mut commands: mpsc::UnboundedReceiver<QueryCmd>,
|
||||
events: mpsc::UnboundedSender<QueryEvent>,
|
||||
) {
|
||||
let connect = login.connect();
|
||||
let observer = Observer::spawn(ObserverConfig::new(connect.clone()));
|
||||
let relays = RelayPool::new(RelayConfig::new(connect));
|
||||
let mut observed = observer.subscribe();
|
||||
@@ -88,3 +172,59 @@ pub(crate) async fn run(
|
||||
relays.close_all().await;
|
||||
let _ = events.send(QueryEvent::Disconnected);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_login_is_the_connection_the_query_crate_opens() {
|
||||
let login = QueryLogin {
|
||||
transport: QueryTransport::Ssh,
|
||||
address: "ts.example.com:10022".into(),
|
||||
user: "serveradmin".into(),
|
||||
secret: Some("hunter2".into()),
|
||||
server_port: Some(9987),
|
||||
server_id: Some(3),
|
||||
allowlisted: false,
|
||||
};
|
||||
let connect = login.connect();
|
||||
assert_eq!(connect.transport, voelin_query::Transport::Ssh);
|
||||
assert_eq!(
|
||||
(connect.addr.as_str(), connect.user.as_str(), connect.secret.as_deref()),
|
||||
("ts.example.com:10022", "serveradmin", Some("hunter2"))
|
||||
);
|
||||
assert_eq!((connect.server_port, connect.server_id), (Some(9987), Some(3)));
|
||||
for (ours, theirs) in [
|
||||
(QueryTransport::Raw, voelin_query::Transport::Raw),
|
||||
(QueryTransport::Http, voelin_query::Transport::Http),
|
||||
] {
|
||||
let connect = QueryLogin { transport: ours, ..login.clone() }.connect();
|
||||
assert_eq!(connect.transport, theirs);
|
||||
}
|
||||
// The line options are the query crate's defaults, as the UI always
|
||||
// gave them, unless the server allowlists the client.
|
||||
let line = voelin_query::LineOptions::default();
|
||||
assert!(line.rate_limit.is_some());
|
||||
assert_eq!(connect.line.rate_limit, line.rate_limit);
|
||||
assert_eq!(connect.line.timeout, line.timeout);
|
||||
let allowlisted = QueryLogin { allowlisted: true, ..login.clone() }.connect();
|
||||
assert_eq!(allowlisted.line.rate_limit, None);
|
||||
assert_eq!(allowlisted.line.timeout, line.timeout);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_secret_stays_out_of_the_debug_text() {
|
||||
let login = QueryLogin {
|
||||
transport: QueryTransport::Raw,
|
||||
address: "h:1".into(),
|
||||
user: "u".into(),
|
||||
secret: Some("hunter2".into()),
|
||||
server_port: None,
|
||||
server_id: None,
|
||||
allowlisted: false,
|
||||
};
|
||||
let text = format!("{login:?}");
|
||||
assert!(!text.contains("hunter2") && text.contains("[secret]"), "{text}");
|
||||
}
|
||||
}
|
||||
+146
-185
@@ -16,11 +16,9 @@ use tokio::time::Instant;
|
||||
|
||||
use tokio::sync::{broadcast, mpsc, watch};
|
||||
use tracing::{debug, info, warn};
|
||||
use tsclientlib::ClientId;
|
||||
use voelin_audio::AudioSettings;
|
||||
use voelin_audio::{AudioSettings, EncodedVoice, TalkerId};
|
||||
use voelin_gateway_proto::{ErrorCode, HistoryEntry, StreamEntry, StreamSpec, feature};
|
||||
use voelin_model::{ChatMessage, ChatTarget, GroupInfo, Presence, ServerDetails, badges};
|
||||
use voelin_stream::ClientState;
|
||||
|
||||
use crate::audio::{self, AudioEvent, AudioHandle, AudioIn};
|
||||
use crate::cache::{self, Fetch, FetchError, RetryHint, SharedCache, Waiter};
|
||||
@@ -31,6 +29,7 @@ use crate::gateway::{
|
||||
Push, ReactionPush,
|
||||
};
|
||||
use crate::history::{self, ChatCtx, HistoryMessage, MessageSource, SharedHistory};
|
||||
use crate::link::{LinkCmd, LinkCtx, LinkEvent, Remote, SessionLink};
|
||||
use crate::query::{self, QueryCmd, QueryEvent};
|
||||
use crate::route::{ChatRoute, Dedup, route_chat};
|
||||
use crate::settings::{
|
||||
@@ -38,10 +37,9 @@ use crate::settings::{
|
||||
PRIVACY_PRIVATE_MESSAGES, SharedSettings,
|
||||
};
|
||||
use crate::stream::{
|
||||
LayerSpec, OwnStreamEvent, PeerConfig, SrtpProfile, StreamFrame, StreamHandle, StreamInfo,
|
||||
StreamInput, StreamKind, kind_name, parse_kind,
|
||||
LayerSpec, OwnStreamEvent, StreamCmd, StreamFrame, StreamInfo, StreamKind, kind_name,
|
||||
parse_kind, parse_srtp_profiles,
|
||||
};
|
||||
use crate::voice::{self, Remote, VoiceCmd, VoiceEvent, VoiceLink};
|
||||
use crate::web;
|
||||
use crate::{Command, Event, ObserveState, SessionId, SessionState, Shared, Source, VoiceState};
|
||||
|
||||
@@ -86,14 +84,10 @@ impl SessionHandle {
|
||||
frames: broadcast::Sender<StreamFrame>,
|
||||
audio_settings: AudioSettings,
|
||||
shared: Shared,
|
||||
myts_identity: watch::Receiver<Option<Arc<tsproto::myts::Identity>>>,
|
||||
myts_data: watch::Receiver<Option<Arc<tsclientlib::MytsData>>>,
|
||||
link: Arc<SessionLink>,
|
||||
) -> Self {
|
||||
let (tx, rx) = mpsc::unbounded_channel();
|
||||
tokio::spawn(
|
||||
Session::new(id, events, frames, audio_settings, shared, myts_identity, myts_data)
|
||||
.run(rx),
|
||||
);
|
||||
tokio::spawn(Session::new(id, events, frames, audio_settings, shared, link).run(rx));
|
||||
Self { tx }
|
||||
}
|
||||
|
||||
@@ -105,13 +99,11 @@ impl SessionHandle {
|
||||
/// Events from sources, tagged with the generation of the source so events
|
||||
/// of a replaced source are ignored.
|
||||
enum SourceEvent {
|
||||
Voice(u64, VoiceEvent),
|
||||
Voice(u64, LinkEvent),
|
||||
Gateway(u64, GatewayEvent),
|
||||
Query(u64, QueryEvent),
|
||||
AudioOut(u64, tsproto_packets::packets::OutPacket),
|
||||
AudioOut(u64, EncodedVoice),
|
||||
Audio(u64, AudioEvent),
|
||||
/// Our own stream (from the stream task of that voice connection).
|
||||
OwnStream(u64, OwnStreamEvent),
|
||||
/// The gateway's stream directory after subscribing.
|
||||
Directory(u64, Result<Vec<StreamEntry>, ClientError>),
|
||||
/// The server's unique id the database remembers for an address.
|
||||
@@ -290,13 +282,13 @@ struct OwnStream {
|
||||
}
|
||||
|
||||
struct Session {
|
||||
myts_identity: watch::Receiver<Option<Arc<tsproto::myts::Identity>>>,
|
||||
myts_data: watch::Receiver<Option<Arc<tsclientlib::MytsData>>>,
|
||||
/// Starts the voice connections.
|
||||
link: Arc<SessionLink>,
|
||||
id: SessionId,
|
||||
events: broadcast::Sender<Event>,
|
||||
state: SessionState,
|
||||
generation: u64,
|
||||
voice: Option<(u64, mpsc::UnboundedSender<VoiceCmd>)>,
|
||||
voice: Option<(u64, mpsc::UnboundedSender<LinkCmd>)>,
|
||||
voice_address: String,
|
||||
voice_presence: Option<Presence>,
|
||||
nickname: String,
|
||||
@@ -318,18 +310,15 @@ struct Session {
|
||||
/// Other names of this server (`voice:<address>`, `gateway:<url>`),
|
||||
/// remembered with its unique id once a source tells it.
|
||||
aliases: Vec<String>,
|
||||
/// Streams of the voice connection (TeamSpeak 6 only).
|
||||
streams: Option<StreamHandle>,
|
||||
stream_peer: PeerConfig,
|
||||
/// The voice connection carries streams (its capabilities say so; the
|
||||
/// connection runs their task, `LinkCmd::Stream` reaches it).
|
||||
streams: bool,
|
||||
/// Simulcast layers of our stream, for the stream task.
|
||||
stream_layers: Vec<LayerSpec>,
|
||||
/// The SRTP profile setting (`Command::SetSrtpProfiles`), over the voice
|
||||
/// options' `stream_peer`.
|
||||
srtp_profiles: Option<Vec<SrtpProfile>>,
|
||||
srtp_profiles: Option<Vec<String>>,
|
||||
frames: broadcast::Sender<StreamFrame>,
|
||||
/// Channel and `client_is_streaming` of the voice presence, as last told
|
||||
/// to the streams.
|
||||
streaming_clients: BTreeMap<u16, ClientState>,
|
||||
/// The gateway's stream directory, by id.
|
||||
directory: BTreeMap<String, StreamEntry>,
|
||||
own_stream: Option<OwnStream>,
|
||||
@@ -386,15 +375,13 @@ impl Session {
|
||||
frames: broadcast::Sender<StreamFrame>,
|
||||
audio_settings: AudioSettings,
|
||||
shared: Shared,
|
||||
myts_identity: watch::Receiver<Option<Arc<tsproto::myts::Identity>>>,
|
||||
myts_data: watch::Receiver<Option<Arc<tsclientlib::MytsData>>>,
|
||||
link: Arc<SessionLink>,
|
||||
) -> Self {
|
||||
let (sources_tx, sources_rx) = mpsc::unbounded_channel();
|
||||
let Shared { settings, history, cache, contacts } = shared;
|
||||
let contacts_rx = Some(contacts.watch());
|
||||
Self {
|
||||
myts_identity,
|
||||
myts_data,
|
||||
link,
|
||||
cache,
|
||||
contacts,
|
||||
contacts_rx,
|
||||
@@ -434,12 +421,10 @@ impl Session {
|
||||
history,
|
||||
own_uid: None,
|
||||
aliases: Vec::new(),
|
||||
streams: None,
|
||||
stream_peer: PeerConfig::default(),
|
||||
streams: false,
|
||||
stream_layers: Vec::new(),
|
||||
srtp_profiles: None,
|
||||
frames,
|
||||
streaming_clients: BTreeMap::new(),
|
||||
directory: BTreeMap::new(),
|
||||
own_stream: None,
|
||||
open_chats: HashSet::new(),
|
||||
@@ -509,17 +494,19 @@ impl Session {
|
||||
fn command(&mut self, cmd: Command) {
|
||||
match cmd {
|
||||
Command::ConnectVoice { options, .. } => {
|
||||
if let Some((_, tx)) = self.voice.take() {
|
||||
let _ = tx.send(VoiceCmd::Disconnect);
|
||||
}
|
||||
// The streams end first: their shutdown goes through the
|
||||
// connection that is replaced.
|
||||
self.stop_streams("voice reconnecting");
|
||||
if let Some((_, tx)) = self.voice.take() {
|
||||
let _ = tx.send(LinkCmd::Disconnect);
|
||||
}
|
||||
let mut options = *options;
|
||||
let generation = self.next_generation();
|
||||
self.voice_address = options.address.clone();
|
||||
self.details = None;
|
||||
self.nickname = options.nickname.clone();
|
||||
self.stream_peer = options.stream_peer.clone();
|
||||
if let Some(profiles) = &self.srtp_profiles {
|
||||
self.stream_peer.srtp_profiles = profiles.clone();
|
||||
options.stream_peer.srtp_profiles = parse_srtp_profiles(profiles);
|
||||
}
|
||||
self.known_server(format!("voice:{}", options.address));
|
||||
let (cmd_tx, cmd_rx) = mpsc::unbounded_channel();
|
||||
@@ -532,14 +519,13 @@ impl Session {
|
||||
self.forward(out_rx, move |p| SourceEvent::AudioOut(generation, p));
|
||||
self.forward(audio_rx, move |e| SourceEvent::Audio(generation, e));
|
||||
}
|
||||
let link = VoiceLink {
|
||||
myts_identity: self.myts_identity.clone(),
|
||||
myts_data: self.myts_data.clone(),
|
||||
let ctx = LinkCtx {
|
||||
session: self.id,
|
||||
events: self.events.clone(),
|
||||
frames: self.frames.clone(),
|
||||
settings: self.settings.clone(),
|
||||
};
|
||||
tokio::spawn(voice::run(*options, link, cmd_rx, ev_tx));
|
||||
self.link.spawn(options, ctx, cmd_rx, ev_tx);
|
||||
self.forward(ev_rx, move |e| SourceEvent::Voice(generation, e));
|
||||
self.forget_images();
|
||||
self.voice = Some((generation, cmd_tx));
|
||||
@@ -548,7 +534,7 @@ impl Session {
|
||||
}
|
||||
Command::DisconnectVoice { .. } => {
|
||||
if let Some((_, tx)) = &self.voice {
|
||||
let _ = tx.send(VoiceCmd::Disconnect);
|
||||
let _ = tx.send(LinkCmd::Disconnect);
|
||||
}
|
||||
}
|
||||
Command::ObserveGateway { urls, identity, .. } => {
|
||||
@@ -590,7 +576,10 @@ impl Session {
|
||||
// source, the history is kept under the query address.
|
||||
if self.state.server_uid.is_none() {
|
||||
let port = connect.server_port.map(|p| format!("/{p}")).unwrap_or_default();
|
||||
self.learn_server_uid(format!("query:{}{port}", connect.addr), Source::Query);
|
||||
self.learn_server_uid(
|
||||
format!("query:{}{port}", connect.address),
|
||||
Source::Query,
|
||||
);
|
||||
self.open_histories();
|
||||
}
|
||||
let (cmd_tx, cmd_rx) = mpsc::unbounded_channel();
|
||||
@@ -626,7 +615,7 @@ impl Session {
|
||||
self.store_own(&target, &text, &route);
|
||||
}
|
||||
match route {
|
||||
ChatRoute::Voice => self.voice_cmd(VoiceCmd::SendChat(target, text)),
|
||||
ChatRoute::Voice => self.voice_cmd(LinkCmd::SendChat(target, text)),
|
||||
ChatRoute::Gateway => {
|
||||
if let Some((_, tx)) = &self.gateway {
|
||||
let _ = tx.send(GatewayCmd::SendChat(target, text));
|
||||
@@ -657,11 +646,11 @@ impl Session {
|
||||
},
|
||||
Command::Gateway { request, .. } => self.gateway_request(request),
|
||||
Command::MoveToChannel { channel, password, .. } => {
|
||||
self.voice_cmd(VoiceCmd::Move(channel, password));
|
||||
self.voice_cmd(LinkCmd::Move(channel, password));
|
||||
}
|
||||
Command::SetInputMuted { muted, .. } => {
|
||||
self.state.input_muted = muted;
|
||||
self.voice_cmd(VoiceCmd::SetInputMuted(muted));
|
||||
self.voice_cmd(LinkCmd::SetInputMuted(muted));
|
||||
if let Some(a) = &self.audio {
|
||||
a.send(AudioIn::InputMuted(muted));
|
||||
}
|
||||
@@ -669,7 +658,7 @@ impl Session {
|
||||
}
|
||||
Command::SetOutputMuted { muted, .. } => {
|
||||
self.state.output_muted = muted;
|
||||
self.voice_cmd(VoiceCmd::SetOutputMuted(muted));
|
||||
self.voice_cmd(LinkCmd::SetOutputMuted(muted));
|
||||
if let Some(a) = &self.audio {
|
||||
a.send(AudioIn::OutputMuted(muted));
|
||||
}
|
||||
@@ -692,12 +681,12 @@ impl Session {
|
||||
// again after connecting.
|
||||
Command::SetClientVolume { client, volume, .. } => {
|
||||
if let Some(a) = &self.audio {
|
||||
a.send(AudioIn::ClientVolume { client: ClientId(client), volume });
|
||||
a.send(AudioIn::ClientVolume { client: TalkerId(client), volume });
|
||||
}
|
||||
}
|
||||
Command::SetClientMuted { client, muted, .. } => {
|
||||
if let Some(a) = &self.audio {
|
||||
a.send(AudioIn::ClientMuted { client: ClientId(client), muted });
|
||||
a.send(AudioIn::ClientMuted { client: TalkerId(client), muted });
|
||||
}
|
||||
}
|
||||
Command::SetStreamVolume { stream_id, volume, .. } => {
|
||||
@@ -706,50 +695,43 @@ impl Session {
|
||||
}
|
||||
}
|
||||
Command::StartStream { setup, auto_accept, .. } => {
|
||||
self.stream_input(StreamInput::Start { setup, auto_accept });
|
||||
self.stream_input(StreamCmd::Start { setup, auto_accept });
|
||||
}
|
||||
Command::StopStream { .. } => self.stream_input(StreamInput::Stop),
|
||||
Command::StopStream { .. } => self.stream_input(StreamCmd::Stop),
|
||||
Command::AcceptViewer { viewer, accept, .. } => {
|
||||
self.stream_input(StreamInput::Respond { viewer, accept });
|
||||
self.stream_input(StreamCmd::Respond { viewer, accept });
|
||||
}
|
||||
Command::KickViewer { viewer, .. } => self.stream_input(StreamInput::Kick { viewer }),
|
||||
Command::KickViewer { viewer, .. } => self.stream_input(StreamCmd::Kick { viewer }),
|
||||
Command::SendStreamFrame { frame, .. } => {
|
||||
// Frames without a stream are dropped silently.
|
||||
if let Some(s) = &self.streams {
|
||||
s.send(StreamInput::Frame(frame));
|
||||
}
|
||||
self.stream_cmd(StreamCmd::Frame(frame));
|
||||
}
|
||||
Command::WatchStream { stream_id, .. } => {
|
||||
self.stream_input(StreamInput::Watch { stream_id });
|
||||
self.stream_input(StreamCmd::Watch { stream_id });
|
||||
}
|
||||
Command::LeaveStream { stream_id, .. } => {
|
||||
self.stream_input(StreamInput::Leave { stream_id });
|
||||
self.stream_input(StreamCmd::Leave { stream_id });
|
||||
}
|
||||
Command::RequestStreamKeyframe { stream_id, .. } => {
|
||||
self.stream_input(StreamInput::RequestKeyframe { stream_id });
|
||||
self.stream_input(StreamCmd::RequestKeyframe { stream_id });
|
||||
}
|
||||
Command::StreamUndecodable { stream_id, .. } => {
|
||||
self.stream_input(StreamInput::Undecodable { stream_id });
|
||||
self.stream_input(StreamCmd::Undecodable { stream_id });
|
||||
}
|
||||
Command::SetWatchLayer { stream_id, layer, .. } => {
|
||||
self.stream_input(StreamInput::WatchLayer { stream_id, layer });
|
||||
self.stream_input(StreamCmd::WatchLayer { stream_id, layer });
|
||||
}
|
||||
// Kept for streams started later, also without a connection.
|
||||
Command::SetStreamLayers { layers, .. } => {
|
||||
self.stream_layers = layers.clone();
|
||||
if let Some(s) = &self.streams {
|
||||
s.send(StreamInput::Layers(layers));
|
||||
}
|
||||
self.stream_cmd(StreamCmd::Layers(layers));
|
||||
}
|
||||
Command::SetSrtpProfiles(profiles) => {
|
||||
self.stream_peer.srtp_profiles = profiles.clone();
|
||||
self.srtp_profiles = Some(profiles.clone());
|
||||
if let Some(s) = &self.streams {
|
||||
s.send(StreamInput::SrtpProfiles(profiles));
|
||||
}
|
||||
self.stream_cmd(StreamCmd::SrtpProfiles(profiles));
|
||||
}
|
||||
Command::Poke { client, message, .. } => {
|
||||
self.voice_cmd(VoiceCmd::Poke { client, message });
|
||||
self.voice_cmd(LinkCmd::Poke { client, message });
|
||||
}
|
||||
Command::ListFiles { request, channel, password, path, .. } => {
|
||||
if self.voice.is_none() {
|
||||
@@ -759,7 +741,7 @@ impl Session {
|
||||
return;
|
||||
}
|
||||
let dir = Remote { channel, password, path };
|
||||
self.voice_cmd(VoiceCmd::ListFiles { request, dir });
|
||||
self.voice_cmd(LinkCmd::ListFiles { request, dir });
|
||||
}
|
||||
Command::DownloadFile { transfer, channel, password, path, to, .. } => {
|
||||
self.download(transfer, Remote { channel, password, path }, &to);
|
||||
@@ -797,34 +779,27 @@ impl Session {
|
||||
let report = self.transfer_report(transfer);
|
||||
let file = Remote { channel, password, path };
|
||||
let transfer = Some(transfer);
|
||||
self.voice_cmd(VoiceCmd::Upload {
|
||||
transfer,
|
||||
file,
|
||||
from,
|
||||
overwrite,
|
||||
resume,
|
||||
report,
|
||||
});
|
||||
self.voice_cmd(LinkCmd::Upload { transfer, file, from, overwrite, resume, report });
|
||||
}
|
||||
Command::CancelTransfer { transfer, .. } => {
|
||||
self.voice_cmd(VoiceCmd::CancelTransfer(transfer));
|
||||
self.voice_cmd(LinkCmd::CancelTransfer(transfer));
|
||||
}
|
||||
Command::DeleteFiles { request, channel, password, paths, .. } => {
|
||||
let request = Some(request);
|
||||
self.voice_request(
|
||||
request,
|
||||
VoiceCmd::DeleteFiles { request, channel, password, paths },
|
||||
LinkCmd::DeleteFiles { request, channel, password, paths },
|
||||
);
|
||||
}
|
||||
Command::RenameFile { request, channel, password, from, to, to_channel, .. } => {
|
||||
let (to_channel, to_password) = to_channel.unwrap_or((channel, password.clone()));
|
||||
let from = Remote { channel, password, path: from };
|
||||
let to = Remote { channel: to_channel, password: to_password, path: to };
|
||||
self.voice_request(Some(request), VoiceCmd::RenameFile { request, from, to });
|
||||
self.voice_request(Some(request), LinkCmd::RenameFile { request, from, to });
|
||||
}
|
||||
Command::CreateDirectory { request, channel, password, path, .. } => {
|
||||
let dir = Remote { channel, password, path };
|
||||
self.voice_request(Some(request), VoiceCmd::CreateDirectory { request, dir });
|
||||
self.voice_request(Some(request), LinkCmd::CreateDirectory { request, dir });
|
||||
}
|
||||
Command::SetAvatar { request, image, .. } => self.set_avatar(request, image),
|
||||
Command::FetchAvatar { client_uid, .. } => {
|
||||
@@ -856,7 +831,7 @@ impl Session {
|
||||
self.emit(Event::OfflineMessages { session: self.id, request, result });
|
||||
return;
|
||||
}
|
||||
self.voice_cmd(VoiceCmd::OfflineList { request });
|
||||
self.voice_cmd(LinkCmd::OfflineList { request });
|
||||
}
|
||||
Command::GetOfflineMessage { request, id, .. } => {
|
||||
if self.voice.is_none() {
|
||||
@@ -864,22 +839,20 @@ impl Session {
|
||||
self.emit(Event::OfflineMessage { session: self.id, request, result });
|
||||
return;
|
||||
}
|
||||
self.voice_cmd(VoiceCmd::OfflineGet { request, id });
|
||||
self.voice_cmd(LinkCmd::OfflineGet { request, id });
|
||||
}
|
||||
Command::SendOfflineMessage { request, to_uid, subject, text, .. } => {
|
||||
let cmd = VoiceCmd::OfflineAdd { request, to_uid, subject, text };
|
||||
let cmd = LinkCmd::OfflineAdd { request, to_uid, subject, text };
|
||||
self.voice_request(Some(request), cmd);
|
||||
}
|
||||
Command::DeleteOfflineMessage { request, id, .. } => {
|
||||
self.voice_request(Some(request), VoiceCmd::OfflineDelete { request, id });
|
||||
self.voice_request(Some(request), LinkCmd::OfflineDelete { request, id });
|
||||
}
|
||||
Command::SetOfflineMessageRead { request, id, read, .. } => {
|
||||
self.voice_request(Some(request), VoiceCmd::OfflineFlag { request, id, read });
|
||||
self.voice_request(Some(request), LinkCmd::OfflineFlag { request, id, read });
|
||||
}
|
||||
// Engine-wide.
|
||||
Command::SetMytsIdentity(_)
|
||||
| Command::SetMytsData(_)
|
||||
| Command::CloseSession { .. }
|
||||
Command::CloseSession { .. }
|
||||
| Command::TestMicrophone { .. }
|
||||
| Command::SetSetting { .. }
|
||||
| Command::ResetSetting { .. }
|
||||
@@ -894,7 +867,7 @@ impl Session {
|
||||
// Files, avatars, icons
|
||||
|
||||
/// A request to the voice connection; without one it fails at once.
|
||||
fn voice_request(&self, request: Option<RequestId>, cmd: VoiceCmd) {
|
||||
fn voice_request(&self, request: Option<RequestId>, cmd: LinkCmd) {
|
||||
match (&self.voice, request) {
|
||||
(Some(_), _) => self.voice_cmd(cmd),
|
||||
(None, Some(request)) => self.emit(Event::RequestDone {
|
||||
@@ -925,7 +898,7 @@ impl Session {
|
||||
}
|
||||
let report = self.transfer_report(transfer);
|
||||
let sink = Sink::from_target(to);
|
||||
self.voice_cmd(VoiceCmd::Download { transfer: Some(transfer), file, sink, report });
|
||||
self.voice_cmd(LinkCmd::Download { transfer: Some(transfer), file, sink, report });
|
||||
}
|
||||
|
||||
/// Upload our avatar and announce its hash, or remove it.
|
||||
@@ -938,7 +911,7 @@ impl Session {
|
||||
let Some(image) = image else {
|
||||
// The file too (best effort), then no hash.
|
||||
if let Some(path) = self.own_uid.as_deref().and_then(files::avatar_path) {
|
||||
let cmd = VoiceCmd::DeleteFiles {
|
||||
let cmd = LinkCmd::DeleteFiles {
|
||||
request: None,
|
||||
channel: 0,
|
||||
password: None,
|
||||
@@ -947,7 +920,7 @@ impl Session {
|
||||
self.voice_cmd(cmd);
|
||||
}
|
||||
let hash = String::new();
|
||||
self.voice_cmd(VoiceCmd::SetAvatarHash { request: Some(request), hash });
|
||||
self.voice_cmd(LinkCmd::SetAvatarHash { request: Some(request), hash });
|
||||
return;
|
||||
};
|
||||
let (sources, cache, settings) =
|
||||
@@ -983,7 +956,7 @@ impl Session {
|
||||
let _ = sources.send(SourceEvent::AvatarUploaded(generation, request, result));
|
||||
});
|
||||
let file = Remote { channel: 0, password: None, path: "/avatar".into() };
|
||||
let upload = VoiceCmd::Upload {
|
||||
let upload = LinkCmd::Upload {
|
||||
transfer: None,
|
||||
file,
|
||||
from: image,
|
||||
@@ -1403,7 +1376,7 @@ impl Session {
|
||||
let sink = Sink::File { part: temp.clone(), dest: temp, append: false };
|
||||
let file = Remote { channel, password: None, path };
|
||||
let failed = report.clone();
|
||||
if voice.send(VoiceCmd::Download { transfer: None, file, sink, report }).is_err() {
|
||||
if voice.send(LinkCmd::Download { transfer: None, file, sink, report }).is_err() {
|
||||
failed(TransferState::Failed(NO_VOICE.into()));
|
||||
}
|
||||
}
|
||||
@@ -1436,24 +1409,22 @@ impl Session {
|
||||
if let Some(a) = &self.audio {
|
||||
for (client, (volume, muted)) in &wanted {
|
||||
if self.contact_audio.get(client) != Some(&(*volume, *muted)) {
|
||||
a.send(AudioIn::ClientVolume { client: ClientId(*client), volume: *volume });
|
||||
a.send(AudioIn::ClientMuted { client: ClientId(*client), muted: *muted });
|
||||
a.send(AudioIn::ClientVolume { client: TalkerId(*client), volume: *volume });
|
||||
a.send(AudioIn::ClientMuted { client: TalkerId(*client), muted: *muted });
|
||||
}
|
||||
}
|
||||
// No contact setting any more: back to normal.
|
||||
for client in self.contact_audio.keys().filter(|c| !wanted.contains_key(c)) {
|
||||
if p.clients.contains_key(client) {
|
||||
a.send(AudioIn::ClientVolume { client: ClientId(*client), volume: 1.0 });
|
||||
a.send(AudioIn::ClientMuted { client: ClientId(*client), muted: false });
|
||||
a.send(AudioIn::ClientVolume { client: TalkerId(*client), volume: 1.0 });
|
||||
a.send(AudioIn::ClientMuted { client: TalkerId(*client), muted: false });
|
||||
}
|
||||
}
|
||||
self.contact_audio = wanted;
|
||||
}
|
||||
if friends != self.stream_friends {
|
||||
self.stream_friends = friends.clone();
|
||||
if let Some(s) = &self.streams {
|
||||
s.send(StreamInput::Friends(friends));
|
||||
}
|
||||
self.stream_cmd(StreamCmd::Friends(friends));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1464,7 +1435,7 @@ impl Session {
|
||||
let clients = p.clients.values().filter(|c| c.priority_speaker).map(|c| c.id).collect();
|
||||
let wanted = (clients, p.server.priority_speaker_dimm_db);
|
||||
if wanted != self.priority_audio {
|
||||
let clients = wanted.0.iter().map(|c| ClientId(*c)).collect();
|
||||
let clients = wanted.0.iter().map(|c| TalkerId(*c)).collect();
|
||||
a.send(AudioIn::PrioritySpeakers { clients, dimm_db: wanted.1 as f32 });
|
||||
self.priority_audio = wanted;
|
||||
}
|
||||
@@ -1502,26 +1473,36 @@ impl Session {
|
||||
allows(self.settings.current().get(key), uid.map(|u| self.contacts.relation(u)))
|
||||
}
|
||||
|
||||
fn stream_input(&self, input: StreamInput) {
|
||||
match &self.streams {
|
||||
Some(s) => s.send(input),
|
||||
None if self.state.voice == VoiceState::Connected => {
|
||||
self.error("streams need a TeamSpeak 6 server");
|
||||
}
|
||||
None => self.error("not connected with voice"),
|
||||
/// A stream command of the user: an error where the connection has no
|
||||
/// streams.
|
||||
fn stream_input(&self, cmd: StreamCmd) {
|
||||
if self.streams {
|
||||
self.stream_cmd(cmd);
|
||||
} else if self.state.voice == VoiceState::Connected {
|
||||
self.error("streams need a TeamSpeak 6 server");
|
||||
} else {
|
||||
self.error("not connected with voice");
|
||||
}
|
||||
}
|
||||
|
||||
/// A command for the streams of the voice connection; dropped where it
|
||||
/// has none.
|
||||
fn stream_cmd(&self, cmd: StreamCmd) {
|
||||
if let (true, Some((_, tx))) = (self.streams, &self.voice) {
|
||||
let _ = tx.send(LinkCmd::Stream(cmd));
|
||||
}
|
||||
}
|
||||
|
||||
fn stop_streams(&mut self, reason: &str) {
|
||||
if let Some(s) = self.streams.take() {
|
||||
s.send(StreamInput::Shutdown(reason.into()));
|
||||
if self.streams {
|
||||
self.stream_cmd(StreamCmd::Shutdown(reason.into()));
|
||||
self.streams = false;
|
||||
}
|
||||
self.streaming_clients.clear();
|
||||
// The stream task's report comes from a replaced source.
|
||||
self.own_stream_ended();
|
||||
}
|
||||
|
||||
fn voice_cmd(&self, cmd: VoiceCmd) {
|
||||
fn voice_cmd(&self, cmd: LinkCmd) {
|
||||
match &self.voice {
|
||||
Some((_, tx)) => {
|
||||
let _ = tx.send(cmd);
|
||||
@@ -1710,14 +1691,16 @@ impl Session {
|
||||
|
||||
/// The registered streams of the directory, for the stream task.
|
||||
fn feed_directory(&self) {
|
||||
let Some(streams) = &self.streams else { return };
|
||||
if !self.streams {
|
||||
return;
|
||||
}
|
||||
let entries = self
|
||||
.directory
|
||||
.values()
|
||||
.filter_map(|e| {
|
||||
Some(StreamInfo {
|
||||
id: e.stream_id.clone()?,
|
||||
streamer: ClientId(e.client_id?),
|
||||
streamer: e.client_id?,
|
||||
name: e.title.clone(),
|
||||
kind: parse_kind(&e.kind),
|
||||
// Not in the directory; the stream's offer tells.
|
||||
@@ -1729,7 +1712,7 @@ impl Session {
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
streams.send(StreamInput::Directory(entries));
|
||||
self.stream_cmd(StreamCmd::Directory(entries));
|
||||
}
|
||||
|
||||
fn register_own_stream(&mut self) {
|
||||
@@ -1834,7 +1817,7 @@ impl Session {
|
||||
}
|
||||
self.stop_streams("session closed");
|
||||
if let Some((_, tx)) = self.voice.take() {
|
||||
let _ = tx.send(VoiceCmd::Disconnect);
|
||||
let _ = tx.send(LinkCmd::Disconnect);
|
||||
}
|
||||
self.audio = None;
|
||||
self.stop_observing();
|
||||
@@ -1858,7 +1841,7 @@ impl Session {
|
||||
SourceEvent::Query(g, e) if self.is_current(Source::Query, g) => self.query_event(e),
|
||||
SourceEvent::AudioOut(g, packet) if self.is_current(Source::Voice, g) => {
|
||||
if let Some((_, tx)) = &self.voice {
|
||||
let _ = tx.send(VoiceCmd::Audio(packet));
|
||||
let _ = tx.send(LinkCmd::Audio(packet));
|
||||
}
|
||||
}
|
||||
SourceEvent::Audio(g, event) if self.is_current(Source::Voice, g) => match event {
|
||||
@@ -1867,9 +1850,6 @@ impl Session {
|
||||
self.emit(Event::InputLevel { session: Some(self.id), level_db: db, sending })
|
||||
}
|
||||
},
|
||||
SourceEvent::OwnStream(g, e) if self.is_current(Source::Voice, g) => {
|
||||
self.own_stream_event(e)
|
||||
}
|
||||
SourceEvent::Directory(g, result) if self.is_current(Source::Gateway, g) => {
|
||||
match result {
|
||||
Ok(streams) => {
|
||||
@@ -1895,7 +1875,7 @@ impl Session {
|
||||
}
|
||||
SourceEvent::AvatarUploaded(g, request, result) => match result {
|
||||
Ok(hash) if self.is_current(Source::Voice, g) => {
|
||||
self.voice_cmd(VoiceCmd::SetAvatarHash { request: Some(request), hash });
|
||||
self.voice_cmd(LinkCmd::SetAvatarHash { request: Some(request), hash });
|
||||
}
|
||||
Ok(_) => self.emit(Event::RequestDone {
|
||||
session: self.id,
|
||||
@@ -1923,9 +1903,16 @@ impl Session {
|
||||
}
|
||||
}
|
||||
|
||||
fn voice_event(&mut self, e: VoiceEvent) {
|
||||
fn voice_event(&mut self, e: LinkEvent) {
|
||||
match e {
|
||||
VoiceEvent::Connected { name, flavor, own_client, server_uid, own_uid } => {
|
||||
LinkEvent::Connected {
|
||||
name,
|
||||
backend,
|
||||
capabilities,
|
||||
own_client,
|
||||
server_uid,
|
||||
own_uid,
|
||||
} => {
|
||||
self.state.voice = VoiceState::Connected;
|
||||
self.state.own_client = Some(own_client);
|
||||
if own_uid.is_some() {
|
||||
@@ -1940,50 +1927,26 @@ impl Session {
|
||||
{
|
||||
let _ = tx.send(GatewayCmd::RetryNow);
|
||||
}
|
||||
let capabilities = flavor.capabilities();
|
||||
if capabilities.streams
|
||||
&& let Some((generation, voice)) = &self.voice
|
||||
{
|
||||
let generation = *generation;
|
||||
let (own_tx, own_rx) = mpsc::unbounded_channel();
|
||||
self.forward(own_rx, move |e| SourceEvent::OwnStream(generation, e));
|
||||
let streams = StreamHandle::spawn(
|
||||
self.id,
|
||||
own_client,
|
||||
self.stream_peer.clone(),
|
||||
voice.clone(),
|
||||
self.events.clone(),
|
||||
self.frames.clone(),
|
||||
self.audio.clone(),
|
||||
self.settings.clone(),
|
||||
own_tx,
|
||||
);
|
||||
if capabilities.streams {
|
||||
self.streams = true;
|
||||
if !self.stream_layers.is_empty() {
|
||||
streams.send(StreamInput::Layers(self.stream_layers.clone()));
|
||||
self.stream_cmd(StreamCmd::Layers(self.stream_layers.clone()));
|
||||
}
|
||||
// The setting may have changed since the connection was asked for.
|
||||
if let Some(profiles) = self.srtp_profiles.clone() {
|
||||
self.stream_cmd(StreamCmd::SrtpProfiles(profiles));
|
||||
}
|
||||
self.streams = Some(streams);
|
||||
self.feed_directory();
|
||||
}
|
||||
self.emit(Event::ServerInfo { session: self.id, name, flavor, capabilities });
|
||||
self.emit(Event::ServerInfo { session: self.id, name, backend, capabilities });
|
||||
self.reopen_relayed_chats();
|
||||
self.open_histories();
|
||||
}
|
||||
VoiceEvent::Presence(p) => {
|
||||
LinkEvent::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, ClientState { channel: c.channel, streaming: c.streaming }))
|
||||
.collect();
|
||||
if clients != self.streaming_clients {
|
||||
self.streaming_clients = clients.clone();
|
||||
s.send(StreamInput::Clients(clients));
|
||||
a.send(AudioIn::ClientLeft(TalkerId(*id)));
|
||||
}
|
||||
}
|
||||
self.report_details(&p);
|
||||
@@ -1993,7 +1956,7 @@ impl Session {
|
||||
self.voice_presence = Some(*p);
|
||||
self.publish_presence();
|
||||
}
|
||||
VoiceEvent::Poke { from, from_uid, from_name, message } => {
|
||||
LinkEvent::Poke { from, from_uid, from_name, message } => {
|
||||
let blocked = self.contacts.is_blocked(from_uid.as_deref());
|
||||
if blocked && self.block_mode() == BlockMode::Hide {
|
||||
debug!(?from_uid, "poke of a blocked contact hidden");
|
||||
@@ -2006,35 +1969,37 @@ impl Session {
|
||||
let session = self.id;
|
||||
self.emit(Event::Poke { session, from, from_uid, from_name, message, blocked });
|
||||
}
|
||||
VoiceEvent::Error(message) => self.error(message),
|
||||
VoiceEvent::Stream(n) => {
|
||||
if let Some(s) = &self.streams {
|
||||
s.send(StreamInput::Notification(n));
|
||||
LinkEvent::Error(message) => self.error(message),
|
||||
LinkEvent::OwnStream(e) => self.own_stream_event(e),
|
||||
LinkEvent::StreamAudio { stream, time, data } => {
|
||||
if let Some(a) = &self.audio {
|
||||
a.send(AudioIn::StreamAudio { stream, time, data });
|
||||
}
|
||||
}
|
||||
VoiceEvent::StreamRequestFailed(request, error) => {
|
||||
if let Some(s) = &self.streams {
|
||||
s.send(StreamInput::RequestFailed(request, error));
|
||||
LinkEvent::StreamAudioEnded(stream) => {
|
||||
if let Some(a) = &self.audio {
|
||||
a.send(AudioIn::StreamEnded(stream));
|
||||
}
|
||||
}
|
||||
VoiceEvent::OwnChannel(cid) => {
|
||||
LinkEvent::OwnChannel(cid) => {
|
||||
if self.state.own_channel != Some(cid) {
|
||||
self.state.own_channel = Some(cid);
|
||||
self.emit_state();
|
||||
}
|
||||
}
|
||||
VoiceEvent::Chat(msg) => self.chat(msg, MessageSource::Voice, None),
|
||||
VoiceEvent::Audio(packet) => {
|
||||
LinkEvent::Chat(msg) => self.chat(msg, MessageSource::Voice, None),
|
||||
LinkEvent::Audio(packet) => {
|
||||
if let Some(a) = &self.audio {
|
||||
a.send(AudioIn::Packet(packet));
|
||||
}
|
||||
}
|
||||
VoiceEvent::Talking { client, talking } => {
|
||||
LinkEvent::Talking { client, talking } => {
|
||||
self.emit(Event::Talking { session: self.id, client, talking });
|
||||
}
|
||||
VoiceEvent::Disconnected(reason) => {
|
||||
self.stop_streams("voice disconnected");
|
||||
LinkEvent::Disconnected(reason) => {
|
||||
// The connection ended its streams itself.
|
||||
self.voice = None;
|
||||
self.stop_streams("voice disconnected");
|
||||
self.voice_presence = None;
|
||||
self.audio = None;
|
||||
self.forget_images();
|
||||
@@ -2288,18 +2253,13 @@ mod banner_tests {
|
||||
cache: SharedCache::new(Cache::new(dir)),
|
||||
contacts: Contacts::new(events.clone(), history),
|
||||
};
|
||||
// No myTeamSpeak account; its source stays open, as the engine's does
|
||||
// (a closed one ends voice connections).
|
||||
let myts_identity = Box::leak(Box::new(watch::Sender::new(None))).subscribe();
|
||||
let myts_data = Box::leak(Box::new(watch::Sender::new(None))).subscribe();
|
||||
let session = Session::new(
|
||||
1,
|
||||
events,
|
||||
frames,
|
||||
AudioSettings::default(),
|
||||
shared,
|
||||
myts_identity,
|
||||
myts_data,
|
||||
Arc::new(SessionLink::new(crate::Backends::empty())),
|
||||
);
|
||||
(session, receiver)
|
||||
}
|
||||
@@ -2386,7 +2346,7 @@ mod banner_tests {
|
||||
Err("temporarily unavailable".into()),
|
||||
);
|
||||
session.retry_images(session.image_retries[&request].due.unwrap());
|
||||
let VoiceCmd::Download { file, sink: Sink::File { part, .. }, report, .. } =
|
||||
let LinkCmd::Download { file, sink: Sink::File { part, .. }, report, .. } =
|
||||
commands.try_recv().unwrap()
|
||||
else {
|
||||
panic!("expected an image download");
|
||||
@@ -2433,7 +2393,7 @@ mod banner_tests {
|
||||
session.state.server_uid = Some("server-a".into());
|
||||
session.fetch_pictures(&presence);
|
||||
assert!(session.pictures.contains(url));
|
||||
let VoiceCmd::Download { file, sink: Sink::File { part, .. }, report, .. } =
|
||||
let LinkCmd::Download { file, sink: Sink::File { part, .. }, report, .. } =
|
||||
commands.try_recv().unwrap()
|
||||
else {
|
||||
panic!("expected a file download");
|
||||
@@ -2975,9 +2935,10 @@ mod banner_tests {
|
||||
let (mut session, _events) = session("gateway-wake");
|
||||
let (tx, mut rx) = mpsc::unbounded_channel();
|
||||
session.gateway = Some((session.next_generation(), tx));
|
||||
let connected = || VoiceEvent::Connected {
|
||||
let connected = || LinkEvent::Connected {
|
||||
name: "test".into(),
|
||||
flavor: voelin_model::ServerFlavor::Unknown(String::new()),
|
||||
backend: crate::BackendInfo::default(),
|
||||
capabilities: voelin_model::Capabilities::default(),
|
||||
own_client: 1,
|
||||
server_uid: "server=".into(),
|
||||
own_uid: None,
|
||||
|
||||
@@ -50,8 +50,8 @@ use serde_json::{Value, json};
|
||||
use tokio::sync::{broadcast, watch};
|
||||
use tracing::{debug, warn};
|
||||
use voelin_audio::AudioSettings;
|
||||
use voelin_media::{LayerId, LayerSpec};
|
||||
use voelin_store::Store;
|
||||
use voelin_stream::{LayerId, LayerSpec};
|
||||
|
||||
/// A value of any key, typed (`Arc<T>` of the key's `T`).
|
||||
type Stored = Arc<dyn Any + Send + Sync>;
|
||||
@@ -1135,7 +1135,7 @@ pub static CACHE_FETCH_IMAGES: Key<bool> = Key::new(
|
||||
);
|
||||
|
||||
/// Import identities from the official TeamSpeak clients when the app
|
||||
/// starts ([`crate::identity::import_new`]; their files are only read).
|
||||
/// starts ([`crate::ts::identity::import_new`]; their files are only read).
|
||||
pub static IDENTITY_IMPORT: Key<bool> = Key::new(
|
||||
"identity.import_from_teamspeak",
|
||||
Kind::Bool,
|
||||
|
||||
+539
-161
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,155 @@
|
||||
//! The stream types of the engine's API, owned by the core: what the UI is
|
||||
//! told about streams ([`StreamInfo`], [`ViewerInfo`], why a stream
|
||||
//! [ended](EndReason)) and what it asks for ([`StreamSetup`]).
|
||||
//!
|
||||
//! They carry plain fields only: client ids are `u16`, an SRTP profile is its
|
||||
//! name, a video codec is `voelin_media`'s. What a server link speaks (the
|
||||
//! TeamSpeak 6 stream crate today) is converted to and from them at the
|
||||
//! boundary in [`crate::stream`], so the UI does not depend on the link's
|
||||
//! types. The frame and simulcast layer types (`EncodedFrame`, `LayerSpec`,
|
||||
//! `LayerId`) are `voelin-media`'s.
|
||||
|
||||
use voelin_media::{Codec, LayerId};
|
||||
|
||||
/// What a stream shows.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum StreamKind {
|
||||
Camera,
|
||||
Screen,
|
||||
Window,
|
||||
/// A kind this client does not know, by its number on the server.
|
||||
Other(u8),
|
||||
}
|
||||
|
||||
impl StreamKind {
|
||||
/// From the number servers use: 2 camera, 3 screen, 4 window.
|
||||
pub fn from_u8(v: u8) -> Self {
|
||||
match v {
|
||||
2 => Self::Camera,
|
||||
3 => Self::Screen,
|
||||
4 => Self::Window,
|
||||
v => Self::Other(v),
|
||||
}
|
||||
}
|
||||
|
||||
/// [`from_u8`](Self::from_u8) back.
|
||||
pub fn to_u8(self) -> u8 {
|
||||
match self {
|
||||
Self::Camera => 2,
|
||||
Self::Screen => 3,
|
||||
Self::Window => 4,
|
||||
Self::Other(v) => v,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What we announce when we start a stream ([`crate::Command::StartStream`]).
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct StreamSetup {
|
||||
pub name: String,
|
||||
pub kind: StreamKind,
|
||||
/// The stream's video bitrate in kbit/s (the single layer's without
|
||||
/// simulcast). TeamSpeak 6 servers keep it in 16 bits, so it is
|
||||
/// announced as at most 65535; the stream sends its real rate whatever
|
||||
/// the announcement says.
|
||||
pub bitrate: u32,
|
||||
/// `accessibility`: the official client sends 1.
|
||||
pub accessibility: u8,
|
||||
/// `mode`: 1 (none) is what clients send today; 2 is P2P, 3 SFU.
|
||||
pub mode: u8,
|
||||
/// 0 = unlimited.
|
||||
pub viewer_limit: u32,
|
||||
pub audio: bool,
|
||||
}
|
||||
|
||||
impl Default for StreamSetup {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
name: String::new(),
|
||||
kind: StreamKind::Screen,
|
||||
bitrate: 4608,
|
||||
accessibility: 1,
|
||||
mode: 1,
|
||||
viewer_limit: 0,
|
||||
audio: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A stream on the server ([`crate::Event::StreamsChanged`]).
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct StreamInfo {
|
||||
pub id: String,
|
||||
/// The client id of the streamer.
|
||||
pub streamer: u16,
|
||||
pub name: String,
|
||||
pub kind: StreamKind,
|
||||
pub bitrate: u32,
|
||||
pub viewer_limit: u32,
|
||||
pub audio: bool,
|
||||
/// How many watch it; `None` where nothing told (e.g. a gateway's
|
||||
/// directory entry).
|
||||
pub viewers: Option<u32>,
|
||||
}
|
||||
|
||||
/// A viewer of our stream, as we see it.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum ViewerState {
|
||||
/// Asked to watch, waiting for our decision.
|
||||
Requested,
|
||||
/// Offer sent; waiting for the answer and the connection.
|
||||
Connecting,
|
||||
Connected,
|
||||
}
|
||||
|
||||
/// A viewer of our stream ([`crate::Event::StreamViewers`]).
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct ViewerInfo {
|
||||
/// The client id of the viewer.
|
||||
pub client: u16,
|
||||
pub state: ViewerState,
|
||||
/// The message of the join request.
|
||||
pub message: String,
|
||||
/// The simulcast layer the viewer receives (it moves at a keyframe of the
|
||||
/// new layer); `None` before we offered, and with RID simulcast (all
|
||||
/// layers).
|
||||
pub layer: Option<LayerId>,
|
||||
/// The latest bandwidth estimate of the connection (bit/s).
|
||||
pub estimate: Option<u64>,
|
||||
/// The SRTP profile of the connection by its name (as in RFC 5764 and
|
||||
/// WebRTC statistics, e.g. `AEAD_AES_128_GCM`), once the key exchange is
|
||||
/// done.
|
||||
pub srtp_profile: Option<String>,
|
||||
/// The video codec the viewer's answer chose (it gets video in that
|
||||
/// codec).
|
||||
pub codec: Option<Codec>,
|
||||
}
|
||||
|
||||
/// Why a viewer left a stream.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum LeaveReason {
|
||||
None,
|
||||
Left,
|
||||
Denied,
|
||||
Failed,
|
||||
Kicked,
|
||||
Banned,
|
||||
/// A reason this client does not know, by its number on the server.
|
||||
Other(u8),
|
||||
}
|
||||
|
||||
/// Why a stream ended for us ([`crate::StreamState::Ended`],
|
||||
/// [`crate::WatchState::Ended`]).
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum EndReason {
|
||||
/// We stopped streaming or watching.
|
||||
Local,
|
||||
/// The streamer denied our join request.
|
||||
Denied,
|
||||
/// The stream was stopped (or its streamer disconnected).
|
||||
Stopped,
|
||||
/// The streamer or the server ended our viewing session.
|
||||
Removed(Option<LeaveReason>),
|
||||
/// A command failed or no connection could be established.
|
||||
Failed(String),
|
||||
}
|
||||
@@ -331,4 +331,301 @@ mod tests {
|
||||
let p = presence_from_book(&book, None, |_| false);
|
||||
assert_eq!(avatar(&p, 6).as_deref(), Some("https://a.example/off.png"));
|
||||
}
|
||||
|
||||
// ---- across the session seam ---------------------------------------------
|
||||
|
||||
/// A presence made into the entities the TeamSpeak session writes
|
||||
/// (`ts_session::entities`), pushed the way a host syncs them, and
|
||||
/// projected back by the engine (`link::project`): what the UI is shown
|
||||
/// of what a TeamSpeak link reported (`docs/session-seam.md` section 5.1).
|
||||
fn through_the_seam(presence: &Presence, ts6: bool, own: Option<u16>) -> Presence {
|
||||
use voelin_model::replica::{Replica, SCHEMA_GENERATION, ScopeId};
|
||||
use voelin_proto::link::Features;
|
||||
use voelin_proto::v1::{self, push::Body};
|
||||
|
||||
use crate::link::media::TalkTracker;
|
||||
use crate::link::project::{View, presence as project};
|
||||
use crate::ts::ts_session::entities::build;
|
||||
|
||||
let built = build(presence, ts6, own);
|
||||
let mut replica = Replica::new(SCHEMA_GENERATION);
|
||||
for (scope, layer) in [(ScopeId::Server(1), &built.server), (ScopeId::Live(1), &built.live)]
|
||||
{
|
||||
replica.subscribe(scope);
|
||||
let pushes = [
|
||||
Body::SyncBegin(v1::SyncBegin {
|
||||
scope: Some(scope.to_proto()),
|
||||
mode: v1::SyncMode::Full as i32,
|
||||
epoch: 1,
|
||||
}),
|
||||
Body::Change(v1::Change {
|
||||
scope: Some(scope.to_proto()),
|
||||
rev: 1,
|
||||
put: layer.values().cloned().collect(),
|
||||
del: Vec::new(),
|
||||
}),
|
||||
Body::SyncEnd(v1::SyncEnd {
|
||||
scope: Some(scope.to_proto()),
|
||||
cursor: Some(v1::Cursor { epoch: 1, rev: 1 }),
|
||||
gap: false,
|
||||
}),
|
||||
];
|
||||
for body in pushes {
|
||||
replica.apply_push(&v1::Push { body: Some(body) });
|
||||
}
|
||||
}
|
||||
let features = Features::new(["voice"]);
|
||||
let talking = TalkTracker::default();
|
||||
project(&View {
|
||||
replica: &replica,
|
||||
server: 1,
|
||||
teamspeak: true,
|
||||
version: "",
|
||||
features: &features,
|
||||
streams: ts6,
|
||||
talking: &talking,
|
||||
})
|
||||
}
|
||||
|
||||
/// A TeamSpeak 6 server and some clients with what the book holds of them.
|
||||
fn ts6_presence() -> Presence {
|
||||
let mut book = ts6_book();
|
||||
let list = format!(
|
||||
"channellist {}|{}|{}",
|
||||
channel(1, 0, "Lobby", "channel_banner_gfx_url channel_banner_mode=0"),
|
||||
channel(
|
||||
12,
|
||||
1,
|
||||
"Raid",
|
||||
r"channel_banner_gfx_url=http:\/\/127.0.0.1:1\/d.png channel_banner_mode=2"
|
||||
),
|
||||
channel(20, 12, "Last", "channel_banner_gfx_url channel_banner_mode=0"),
|
||||
);
|
||||
book.handle_command(&message(&list)).unwrap();
|
||||
let enter = |clid: u16, channel: u64, groups: &str, away: &str, avatar: &str| {
|
||||
format!(
|
||||
"notifycliententerview reasonid=0 ctid={channel} clid={clid} \
|
||||
client_database_id={} client_nickname=c{clid} client_type=0 cfid=0 \
|
||||
client_unique_identifier=u{clid}= client_flag_avatar=abcdef \
|
||||
client_description=about\\sme client_icon_id=777 client_input_muted=1 \
|
||||
client_output_muted=0 client_outputonly_muted=0 client_input_hardware=1 \
|
||||
client_output_hardware=1 client_meta_data client_is_recording=1 \
|
||||
client_channel_group_id=8 client_channel_group_inherited_channel_id=1 \
|
||||
client_servergroups={groups} client_away={} client_away_message={away} \
|
||||
client_talk_power=75 client_talk_request=0 client_talk_request_msg \
|
||||
client_is_talker=1 client_is_priority_speaker=1 client_unread_messages=0 \
|
||||
client_nickname_phonetic client_needed_serverquery_view_power=75 \
|
||||
client_is_channel_commander=1 client_country=RU client_badges \
|
||||
client_myteamspeak_id=m{clid} client_integrations{avatar}",
|
||||
100 + u64::from(clid),
|
||||
u8::from(!away.is_empty()),
|
||||
)
|
||||
};
|
||||
for text in [
|
||||
enter(5, 1, "8", "", r" client_myteamspeak_avatar=2,https:\/\/a.example\/on.png"),
|
||||
enter(6, 12, "8,9", "gone\\sfishing", ""),
|
||||
enter(7, 12, "", "", " client_myteamspeak_avatar"),
|
||||
] {
|
||||
book.handle_command(&message(&text)).unwrap();
|
||||
}
|
||||
presence_from_book(&book, Some("ibhejBRSRRI7v+fSsUzpQ33JGK6rf5xKOLelpWUr0sE="), |_| false)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_book_is_what_the_ui_is_shown_across_the_seam() {
|
||||
let p = ts6_presence();
|
||||
assert_eq!(p.clients.len(), 3, "the fixture has clients");
|
||||
assert!(p.clients.values().any(|c| c.away.is_some()), "one is away");
|
||||
// A TeamSpeak 6 client the book has no streaming flag of (it was not
|
||||
// sent) is not streaming: v1 has no "unknown" for it.
|
||||
let mut expected = p.clone();
|
||||
for client in expected.clients.values_mut() {
|
||||
client.streaming = Some(client.streaming.unwrap_or(false));
|
||||
}
|
||||
assert_eq!(through_the_seam(&p, true, Some(5)), expected);
|
||||
// The same server as a TeamSpeak 3 one has no streams to tell of.
|
||||
let mut ts3 = p.clone();
|
||||
for client in ts3.clients.values_mut() {
|
||||
client.streaming = None;
|
||||
}
|
||||
assert_eq!(through_the_seam(&ts3, false, Some(5)), ts3);
|
||||
}
|
||||
|
||||
/// A deterministic stream of numbers for the generated presences.
|
||||
struct Numbers(u64);
|
||||
|
||||
impl Numbers {
|
||||
fn next(&mut self) -> u64 {
|
||||
self.0 ^= self.0 << 13;
|
||||
self.0 ^= self.0 >> 7;
|
||||
self.0 ^= self.0 << 17;
|
||||
self.0
|
||||
}
|
||||
|
||||
fn below(&mut self, n: u64) -> u64 {
|
||||
self.next() % n
|
||||
}
|
||||
|
||||
fn flag(&mut self) -> bool {
|
||||
self.below(2) == 0
|
||||
}
|
||||
|
||||
fn text(&mut self, prefix: &str) -> String {
|
||||
format!("{prefix}{}", self.below(1000))
|
||||
}
|
||||
}
|
||||
|
||||
/// A presence of the shape a TeamSpeak link reports: sibling channels in an
|
||||
/// order chain, every client with a database id, unique ids that are base64
|
||||
/// (TeamSpeak 3 and 6) or login names, groups of both kinds.
|
||||
fn generated(seed: u64, ts6: bool) -> Presence {
|
||||
use base64::Engine as _;
|
||||
use voelin_model::{
|
||||
BannerMode, ChannelInfo, ClientInfo, GroupInfo, GroupNamingMode, GroupType,
|
||||
HostMessageMode,
|
||||
};
|
||||
let mut n = Numbers(seed | 1);
|
||||
let mut p = Presence::default();
|
||||
let name = n.text("Server ");
|
||||
p.server_name = name.clone();
|
||||
p.server = voelin_model::ServerDetails {
|
||||
name,
|
||||
uid: Some(n.text("uid")),
|
||||
welcome_message: n.text("welcome "),
|
||||
host_message: n.text("host "),
|
||||
host_message_mode: [
|
||||
HostMessageMode::None,
|
||||
HostMessageMode::Log,
|
||||
HostMessageMode::Modal,
|
||||
][n.below(3) as usize],
|
||||
banner_url: if n.flag() { n.text("https://b/") } else { String::new() },
|
||||
banner_gfx_url: if n.flag() { n.text("https://g/") } else { String::new() },
|
||||
banner_gfx_interval_s: n.below(100),
|
||||
banner_mode: [BannerMode::NoAdjust, BannerMode::IgnoreAspect, BannerMode::KeepAspect]
|
||||
[n.below(3) as usize],
|
||||
host_button_tooltip: if n.flag() { n.text("tip ") } else { String::new() },
|
||||
host_button_url: String::new(),
|
||||
host_button_gfx_url: String::new(),
|
||||
icon: n.below(5) as u32 * 1000,
|
||||
platform: "Linux".into(),
|
||||
version: n.text("6.0."),
|
||||
max_clients: n.below(500) as u16,
|
||||
priority_speaker_dimm_db: -(n.below(30) as i32),
|
||||
default_server_group: Some(1 + n.below(9)),
|
||||
default_channel_group: Some(1 + n.below(9)),
|
||||
};
|
||||
// Groups.
|
||||
for id in 1..=(2 + n.below(4)) {
|
||||
let group = |id: u64, n: &mut Numbers| GroupInfo {
|
||||
id,
|
||||
name: n.text("group "),
|
||||
icon: n.below(3) as u32 * 100,
|
||||
sort_id: n.below(1000) as i32 - 500,
|
||||
naming_mode: [
|
||||
GroupNamingMode::None,
|
||||
GroupNamingMode::Before,
|
||||
GroupNamingMode::After,
|
||||
][n.below(3) as usize],
|
||||
group_type: [GroupType::Regular, GroupType::Template, GroupType::Query]
|
||||
[n.below(3) as usize],
|
||||
};
|
||||
p.server_groups.insert(id, group(id, &mut n));
|
||||
p.channel_groups.insert(id, group(id, &mut n));
|
||||
}
|
||||
// Channels: a tree whose siblings follow each other.
|
||||
let mut parents = vec![0u64];
|
||||
for id in 1..=(3 + n.below(8)) {
|
||||
let parent = parents[n.below(parents.len() as u64) as usize];
|
||||
let order = p
|
||||
.channels
|
||||
.values()
|
||||
.filter(|c| c.parent == parent)
|
||||
.map(|c| c.id)
|
||||
.next_back()
|
||||
.unwrap_or(0);
|
||||
parents.push(id);
|
||||
p.channels.insert(
|
||||
id,
|
||||
ChannelInfo {
|
||||
id,
|
||||
parent,
|
||||
order,
|
||||
name: n.text("channel "),
|
||||
topic: n.flag().then(|| n.text("topic ")),
|
||||
has_password: n.flag(),
|
||||
max_clients: match n.below(3) {
|
||||
0 => None,
|
||||
1 => Some(0),
|
||||
_ => Some(1 + n.below(50) as i32),
|
||||
},
|
||||
needed_subscribe_power: n.below(3) as i32 * 10,
|
||||
needed_talk_power: n.below(3) as i32 * 25,
|
||||
is_default: id == 1,
|
||||
icon: n.below(3) as u32 * 500,
|
||||
banner_gfx_url: n.flag().then(|| n.text("https://c/")),
|
||||
banner_mode: [
|
||||
BannerMode::NoAdjust,
|
||||
BannerMode::IgnoreAspect,
|
||||
BannerMode::KeepAspect,
|
||||
][n.below(3) as usize],
|
||||
},
|
||||
);
|
||||
}
|
||||
// Clients.
|
||||
let channels: Vec<u64> = p.channels.keys().copied().collect();
|
||||
for id in 1..=(1 + n.below(12)) {
|
||||
let id = id as u16;
|
||||
let uid = match n.below(4) {
|
||||
0 => None,
|
||||
1 => Some(n.text("login")),
|
||||
_ => {
|
||||
let bytes: Vec<u8> =
|
||||
(0..if ts6 { 32 } else { 20 }).map(|_| n.below(256) as u8).collect();
|
||||
Some(base64::engine::general_purpose::STANDARD.encode(bytes))
|
||||
}
|
||||
};
|
||||
let channel = channels[n.below(channels.len() as u64) as usize];
|
||||
p.clients.insert(
|
||||
id,
|
||||
ClientInfo {
|
||||
id,
|
||||
uid,
|
||||
nickname: n.text("nick "),
|
||||
channel,
|
||||
is_query: n.below(5) == 0,
|
||||
away: n.flag().then(|| if n.flag() { n.text("away ") } else { String::new() }),
|
||||
input_muted: n.flag(),
|
||||
output_muted: n.flag(),
|
||||
talking: Some(false),
|
||||
streaming: ts6.then(|| n.flag()),
|
||||
server_groups: (0..n.below(3)).map(|_| 1 + n.below(9)).collect(),
|
||||
country: n.flag().then(|| "DE".into()),
|
||||
avatar: n.flag().then(|| n.text("hash")),
|
||||
myts_avatar: n.flag().then(|| n.text("https://a/")),
|
||||
description: n.flag().then(|| n.text("about ")),
|
||||
talk_power: n.below(100) as i32,
|
||||
talker: n.flag(),
|
||||
channel_group: n.flag().then(|| 1 + n.below(9)),
|
||||
badges: (0..n.below(3)).map(|_| n.text("badge")).collect(),
|
||||
icon: n.below(3) as u32 * 111,
|
||||
recording: n.flag(),
|
||||
priority_speaker: n.flag(),
|
||||
channel_commander: n.flag(),
|
||||
database_id: Some(1_000 + u64::from(id)),
|
||||
},
|
||||
);
|
||||
}
|
||||
p
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generated_presences_survive_the_seam() {
|
||||
for seed in 1..=200u64 {
|
||||
for ts6 in [false, true] {
|
||||
let p = generated(seed.wrapping_mul(0x9e37_79b9_7f4a_7c15), ts6);
|
||||
let own = p.clients.keys().next().copied();
|
||||
assert_eq!(through_the_seam(&p, ts6, own), p, "seed {seed}, ts6 {ts6}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -32,6 +32,7 @@ use std::{fs, str};
|
||||
use rusqlite::{Connection, OpenFlags, OptionalExtension};
|
||||
use tsclientlib::Identity;
|
||||
use voelin_gateway_proto::UniqueIds;
|
||||
use voelin_identity::IdentityBlob;
|
||||
use voelin_store::{IdentityOrigin, Store};
|
||||
|
||||
/// Name given to an identity whose source kept none.
|
||||
@@ -55,6 +56,9 @@ pub enum IdentityError {
|
||||
NoIdentity { path: String },
|
||||
#[error("client database: {0}")]
|
||||
Store(String),
|
||||
/// An [`IdentityBlob`] that is no TeamSpeak identity ([`from_blob`]).
|
||||
#[error("{0}")]
|
||||
Blob(String),
|
||||
}
|
||||
|
||||
impl IdentityError {
|
||||
@@ -230,6 +234,77 @@ pub fn import_new(store: &Store, paths: &[PathBuf]) -> Result<LaunchImport, Iden
|
||||
Ok(report)
|
||||
}
|
||||
|
||||
/// A TeamSpeak identity as the API takes it
|
||||
/// ([`VoiceOptions::identity`](crate::VoiceOptions::identity),
|
||||
/// [`Command::ObserveGateway`](crate::Command::ObserveGateway)) and the key
|
||||
/// store keeps it: kind `teamspeak`, the unique id TeamSpeak 3 servers know it
|
||||
/// by (also how [`voelin_store`] keys it), its security level, and the JSON
|
||||
/// the store writes.
|
||||
pub fn to_blob(identity: &Identity) -> IdentityBlob {
|
||||
// An identity is a key and two counters: writing it cannot fail. (A blob with
|
||||
// no JSON is refused when it is used, in words.)
|
||||
let json = serde_json::to_string(identity).unwrap_or_default();
|
||||
IdentityBlob::teamspeak(identity.key().to_pub().get_uid(), identity.level(), json)
|
||||
}
|
||||
|
||||
/// The TeamSpeak identity of a blob (the reverse of [`to_blob`]).
|
||||
pub fn from_blob(blob: &IdentityBlob) -> Result<Identity, IdentityError> {
|
||||
if !blob.is_teamspeak() {
|
||||
return Err(IdentityError::Blob(format!(
|
||||
"the identity is of kind {:?}, not a TeamSpeak one",
|
||||
blob.kind
|
||||
)));
|
||||
}
|
||||
from_json(&blob.json)
|
||||
}
|
||||
|
||||
/// The TeamSpeak identity in `json`, the text [`to_blob`] writes and the key
|
||||
/// store keeps; voelin-core reads that text only through here (voelin-store
|
||||
/// parses it too, for its own checks of a stored row).
|
||||
///
|
||||
/// What does not read is refused in words that say how it is wrong
|
||||
/// (malformed, cut short, not an identity, unreadable) and where (line and
|
||||
/// column), and never what it holds: the text holds a private key, and the
|
||||
/// message of the JSON reader quotes a value it refuses (`tsproto` reports a
|
||||
/// key that does not import as an invalid value, the key string and all), so
|
||||
/// that message is never shown, not in an error, an event or a log.
|
||||
pub(crate) fn from_json(json: &str) -> Result<Identity, IdentityError> {
|
||||
serde_json::from_str(json).map_err(|e| {
|
||||
let what = match e.classify() {
|
||||
serde_json::error::Category::Syntax => "malformed",
|
||||
serde_json::error::Category::Eof => "cut short",
|
||||
serde_json::error::Category::Data => "not an identity",
|
||||
serde_json::error::Category::Io => "unreadable",
|
||||
};
|
||||
IdentityError::Blob(format!(
|
||||
"the TeamSpeak identity cannot be read: {what} at line {}, column {}",
|
||||
e.line(),
|
||||
e.column()
|
||||
))
|
||||
})
|
||||
}
|
||||
|
||||
/// The JSON of a fresh identity whose key lost its last two characters (a key
|
||||
/// that does not import), and that cut key.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn json_with_a_cut_key() -> (String, String) {
|
||||
let mut json = serde_json::to_value(Identity::create()).unwrap();
|
||||
let key = json["key"].as_str().unwrap().to_owned();
|
||||
let cut = key[..key.len() - 2].to_owned();
|
||||
json["key"] = cut.clone().into();
|
||||
(json.to_string(), cut)
|
||||
}
|
||||
|
||||
/// Fail if `text` holds any 8 characters in a row of `secret`.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn assert_holds_no_piece_of(text: &str, secret: &str) {
|
||||
assert!(secret.len() >= 8 && secret.is_ascii());
|
||||
for piece in secret.as_bytes().windows(8) {
|
||||
let piece = std::str::from_utf8(piece).unwrap();
|
||||
assert!(!text.contains(piece), "{text:?} holds {piece:?} of the key");
|
||||
}
|
||||
}
|
||||
|
||||
/// The TeamSpeak 3 `.ini` export of an identity, which the official client
|
||||
/// and every other tool reads.
|
||||
pub fn export(nickname: &str, identity: &Identity) -> String {
|
||||
@@ -548,18 +623,69 @@ mod tests {
|
||||
Identity::create()
|
||||
}
|
||||
|
||||
/// The blob of an identity is how the key store keeps it, and reads back as
|
||||
/// the same identity; what is no TeamSpeak identity is refused without
|
||||
/// quoting its JSON.
|
||||
#[test]
|
||||
fn an_identity_goes_through_its_blob() {
|
||||
let identity = synthetic();
|
||||
let blob = to_blob(&identity);
|
||||
assert!(blob.is_teamspeak());
|
||||
assert_eq!(blob.uid, identity.key().to_pub().get_uid());
|
||||
assert_eq!(blob.level, identity.level());
|
||||
assert_eq!(blob.json, serde_json::to_string(&identity).unwrap());
|
||||
let back = from_blob(&blob).unwrap();
|
||||
assert_eq!(serde_json::to_value(&back).unwrap(), serde_json::to_value(&identity).unwrap());
|
||||
|
||||
// Another kind.
|
||||
let other = IdentityBlob::new("voelin", "x", 0, blob.json.clone());
|
||||
let error = from_blob(&other).unwrap_err().to_string();
|
||||
assert!(error.contains("\"voelin\""), "{error}");
|
||||
// Not an identity: the text says where, and nothing of what it holds.
|
||||
for json in ["", "{", r#"{"key":"hunter2-key","counter":"hunter2"}"#, "[1]"] {
|
||||
let error = from_blob(&IdentityBlob::teamspeak("x", 0, json)).unwrap_err().to_string();
|
||||
assert!(error.starts_with("the TeamSpeak identity cannot be read"), "{error}");
|
||||
assert!(!error.contains("hunter2"), "{error}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The JSON reader's own message quotes a key that does not import, so the
|
||||
/// refusal is worded by `from_json` and holds none of the key.
|
||||
#[test]
|
||||
fn a_key_that_does_not_import_is_refused_without_quoting_it() {
|
||||
let (json, cut) = json_with_a_cut_key();
|
||||
let raw = serde_json::from_str::<Identity>(&json).unwrap_err().to_string();
|
||||
assert!(raw.contains(&cut), "the reader's own message quotes the key: {raw}");
|
||||
for error in [
|
||||
from_json(&json).unwrap_err().to_string(),
|
||||
from_blob(&IdentityBlob::teamspeak("x", 8, json.clone())).unwrap_err().to_string(),
|
||||
] {
|
||||
assert!(
|
||||
error.starts_with(
|
||||
"the TeamSpeak identity cannot be read: not an identity at line 1, column "
|
||||
),
|
||||
"{error}"
|
||||
);
|
||||
assert_holds_no_piece_of(&error, &cut);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn improve_level_keeps_the_key() {
|
||||
let identity = synthetic();
|
||||
// A fresh identity stops at the first counter whose level is 8 or more,
|
||||
// and about one in 32 has 13 or more already, which `improve_level`
|
||||
// returns as it is: ask for more than this one has, whatever it has.
|
||||
let target = identity.level() + 3;
|
||||
let levels = std::sync::Mutex::new(Vec::new());
|
||||
let better = improve_level(&identity, 13, &AtomicBool::new(false), |l| {
|
||||
let better = improve_level(&identity, target, &AtomicBool::new(false), |l| {
|
||||
levels.lock().unwrap().push(l);
|
||||
})
|
||||
.unwrap();
|
||||
assert!(better.level() >= 13);
|
||||
assert!(better.level() >= target);
|
||||
assert_eq!(better.key().to_pub().get_uid(), identity.key().to_pub().get_uid());
|
||||
assert!(better.counter() > identity.counter());
|
||||
assert!(levels.into_inner().unwrap().iter().any(|l| *l >= 13));
|
||||
assert!(levels.into_inner().unwrap().iter().any(|l| *l >= target));
|
||||
// Cancelled: nothing.
|
||||
assert!(improve_level(&identity, 60, &AtomicBool::new(true), |_| {}).is_none());
|
||||
// Already there: the same identity.
|
||||
@@ -0,0 +1,30 @@
|
||||
//! The TeamSpeak implementation of the session seam.
|
||||
//!
|
||||
//! Everything of the engine that is TeamSpeak's lives here, so that it can
|
||||
//! leave this crate for the TeamSpeak gateway (`voelin-gateway-ts` of
|
||||
//! VoelinGateWay) as one piece (`docs/session-seam.md`, H9):
|
||||
//!
|
||||
//! - `ts_link.rs` and `voice.rs` are the connection of `tsclientlib`
|
||||
//! (chat, voice, files, pokes, offline messages, the stream task's
|
||||
//! requests) with `book.rs`, its presence from the library's book;
|
||||
//! - `ts_session/` makes a `voelin_proto::link::Session` of such a connection
|
||||
//! ([`TsConnector`] is the `Connector` the engine registers for
|
||||
//! `ts3server://` and `teamspeak://`);
|
||||
//! - [`versions`] and [`identity`] are what a TeamSpeak client has to know
|
||||
//! about itself: the signed compatibility versions it can claim, and the
|
||||
//! identities (reading, importing from the official clients, the security
|
||||
//! level).
|
||||
//!
|
||||
//! The TeamSpeak crates' types (`tsclientlib::Identity`, `Version`, ...) are
|
||||
//! named in the public items of this module and nowhere else of the crate's
|
||||
//! API.
|
||||
|
||||
mod book;
|
||||
pub mod identity;
|
||||
mod ts_link;
|
||||
pub(crate) mod ts_session;
|
||||
pub mod versions;
|
||||
mod voice;
|
||||
|
||||
pub(crate) use ts_link::{ConnectOptions, ServerLink, TsLink};
|
||||
pub use ts_session::TsConnector;
|
||||
@@ -0,0 +1,256 @@
|
||||
//! The inner link of the TeamSpeak side: [`ServerLink`], the trait that
|
||||
//! [`TsLink`] implements, and the [`ConnectOptions`] it connects with.
|
||||
//!
|
||||
//! The engine does not know this vocabulary: it talks to a
|
||||
//! `voelin_proto::link::Session`. The `ts_session` module makes a `Session`
|
||||
//! of a [`ServerLink`] (`LinkSession`), and the engine's tests give it a link
|
||||
//! of their own, an in-memory one. [`TsLink`] connects as a normal TeamSpeak 3
|
||||
//! or 6 client with `tsclientlib` and
|
||||
//! runs the connection ([`super::voice`]) with everything that rides on it:
|
||||
//! chat, voice, files, pokes, offline messages and, on TeamSpeak 6, the
|
||||
//! stream task. Which product the server is (and what it can do) is decided
|
||||
//! there, from the version it sends, and reported in
|
||||
//! [`LinkEvent::Connected`](crate::link::LinkEvent::Connected).
|
||||
//!
|
||||
//! Everything it uses (`voice.rs`, `book.rs`, `stream.rs`, `versions.rs`,
|
||||
//! `identity.rs`) is TeamSpeak's and leaves this crate together with it:
|
||||
//! the plan moves `TsLink` into the TeamSpeak gateway, `voelin-gateway-ts`
|
||||
//! of VoelinGateWay.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use tokio::sync::{mpsc, watch};
|
||||
use voelin_stream::PeerConfig;
|
||||
|
||||
use super::voice;
|
||||
use crate::link::{LinkCmd, LinkCtx, LinkEvent};
|
||||
|
||||
/// Starts the connection of a link: the contract of `crate::link` for the
|
||||
/// vocabulary ([`LinkCmd`] in, [`LinkEvent`] out) holds for what a link does
|
||||
/// with them, and the module documentation of `link/session_link.rs` states
|
||||
/// it.
|
||||
///
|
||||
/// One link serves every session of an engine; [`spawn`](Self::spawn) starts
|
||||
/// one connection.
|
||||
pub(crate) trait ServerLink: Send + Sync + 'static {
|
||||
/// Connect to the server `options` names and run the connection on its
|
||||
/// own task: take commands from `cmds`, report through `events`, and end
|
||||
/// the connection with [`LinkEvent::Disconnected`]. Does not block.
|
||||
fn spawn(
|
||||
&self,
|
||||
options: ConnectOptions,
|
||||
ctx: LinkCtx,
|
||||
cmds: mpsc::UnboundedReceiver<LinkCmd>,
|
||||
events: mpsc::UnboundedSender<LinkEvent>,
|
||||
);
|
||||
}
|
||||
|
||||
/// What a TeamSpeak connection needs to know: the server, who to be, where
|
||||
/// to join. The reverse of what the engine's `ConnectParams` carry
|
||||
/// (`ts_session::inner_options`).
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) struct ConnectOptions {
|
||||
pub address: String,
|
||||
pub nickname: String,
|
||||
/// The identity to connect with; none generates one.
|
||||
pub identity: Option<tsclientlib::Identity>,
|
||||
/// Signed compatibility version; `None` selects the native platform's tuple.
|
||||
pub client_version: Option<tsclientlib::Version>,
|
||||
pub server_password: Option<String>,
|
||||
/// Channel path to join, e.g. `Lobby/Sub`, or `/<id>`.
|
||||
pub channel: Option<String>,
|
||||
/// The password of `channel`.
|
||||
pub channel_password: Option<String>,
|
||||
/// A privilege key to use when connecting.
|
||||
pub token: Option<String>,
|
||||
/// Open the audio devices (capture and playback).
|
||||
pub audio: bool,
|
||||
/// Network settings for stream peer connections.
|
||||
pub stream_peer: PeerConfig,
|
||||
}
|
||||
|
||||
impl ConnectOptions {
|
||||
/// Options for `address` and `nickname`, the rest as a test leaves it.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn new(address: impl Into<String>, nickname: impl Into<String>) -> Self {
|
||||
Self {
|
||||
address: address.into(),
|
||||
nickname: nickname.into(),
|
||||
identity: None,
|
||||
client_version: None,
|
||||
server_password: None,
|
||||
channel: None,
|
||||
channel_password: None,
|
||||
token: None,
|
||||
audio: false,
|
||||
stream_peer: PeerConfig::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The main myTeamSpeak account of an application, as its connections show
|
||||
/// it to the servers: the proof of the myTS ID, and what servers are shown
|
||||
/// of it (its avatar and badges with their certificates, its User Tag).
|
||||
///
|
||||
/// The senders live here, one pair for every connection of a [`TsLink`]; each
|
||||
/// connection watches the pair through [`Watches`], presents the account it
|
||||
/// finds when it connects, and follows the changes.
|
||||
pub(crate) struct Account {
|
||||
identity: watch::Sender<Option<Arc<tsproto::myts::Identity>>>,
|
||||
data: watch::Sender<Option<Arc<tsclientlib::MytsData>>>,
|
||||
}
|
||||
|
||||
impl Default for Account {
|
||||
/// No account is signed in.
|
||||
fn default() -> Self {
|
||||
Self { identity: watch::Sender::new(None), data: watch::Sender::new(None) }
|
||||
}
|
||||
}
|
||||
|
||||
impl Account {
|
||||
/// The account proof for every current and future connection. Still no
|
||||
/// account is no change: every notification restarts the handshakes and
|
||||
/// sends `updatemytsid` on every connection. Any account is (each
|
||||
/// connection's proof is signed anew).
|
||||
pub(crate) fn set_identity(&self, identity: Option<Arc<tsproto::myts::Identity>>) {
|
||||
self.identity.send_if_modified(|current| {
|
||||
if current.is_none() && identity.is_none() {
|
||||
return false;
|
||||
}
|
||||
*current = identity;
|
||||
true
|
||||
});
|
||||
}
|
||||
|
||||
/// What the servers are shown of the account: sent to every connection
|
||||
/// that presents the account's myTS ID, once connected and when it
|
||||
/// changes; cleared on a sign-out. The same data is no change.
|
||||
pub(crate) fn set_data(&self, data: Option<Arc<tsclientlib::MytsData>>) {
|
||||
self.data.send_if_modified(|current| {
|
||||
if *current == data {
|
||||
return false;
|
||||
}
|
||||
*current = data;
|
||||
true
|
||||
});
|
||||
}
|
||||
|
||||
/// What one connection watches. It keeps the senders alive for as long as
|
||||
/// it runs: a connection ends with "account source closed" when its
|
||||
/// watches have lost them, so the account outlives the connector that
|
||||
/// made the connection.
|
||||
pub(crate) fn watches(self: &Arc<Self>) -> Watches {
|
||||
Watches {
|
||||
identity: self.identity.subscribe(),
|
||||
data: self.data.subscribe(),
|
||||
_keep: Some(self.clone()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The account a connection presents and follows ([`Account::watches`]).
|
||||
pub(crate) struct Watches {
|
||||
pub(super) identity: watch::Receiver<Option<Arc<tsproto::myts::Identity>>>,
|
||||
pub(super) data: watch::Receiver<Option<Arc<tsclientlib::MytsData>>>,
|
||||
_keep: Option<Arc<Account>>,
|
||||
}
|
||||
|
||||
impl Watches {
|
||||
/// Watches of senders that someone else keeps (a test's).
|
||||
#[cfg(test)]
|
||||
pub(super) fn of(
|
||||
identity: watch::Receiver<Option<Arc<tsproto::myts::Identity>>>,
|
||||
data: watch::Receiver<Option<Arc<tsclientlib::MytsData>>>,
|
||||
) -> Self {
|
||||
Self { identity, data, _keep: None }
|
||||
}
|
||||
}
|
||||
|
||||
/// Connects to TeamSpeak 3 and 6 servers. The link of [`TsConnector`](super::TsConnector).
|
||||
#[derive(Clone, Default)]
|
||||
pub(crate) struct TsLink {
|
||||
account: Arc<Account>,
|
||||
}
|
||||
|
||||
impl TsLink {
|
||||
/// A link that presents no account until it is given one.
|
||||
pub(crate) fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
/// The account the link's connections present.
|
||||
pub(crate) fn account(&self) -> &Arc<Account> {
|
||||
&self.account
|
||||
}
|
||||
}
|
||||
|
||||
impl ServerLink for TsLink {
|
||||
fn spawn(
|
||||
&self,
|
||||
options: ConnectOptions,
|
||||
ctx: LinkCtx,
|
||||
cmds: mpsc::UnboundedReceiver<LinkCmd>,
|
||||
events: mpsc::UnboundedSender<LinkEvent>,
|
||||
) {
|
||||
tokio::spawn(voice::run(options, ctx, self.account.watches(), cmds, events));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// A myTS ID's proof (the standard Ed25519 base point as the public key).
|
||||
fn identity() -> Arc<tsproto::myts::Identity> {
|
||||
let mut private = [0; 32];
|
||||
private[0] = 1;
|
||||
let mut public = [0x66; 32];
|
||||
public[0] = 0x58;
|
||||
Arc::new(
|
||||
tsproto::myts::Identity::new(vec![1; 33], 42, public, private, vec![2; 65]).unwrap(),
|
||||
)
|
||||
}
|
||||
|
||||
/// An account sets what it holds only when it changes: every notification
|
||||
/// of a watch restarts the handshake of a connection.
|
||||
#[test]
|
||||
fn a_watch_hears_of_a_change_and_not_of_the_same_account_again() {
|
||||
let account = Arc::new(Account::default());
|
||||
let mut watches = account.watches();
|
||||
// No account, still none: nothing.
|
||||
account.set_identity(None);
|
||||
account.set_data(None);
|
||||
assert!(!watches.identity.has_changed().unwrap());
|
||||
assert!(!watches.data.has_changed().unwrap());
|
||||
|
||||
let proof = identity();
|
||||
account.set_identity(Some(proof.clone()));
|
||||
assert!(watches.identity.borrow_and_update().is_some());
|
||||
// An account again is a change (each connection signs its proof anew), the
|
||||
// same data is none.
|
||||
account.set_identity(Some(proof));
|
||||
assert!(watches.identity.has_changed().unwrap());
|
||||
watches.identity.borrow_and_update();
|
||||
let data = Arc::new(tsclientlib::MytsData::default());
|
||||
account.set_data(Some(data.clone()));
|
||||
assert!(watches.data.has_changed().unwrap());
|
||||
watches.data.borrow_and_update();
|
||||
account.set_data(Some(Arc::new(tsclientlib::MytsData::default())));
|
||||
assert!(!watches.data.has_changed().unwrap(), "equal data is no change");
|
||||
// A sign-out is a change.
|
||||
account.set_identity(None);
|
||||
assert!(watches.identity.has_changed().unwrap());
|
||||
assert!(watches.identity.borrow_and_update().is_none());
|
||||
}
|
||||
|
||||
/// A connection outlives the connector that made it (a session handed out
|
||||
/// by a connector that was dropped): its watches keep their senders.
|
||||
#[test]
|
||||
fn a_connection_keeps_the_account_open_when_its_link_is_gone() {
|
||||
let link = TsLink::new();
|
||||
let watches = link.account().watches();
|
||||
drop(link);
|
||||
assert!(watches.identity.has_changed().is_ok(), "the identity watch lost its sender");
|
||||
assert!(watches.data.has_changed().is_ok(), "the data watch lost its sender");
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,537 @@
|
||||
//! The TeamSpeak connection's presence as v1 entities (protocol section
|
||||
//! 11.1, "Ids and entities"): the client's older model on one side, the
|
||||
//! protocol's `Server`, `Channel`, `Role`, `User`, `Member`, `Presence` and
|
||||
//! `VoiceState` on the other.
|
||||
//!
|
||||
//! [`build`] is the translation the TeamSpeak `Session` makes of every
|
||||
//! snapshot its link reports; the engine's projection (`link/project.rs`)
|
||||
//! is its reverse, and `docs/session-seam.md` section 5.1 states the rule
|
||||
//! both keep: projecting what was built gives back the snapshot (up to the
|
||||
//! normalisations of section 5.4). What v1 has no field for rides in
|
||||
//! [`Foreign`](v1::Foreign) under [`FOREIGN_SYSTEM`].
|
||||
|
||||
use std::collections::{BTreeMap, HashMap, HashSet};
|
||||
|
||||
use serde_json::json;
|
||||
use voelin_model::replica::Key;
|
||||
use voelin_model::{
|
||||
BannerMode, ChannelId, ChannelInfo, ClientInfo, GroupInfo, GroupNamingMode, GroupType,
|
||||
HostMessageMode, Presence, ServerDetails,
|
||||
};
|
||||
use voelin_proto::v1::{self, Entity, entity::Kind};
|
||||
|
||||
use super::ids::{self, FOREIGN_SYSTEM, SERVER_CHAT, SERVER_ID};
|
||||
|
||||
/// Entities by key, as a scope holds them.
|
||||
pub(crate) type Layer = BTreeMap<Key, Entity>;
|
||||
|
||||
/// The entities one snapshot stands for, by scope.
|
||||
#[derive(Debug, Default)]
|
||||
pub(crate) struct Built {
|
||||
/// SERVER (1): the server, its channels and its roles.
|
||||
pub server: Layer,
|
||||
/// LIVE (1): who is online and where.
|
||||
pub live: Layer,
|
||||
/// The own user, for HOME, when the snapshot holds our client.
|
||||
pub own_user: Option<v1::User>,
|
||||
/// Clients by unique id: their user id and participant id.
|
||||
pub by_uid: HashMap<String, (u64, u32)>,
|
||||
}
|
||||
|
||||
/// The `Foreign` of something v1 has no field for.
|
||||
pub(crate) fn foreign(kind: &str, json: &serde_json::Value) -> v1::Foreign {
|
||||
v1::Foreign {
|
||||
system: FOREIGN_SYSTEM.into(),
|
||||
kind: kind.into(),
|
||||
json: serde_json::to_vec(json).unwrap_or_default().into(),
|
||||
}
|
||||
}
|
||||
|
||||
fn entity(kind: Kind) -> Entity {
|
||||
Entity { kind: Some(kind) }
|
||||
}
|
||||
|
||||
/// A picture known by its id (an icon CRC).
|
||||
fn icon(id: u32) -> Option<v1::Image> {
|
||||
(id != 0).then(|| v1::Image { hash: id.to_string(), ..Default::default() })
|
||||
}
|
||||
|
||||
fn banner_mode(mode: BannerMode) -> v1::BannerMode {
|
||||
match mode {
|
||||
BannerMode::NoAdjust => v1::BannerMode::NoAdjust,
|
||||
BannerMode::IgnoreAspect => v1::BannerMode::IgnoreAspect,
|
||||
BannerMode::KeepAspect => v1::BannerMode::KeepAspect,
|
||||
}
|
||||
}
|
||||
|
||||
fn host_message_mode(mode: HostMessageMode) -> v1::HostMessageMode {
|
||||
match mode {
|
||||
HostMessageMode::None => v1::HostMessageMode::None,
|
||||
HostMessageMode::Log => v1::HostMessageMode::Log,
|
||||
HostMessageMode::Modal => v1::HostMessageMode::Modal,
|
||||
HostMessageMode::ModalQuit => v1::HostMessageMode::ModalQuit,
|
||||
}
|
||||
}
|
||||
|
||||
/// The `Server` entity of a connection.
|
||||
pub(crate) fn server(details: &ServerDetails, name: &str, default_channel: u64) -> v1::Server {
|
||||
let gfx =
|
||||
|url: &str| (!url.is_empty()).then(|| v1::Image { url: url.into(), ..Default::default() });
|
||||
let banner = (!details.banner_url.is_empty()
|
||||
|| !details.banner_gfx_url.is_empty()
|
||||
|| details.banner_gfx_interval_s != 0
|
||||
|| details.banner_mode != BannerMode::NoAdjust)
|
||||
.then(|| v1::Banner {
|
||||
image: gfx(&details.banner_gfx_url),
|
||||
link: details.banner_url.clone(),
|
||||
reload_s: u32::try_from(details.banner_gfx_interval_s).unwrap_or(u32::MAX),
|
||||
mode: banner_mode(details.banner_mode) as i32,
|
||||
});
|
||||
let host_button = (!details.host_button_tooltip.is_empty()
|
||||
|| !details.host_button_url.is_empty()
|
||||
|| !details.host_button_gfx_url.is_empty())
|
||||
.then(|| v1::HostButton {
|
||||
tooltip: details.host_button_tooltip.clone(),
|
||||
url: details.host_button_url.clone(),
|
||||
icon: gfx(&details.host_button_gfx_url),
|
||||
});
|
||||
v1::Server {
|
||||
id: SERVER_ID,
|
||||
name: name.to_owned(),
|
||||
icon: icon(details.icon),
|
||||
banner,
|
||||
host_button,
|
||||
welcome: details.welcome_message.clone(),
|
||||
host_message: details.host_message.clone(),
|
||||
host_message_mode: host_message_mode(details.host_message_mode) as i32,
|
||||
default_channel_id: default_channel,
|
||||
default_role_id: details.default_server_group.unwrap_or(0),
|
||||
default_channel_role_id: details.default_channel_group.map_or(0, ids::channel_role),
|
||||
priority_dim_db: details.priority_speaker_dimm_db,
|
||||
max_members: u32::from(details.max_clients),
|
||||
uid: details.uid.as_deref().map(|uid| format!("ts:{uid}")).unwrap_or_default(),
|
||||
foreign: Some(foreign(
|
||||
"server",
|
||||
&json!({ "platform": details.platform, "version": details.version }),
|
||||
)),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// The server group or channel group `info` as a role.
|
||||
fn role(info: &GroupInfo, channel: bool) -> v1::Role {
|
||||
v1::Role {
|
||||
id: if channel { ids::channel_role(info.id) } else { info.id },
|
||||
server_id: SERVER_ID,
|
||||
name: info.name.clone(),
|
||||
icon: icon(info.icon),
|
||||
position: info.sort_id.saturating_neg(),
|
||||
scope: if channel { v1::RoleScope::Channel } else { v1::RoleScope::Server } as i32,
|
||||
name_mode: match info.naming_mode {
|
||||
GroupNamingMode::None => v1::NameMode::None,
|
||||
GroupNamingMode::Before => v1::NameMode::Before,
|
||||
GroupNamingMode::After => v1::NameMode::After,
|
||||
} as i32,
|
||||
kind: match info.group_type {
|
||||
GroupType::Template => v1::RoleKind::Template,
|
||||
GroupType::Regular => v1::RoleKind::Regular,
|
||||
GroupType::Query => v1::RoleKind::Query,
|
||||
} as i32,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// The sibling chain of each parent as positions: `order` names the sibling
|
||||
/// above, so the chain is followed from 0; siblings that no chain reaches
|
||||
/// (a snapshot with broken orders) follow by id.
|
||||
fn positions(channels: &BTreeMap<ChannelId, ChannelInfo>) -> HashMap<ChannelId, i64> {
|
||||
let mut by_parent: BTreeMap<ChannelId, Vec<&ChannelInfo>> = BTreeMap::new();
|
||||
for channel in channels.values() {
|
||||
by_parent.entry(channel.parent).or_default().push(channel);
|
||||
}
|
||||
let mut positions = HashMap::new();
|
||||
for siblings in by_parent.values() {
|
||||
let mut placed: HashSet<ChannelId> = HashSet::new();
|
||||
let mut next = 0;
|
||||
let mut above = 0;
|
||||
// The sibling whose `order` is the one placed last (lowest id first, so
|
||||
// that two claiming the same place do not depend on map order).
|
||||
while let Some(channel) = siblings
|
||||
.iter()
|
||||
.filter(|c| c.order == above && !placed.contains(&c.id))
|
||||
.min_by_key(|c| c.id)
|
||||
{
|
||||
positions.insert(channel.id, next * 1024);
|
||||
placed.insert(channel.id);
|
||||
above = channel.id;
|
||||
next += 1;
|
||||
}
|
||||
for channel in siblings.iter().filter(|c| !placed.contains(&c.id)) {
|
||||
positions.insert(channel.id, next * 1024);
|
||||
next += 1;
|
||||
}
|
||||
}
|
||||
positions
|
||||
}
|
||||
|
||||
fn channel(info: &ChannelInfo, position: i64) -> v1::Channel {
|
||||
let mut needed = HashMap::new();
|
||||
if info.needed_talk_power != 0 {
|
||||
needed.insert(v1::Power::Talk as u32, info.needed_talk_power);
|
||||
}
|
||||
if info.needed_subscribe_power != 0 {
|
||||
needed.insert(v1::Power::Subscribe as u32, info.needed_subscribe_power);
|
||||
}
|
||||
let banner =
|
||||
(info.banner_gfx_url.is_some() || info.banner_mode != BannerMode::NoAdjust).then(|| {
|
||||
v1::Banner {
|
||||
image: info
|
||||
.banner_gfx_url
|
||||
.as_ref()
|
||||
.map(|url| v1::Image { url: url.clone(), ..Default::default() }),
|
||||
mode: banner_mode(info.banner_mode) as i32,
|
||||
..Default::default()
|
||||
}
|
||||
});
|
||||
v1::Channel {
|
||||
id: info.id,
|
||||
server_id: SERVER_ID,
|
||||
parent_id: info.parent,
|
||||
kind: v1::ChannelKind::Voice as i32,
|
||||
name: info.name.clone(),
|
||||
topic: info.topic.clone().unwrap_or_default(),
|
||||
position,
|
||||
has_password: info.has_password,
|
||||
// A limit of 0 cannot be said with `max_members` (0 is unlimited).
|
||||
max_members: info.max_clients.map_or(0, |n| u32::try_from(n).unwrap_or(0)),
|
||||
needed,
|
||||
icon: icon(info.icon),
|
||||
banner,
|
||||
is_default: info.is_default,
|
||||
foreign: (info.max_clients == Some(0))
|
||||
.then(|| foreign("channel", &json!({ "max_clients": 0 }))),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// The user a client is. `Foreign` carries a unique id that is no base64.
|
||||
fn user(client: &ClientInfo, id: u64, ts6: bool) -> v1::User {
|
||||
let uid = client.uid.as_deref().filter(|u| !u.is_empty());
|
||||
let bytes = uid.and_then(ids::uid_bytes);
|
||||
let avatar = (client.avatar.is_some() || client.myts_avatar.is_some()).then(|| v1::Image {
|
||||
hash: client.avatar.clone().unwrap_or_default(),
|
||||
url: client.myts_avatar.clone().unwrap_or_default(),
|
||||
..Default::default()
|
||||
});
|
||||
v1::User {
|
||||
id,
|
||||
uid: bytes.clone().unwrap_or_default().into(),
|
||||
uid_kind: if ts6 { v1::IdKind::Ts6 } else { v1::IdKind::Ts3 } as i32,
|
||||
name: client.nickname.clone(),
|
||||
avatar,
|
||||
badges: client.badges.clone(),
|
||||
country: client.country.clone().unwrap_or_default(),
|
||||
foreign: uid.filter(|_| bytes.is_none()).map(|uid| foreign("user", &json!({ "uid": uid }))),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// A user who is on no snapshot (the sender of a message or a poke): its
|
||||
/// unique id and name only. `None` for a unique id with no content.
|
||||
pub(crate) fn bare_user(uid: &str, name: &str, ts6: bool) -> v1::User {
|
||||
user(
|
||||
&ClientInfo { uid: Some(uid.to_owned()), nickname: name.to_owned(), ..Default::default() },
|
||||
ids::synthetic_user(uid),
|
||||
ts6,
|
||||
)
|
||||
}
|
||||
|
||||
/// A user who is on no snapshot and has no unique id (the sender of a poke
|
||||
/// or a message that the link names by its client id only): `id` and name.
|
||||
pub(crate) fn client_user(id: u64, name: &str, ts6: bool) -> v1::User {
|
||||
user(&ClientInfo { nickname: name.to_owned(), ..Default::default() }, id, ts6)
|
||||
}
|
||||
|
||||
/// Everything the snapshot `presence` says, as entities of the scopes of
|
||||
/// server 1. `ts6`: the server is TeamSpeak 6 (the kind of its unique ids).
|
||||
pub(crate) fn build(presence: &Presence, ts6: bool, own_client: Option<u16>) -> Built {
|
||||
let mut built = Built::default();
|
||||
let name =
|
||||
if presence.server.name.is_empty() { &presence.server_name } else { &presence.server.name };
|
||||
let default_channel =
|
||||
presence.channels.values().find(|c| c.is_default).map_or(0, |channel| channel.id);
|
||||
let put = |layer: &mut Layer, kind: Kind| {
|
||||
let entity = entity(kind);
|
||||
if let Some(key) = Key::of(&entity) {
|
||||
layer.insert(key, entity);
|
||||
}
|
||||
};
|
||||
put(&mut built.server, Kind::Server(server(&presence.server, name, default_channel)));
|
||||
put(
|
||||
&mut built.server,
|
||||
Kind::Channel(v1::Channel {
|
||||
id: SERVER_CHAT,
|
||||
server_id: SERVER_ID,
|
||||
kind: v1::ChannelKind::ServerChat as i32,
|
||||
name: "Server chat".into(),
|
||||
..Default::default()
|
||||
}),
|
||||
);
|
||||
let positions = positions(&presence.channels);
|
||||
for info in presence.channels.values() {
|
||||
let position = positions.get(&info.id).copied().unwrap_or_default();
|
||||
put(&mut built.server, Kind::Channel(channel(info, position)));
|
||||
}
|
||||
for info in presence.server_groups.values() {
|
||||
put(&mut built.server, Kind::Role(role(info, false)));
|
||||
}
|
||||
for info in presence.channel_groups.values() {
|
||||
put(&mut built.server, Kind::Role(role(info, true)));
|
||||
}
|
||||
// The own client first, then by client id.
|
||||
let mut clients: Vec<&ClientInfo> = presence.clients.values().collect();
|
||||
clients.sort_by_key(|client| (Some(client.id) != own_client, client.id));
|
||||
let mut used: HashSet<u64> = HashSet::new();
|
||||
for client in clients {
|
||||
// The same identity twice on a server has one database id: the own
|
||||
// client keeps it (it must stay the user we are, also while a ghost of
|
||||
// our old connection lingers), else the lower client id; the other is a
|
||||
// user of its own.
|
||||
let uid = client.uid.as_deref().filter(|u| !u.is_empty());
|
||||
let mut id = client.database_id.unwrap_or_else(|| {
|
||||
ids::synthetic_user(&uid.map_or_else(|| format!("client:{}", client.id), str::to_owned))
|
||||
});
|
||||
if !used.insert(id) {
|
||||
id = ids::synthetic_user(&format!("client:{}", client.id));
|
||||
used.insert(id);
|
||||
}
|
||||
let participant = u32::from(client.id);
|
||||
if let Some(uid) = uid {
|
||||
built.by_uid.entry(uid.to_owned()).or_insert((id, participant));
|
||||
}
|
||||
let user = user(client, id, ts6);
|
||||
if Some(client.id) == own_client {
|
||||
built.own_user = Some(user.clone());
|
||||
}
|
||||
put(&mut built.live, Kind::User(user));
|
||||
put(
|
||||
&mut built.live,
|
||||
Kind::Member(v1::Member {
|
||||
server_id: SERVER_ID,
|
||||
user_id: id,
|
||||
roles: client.server_groups.clone(),
|
||||
channel_roles: client
|
||||
.channel_group
|
||||
.map(|group| (client.channel, ids::channel_role(group)))
|
||||
.into_iter()
|
||||
.collect(),
|
||||
description: client.description.clone().unwrap_or_default(),
|
||||
foreign: (client.icon != 0)
|
||||
.then(|| foreign("client", &json!({ "icon": client.icon }))),
|
||||
..Default::default()
|
||||
}),
|
||||
);
|
||||
put(
|
||||
&mut built.live,
|
||||
Kind::Presence(v1::Presence {
|
||||
user_id: id,
|
||||
status: if client.away.is_some() { v1::Status::Idle } else { v1::Status::Online }
|
||||
as i32,
|
||||
text: client.away.clone().unwrap_or_default(),
|
||||
..Default::default()
|
||||
}),
|
||||
);
|
||||
put(
|
||||
&mut built.live,
|
||||
Kind::Voice(v1::VoiceState {
|
||||
server_id: SERVER_ID,
|
||||
participant_id: participant,
|
||||
user_id: id,
|
||||
channel_id: client.channel,
|
||||
slot: slot(client.id),
|
||||
nick: client.nickname.clone(),
|
||||
kind: if client.is_query {
|
||||
v1::ParticipantKind::Query
|
||||
} else {
|
||||
v1::ParticipantKind::User
|
||||
} as i32,
|
||||
self_mute: client.input_muted,
|
||||
self_deaf: client.output_muted,
|
||||
priority_speaker: client.priority_speaker,
|
||||
channel_commander: client.channel_commander,
|
||||
talker: client.talker,
|
||||
talk_power: client.talk_power,
|
||||
recording: client.recording,
|
||||
streaming: client.streaming.unwrap_or(false),
|
||||
..Default::default()
|
||||
}),
|
||||
);
|
||||
}
|
||||
built
|
||||
}
|
||||
|
||||
/// The unique id of a user as the client's older model writes it: base64 for
|
||||
/// a TeamSpeak id, or the text kept in `Foreign` when it was no base64 (a
|
||||
/// ServerQuery client's login name). `None` for a user without one.
|
||||
pub(crate) fn user_uid(user: &v1::User) -> Option<String> {
|
||||
let kept = user
|
||||
.foreign
|
||||
.as_ref()
|
||||
.filter(|f| f.system == FOREIGN_SYSTEM && f.kind == "user")
|
||||
.and_then(|f| serde_json::from_slice::<serde_json::Value>(&f.json).ok())
|
||||
.and_then(|json| json.get("uid")?.as_str().map(str::to_owned));
|
||||
kept.or_else(|| voelin_model::replica::convert::uid_text(user))
|
||||
}
|
||||
|
||||
/// The media slot of a client: its id plus one (slot 0 is not a media source).
|
||||
pub(crate) fn slot(client: u16) -> u32 {
|
||||
u32::from(client) + 1
|
||||
}
|
||||
|
||||
/// The key of an entity, as a `Change` deletes it: the key fields only.
|
||||
pub(crate) fn key_only(entity: &Entity) -> Entity {
|
||||
let kind = match entity.kind.as_ref() {
|
||||
Some(Kind::Server(s)) => Kind::Server(v1::Server { id: s.id, ..Default::default() }),
|
||||
Some(Kind::Channel(c)) => Kind::Channel(v1::Channel { id: c.id, ..Default::default() }),
|
||||
Some(Kind::Role(r)) => {
|
||||
Kind::Role(v1::Role { server_id: r.server_id, id: r.id, ..Default::default() })
|
||||
}
|
||||
Some(Kind::Member(m)) => Kind::Member(v1::Member {
|
||||
server_id: m.server_id,
|
||||
user_id: m.user_id,
|
||||
..Default::default()
|
||||
}),
|
||||
Some(Kind::User(u)) => Kind::User(v1::User { id: u.id, ..Default::default() }),
|
||||
Some(Kind::Presence(p)) => {
|
||||
Kind::Presence(v1::Presence { user_id: p.user_id, ..Default::default() })
|
||||
}
|
||||
Some(Kind::Voice(v)) => Kind::Voice(v1::VoiceState {
|
||||
server_id: v.server_id,
|
||||
participant_id: v.participant_id,
|
||||
..Default::default()
|
||||
}),
|
||||
Some(Kind::Message(m)) => {
|
||||
Kind::Message(v1::Message { channel_id: m.channel_id, id: m.id, ..Default::default() })
|
||||
}
|
||||
Some(Kind::Mail(m)) => Kind::Mail(v1::Mail { id: m.id, ..Default::default() }),
|
||||
_ => return entity.clone(),
|
||||
};
|
||||
Entity { kind: Some(kind) }
|
||||
}
|
||||
|
||||
/// What changed from `old` to `new`: the entities to put (new or different)
|
||||
/// and the keys to delete.
|
||||
pub(crate) fn diff(old: &Layer, new: &Layer) -> (Vec<Entity>, Vec<Entity>) {
|
||||
let put = new.iter().filter(|(key, entity)| old.get(*key) != Some(*entity));
|
||||
let del = old.iter().filter(|(key, _)| !new.contains_key(*key));
|
||||
(put.map(|(_, e)| e.clone()).collect(), del.map(|(_, e)| key_only(e)).collect())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn channel_info(id: u64, parent: u64, order: u64) -> ChannelInfo {
|
||||
ChannelInfo { id, parent, order, name: format!("c{id}"), ..Default::default() }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_order_chain_becomes_positions() {
|
||||
// 3 first, then 1, then 2 under the same parent; 5 alone under 3.
|
||||
let channels: BTreeMap<_, _> = [
|
||||
channel_info(1, 0, 3),
|
||||
channel_info(2, 0, 1),
|
||||
channel_info(3, 0, 0),
|
||||
channel_info(5, 3, 0),
|
||||
]
|
||||
.into_iter()
|
||||
.map(|c| (c.id, c))
|
||||
.collect();
|
||||
let positions = positions(&channels);
|
||||
assert!(positions[&3] < positions[&1] && positions[&1] < positions[&2]);
|
||||
assert_eq!(positions[&5], 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn siblings_a_chain_does_not_reach_follow_by_id() {
|
||||
// Both claim the first place, and 4 follows nobody.
|
||||
let channels: BTreeMap<_, _> =
|
||||
[channel_info(1, 0, 0), channel_info(2, 0, 0), channel_info(4, 0, 77)]
|
||||
.into_iter()
|
||||
.map(|c| (c.id, c))
|
||||
.collect();
|
||||
let positions = positions(&channels);
|
||||
assert_eq!((positions[&1], positions[&2], positions[&4]), (0, 1024, 2048));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_same_identity_twice_keeps_both_clients() {
|
||||
let client = |id, db| ClientInfo {
|
||||
id,
|
||||
uid: Some("uXDkxSZbv0IoA0z/toW3guGpUbI=".into()),
|
||||
nickname: format!("n{id}"),
|
||||
database_id: Some(db),
|
||||
..Default::default()
|
||||
};
|
||||
let mut presence = Presence::default();
|
||||
for c in [client(3, 77), client(4, 77)] {
|
||||
presence.clients.insert(c.id, c);
|
||||
}
|
||||
let built = build(&presence, false, None);
|
||||
let voices = built.live.keys().filter(|k| matches!(k, Key::Voice { .. })).count();
|
||||
let users = built.live.keys().filter(|k| matches!(k, Key::User { .. })).count();
|
||||
assert_eq!((voices, users), (2, 2));
|
||||
}
|
||||
|
||||
/// The own client is the user whose database id the identity has, also when a
|
||||
/// ghost of the old connection (the lower client id) lingers.
|
||||
#[test]
|
||||
fn the_own_client_keeps_the_database_id_of_an_identity_that_is_there_twice() {
|
||||
let client = |id| ClientInfo {
|
||||
id,
|
||||
uid: Some("uXDkxSZbv0IoA0z/toW3guGpUbI=".into()),
|
||||
nickname: format!("n{id}"),
|
||||
database_id: Some(77),
|
||||
..Default::default()
|
||||
};
|
||||
let mut presence = Presence::default();
|
||||
for c in [client(3), client(4)] {
|
||||
presence.clients.insert(c.id, c);
|
||||
}
|
||||
let user_of = |built: &Built, client: u32| {
|
||||
let key = Key::Voice { server_id: SERVER_ID, participant_id: client };
|
||||
let Some(Entity { kind: Some(Kind::Voice(voice)) }) = built.live.get(&key) else {
|
||||
panic!("no voice state")
|
||||
};
|
||||
voice.user_id
|
||||
};
|
||||
// Nobody is us: the lower client id keeps it.
|
||||
let built = build(&presence, false, None);
|
||||
assert_eq!(user_of(&built, 3), 77);
|
||||
assert_ne!(user_of(&built, 4), 77);
|
||||
// The later client is us: it keeps it, and the ghost has the made-up id.
|
||||
let built = build(&presence, false, Some(4));
|
||||
assert_eq!(user_of(&built, 4), 77);
|
||||
assert_ne!(user_of(&built, 3), 77);
|
||||
assert_eq!(built.own_user.map(|u| u.id), Some(77));
|
||||
assert_eq!(built.by_uid["uXDkxSZbv0IoA0z/toW3guGpUbI="], (77, 4));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_change_deletes_by_key_and_puts_what_differs() {
|
||||
let mut presence = Presence::default();
|
||||
presence.channels.insert(1, channel_info(1, 0, 0));
|
||||
let before = build(&presence, false, None);
|
||||
presence.channels.insert(2, channel_info(2, 0, 1));
|
||||
presence.channels.get_mut(&1).unwrap().name = "renamed".into();
|
||||
let after = build(&presence, false, None);
|
||||
let (put, del) = diff(&before.server, &after.server);
|
||||
assert_eq!(put.len(), 2, "the renamed channel and the new one");
|
||||
assert!(del.is_empty());
|
||||
let (put, del) = diff(&after.server, &before.server);
|
||||
assert_eq!(put.len(), 1, "channel 1 is back to its old name");
|
||||
assert_eq!(del.len(), 1);
|
||||
let Some(Kind::Channel(gone)) = &del[0].kind else { panic!("a channel") };
|
||||
assert_eq!((gone.id, gone.name.as_str()), (2, ""));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
//! Ids and unique ids as the TeamSpeak gateway writes them (protocol
|
||||
//! section 11.1, "Ids"): TeamSpeak's numbers as they are, and a few
|
||||
//! synthetic ones with bit 63 set.
|
||||
//!
|
||||
//! Both sides of the seam use these rules: the TeamSpeak `Session`
|
||||
//! ([`super::LinkSession`]) writes entities with them, and the engine's
|
||||
//! projection (`link/project.rs`) undoes the few that the client's older
|
||||
//! model has no room for.
|
||||
|
||||
use base64::Engine as _;
|
||||
use base64::engine::general_purpose::STANDARD;
|
||||
|
||||
/// The only server of a TeamSpeak connection (its virtual server).
|
||||
pub(crate) const SERVER_ID: u64 = 1;
|
||||
|
||||
/// Marks the ids the gateway makes up: the server chat, direct-message
|
||||
/// channels and users it knows by their unique id only.
|
||||
pub(crate) const SYNTHETIC: u64 = 1 << 63;
|
||||
|
||||
/// The channel of the server chat, in the SERVER scope.
|
||||
pub(crate) const SERVER_CHAT: u64 = SYNTHETIC;
|
||||
|
||||
/// Set on the id of a channel group, so that a role id does not mean a server
|
||||
/// group and a channel group at once.
|
||||
pub(crate) const CHANNEL_ROLE: u64 = 1 << 62;
|
||||
|
||||
/// The `Foreign.system` of what the protocol has no field for.
|
||||
pub(crate) const FOREIGN_SYSTEM: &str = "teamspeak";
|
||||
|
||||
/// The role id of a channel group.
|
||||
pub(crate) fn channel_role(group: u64) -> u64 {
|
||||
group | CHANNEL_ROLE
|
||||
}
|
||||
|
||||
/// The channel group a role id stands for (the reverse of [`channel_role`]).
|
||||
pub(crate) fn channel_group(role: u64) -> u64 {
|
||||
role & !CHANNEL_ROLE
|
||||
}
|
||||
|
||||
/// FNV-1a, 64 bits.
|
||||
fn fnv1a(bytes: &[u8]) -> u64 {
|
||||
let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
|
||||
for byte in bytes {
|
||||
hash ^= u64::from(*byte);
|
||||
hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
|
||||
}
|
||||
hash
|
||||
}
|
||||
|
||||
/// A synthetic id for something known by a name only: bit 63 set and the
|
||||
/// hash of `name` in the low 63 bits (1 if they come out 0, so it is never
|
||||
/// [`SERVER_CHAT`]).
|
||||
fn synthetic(name: &str) -> u64 {
|
||||
let low = fnv1a(name.as_bytes()) & !SYNTHETIC;
|
||||
SYNTHETIC | low.max(1)
|
||||
}
|
||||
|
||||
/// The direct-message channel with the client of this unique id.
|
||||
pub(crate) fn dm_channel(uid: &str) -> u64 {
|
||||
synthetic(uid)
|
||||
}
|
||||
|
||||
/// The user id of a client that has no database id (or that the snapshot
|
||||
/// does not hold): by unique id, else by whatever names it.
|
||||
pub(crate) fn synthetic_user(uid: &str) -> u64 {
|
||||
synthetic(uid)
|
||||
}
|
||||
|
||||
/// The bytes of a unique id, when it is canonical base64 (what TeamSpeak
|
||||
/// writes): decoding and encoding again gives the same text. A ServerQuery
|
||||
/// client's login name, or anything else, is not, and goes into
|
||||
/// [`Foreign`](voelin_proto::v1::Foreign) instead.
|
||||
pub(crate) fn uid_bytes(uid: &str) -> Option<Vec<u8>> {
|
||||
let bytes = STANDARD.decode(uid).ok()?;
|
||||
(STANDARD.encode(&bytes) == uid && !bytes.is_empty()).then_some(bytes)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn channel_groups_keep_their_number_below_the_flag() {
|
||||
assert_eq!(channel_role(8), 8 | (1 << 62));
|
||||
assert_eq!(channel_group(channel_role(8)), 8);
|
||||
assert_eq!(channel_group(channel_role(0)), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn synthetic_ids_have_bit_63_and_are_never_the_server_chat() {
|
||||
for name in ["", "alice=", "client:7", "a-very-long-name-that-hashes-to-something"] {
|
||||
let id = dm_channel(name);
|
||||
assert_ne!(id & SYNTHETIC, 0, "{name}");
|
||||
assert_ne!(id, SERVER_CHAT, "{name}");
|
||||
}
|
||||
assert_eq!(dm_channel("alice="), dm_channel("alice="));
|
||||
assert_ne!(dm_channel("alice="), dm_channel("bob="));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_canonical_base64_is_a_unique_id() {
|
||||
// A TeamSpeak 3 unique id (SHA-1) and a TeamSpeak 6 one (SHA-256).
|
||||
assert_eq!(uid_bytes("uXDkxSZbv0IoA0z/toW3guGpUbI=").map(|b| b.len()), Some(20));
|
||||
assert_eq!(
|
||||
uid_bytes("xEZDkyeGdZ4bOSBCKqzTw8jVz2jsZCrJDRl9F8WWd3M=").map(|b| b.len()),
|
||||
Some(32)
|
||||
);
|
||||
// A ServerQuery login name, a fixture's name, the empty string.
|
||||
for not in ["serveradmin", "alice=", "me=", "", "Af4"] {
|
||||
assert_eq!(uid_bytes(not), None, "{not:?}");
|
||||
}
|
||||
// Non-canonical trailing bits decode but do not round trip.
|
||||
assert_eq!(uid_bytes("Af5="), None);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,862 @@
|
||||
//! The TeamSpeak `Session` against the development servers
|
||||
//! (`dev/docker-compose.yml`; `docs/session-seam.md` sections 9.3 and 16).
|
||||
//! Runs only with `VOELIN_LIVE=1`:
|
||||
//!
|
||||
//! ```text
|
||||
//! VOELIN_LIVE=1 cargo test -p voelin-core --lib ts_session::live_tests -- --test-threads=1
|
||||
//! ```
|
||||
//!
|
||||
//! Two kinds of test, each on TeamSpeak 3 and on TeamSpeak 6:
|
||||
//!
|
||||
//! - the link conformance suite of the protocol repository, the cases that
|
||||
//! apply to a TeamSpeak session, with the verdict of every case asserted
|
||||
//! and the reason of every case that cannot pass or cannot run in
|
||||
//! [`EXPECTED`];
|
||||
//! - what the suite cannot reach, as a session of its own does it: a message
|
||||
//! in the own channel answered, then pushed to the other session and back to
|
||||
//! ours, the refusals of a move, a poke between two sessions, voice RTP from
|
||||
//! one session's slot to the other's media sink, and a channel file written
|
||||
//! and read back from an offset.
|
||||
//!
|
||||
//! The sessions are made by [`TsConnector`] through the plain `Connector`
|
||||
//! interface, as a client of the seam outside an engine would make them.
|
||||
//!
|
||||
//! The servers ban an address that connects as often as these tests do
|
||||
//! (`ConnectFailedBanned` after three or four connections) unless their
|
||||
//! anti-flood limits are raised first. `scripts/it-smoke.sh` raises them when it
|
||||
//! prepares its admin identity; this module raises them itself, once per server
|
||||
//! and run, through the ServerQuery admin login that `refused_moves` uses
|
||||
//! ([`raise_flood_limits`]), so that the command above works on a freshly
|
||||
//! started stack. It needs that login (the development servers of
|
||||
//! `dev/docker-compose.yml` have it) and does not lower the limits again.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::future::Future;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
use tokio::sync::mpsc;
|
||||
use voelin_proto::link::{Connector, FlowId, MediaClass, MediaPacket, voice_sub};
|
||||
use voelin_proto::media::payload::PT_OPUS;
|
||||
use voelin_proto::media::{RtpHeader, RtpView};
|
||||
use voelin_proto::test_util::conformance::{self, Fixture, Verdict};
|
||||
use voelin_proto::test_util::{FakeConnector, MediaReceiver, media_channel};
|
||||
use voelin_proto::v1::request::Op;
|
||||
use voelin_proto::v1::{self, entity::Kind};
|
||||
|
||||
use super::*;
|
||||
use crate::link::{Backends, VoiceOptions, connect_params};
|
||||
|
||||
fn live() -> bool {
|
||||
std::env::var("VOELIN_LIVE").is_ok_and(|v| v == "1")
|
||||
}
|
||||
|
||||
/// How long a test waits for the server.
|
||||
const WAIT: Duration = Duration::from_secs(20);
|
||||
|
||||
async fn within<T>(what: &str, future: impl Future<Output = T>) -> T {
|
||||
match tokio::time::timeout(WAIT, future).await {
|
||||
Ok(value) => value,
|
||||
Err(_) => panic!("timed out after {WAIT:?} waiting for {what}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// A development server: where to connect, and how to ask it as the admin.
|
||||
#[derive(Clone, Copy)]
|
||||
struct Dev {
|
||||
name: &'static str,
|
||||
voice: &'static str,
|
||||
ssh: bool,
|
||||
query: &'static str,
|
||||
}
|
||||
|
||||
const TS3: Dev = Dev { name: "ts3", voice: "127.0.0.1:9987", ssh: false, query: "127.0.0.1:10011" };
|
||||
const TS6: Dev = Dev { name: "ts6", voice: "127.0.0.1:9988", ssh: true, query: "127.0.0.1:10022" };
|
||||
|
||||
impl Dev {
|
||||
fn query(&self) -> voelin_query::Connect {
|
||||
voelin_query::Connect {
|
||||
transport: if self.ssh {
|
||||
voelin_query::Transport::Ssh
|
||||
} else {
|
||||
voelin_query::Transport::Raw
|
||||
},
|
||||
addr: self.query.into(),
|
||||
user: "serveradmin".into(),
|
||||
secret: Some("voelin-dev-admin".into()),
|
||||
server_port: Some(9987),
|
||||
server_id: None,
|
||||
line: voelin_query::LineOptions { rate_limit: None, ..Default::default() },
|
||||
}
|
||||
}
|
||||
|
||||
/// A nickname no other client of this run has.
|
||||
fn nick(&self, role: &str) -> String {
|
||||
static COUNT: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
|
||||
let n = COUNT.fetch_add(1, Ordering::Relaxed);
|
||||
format!("{role}-{}-{n}", std::process::id() % 10_000)
|
||||
}
|
||||
}
|
||||
|
||||
/// Raise the anti-flood limits of a development server, once per run, and
|
||||
/// lift the bans an earlier run left behind. The tests connect many times in
|
||||
/// a few seconds from one address, which a server with its default limits
|
||||
/// bans (`ConnectFailedBanned`); `scripts/it-smoke.sh` sets the same two
|
||||
/// values in `admin_args`. Done through the ServerQuery login of the admin,
|
||||
/// which the tests that create channels and keys use as well.
|
||||
async fn raise_flood_limits(dev: &Dev) {
|
||||
use tokio::sync::OnceCell;
|
||||
use voelin_query::{Command as Query, QueryClient};
|
||||
static TS3_READY: OnceCell<()> = OnceCell::const_new();
|
||||
static TS6_READY: OnceCell<()> = OnceCell::const_new();
|
||||
let ready = if dev.ssh { &TS6_READY } else { &TS3_READY };
|
||||
ready
|
||||
.get_or_init(|| async {
|
||||
let (admin, _) = within("the query login", QueryClient::connect(&dev.query()))
|
||||
.await
|
||||
.unwrap_or_else(|e| panic!("the query login of {}: {e}", dev.name));
|
||||
for key in [
|
||||
"virtualserver_antiflood_points_needed_ip_block",
|
||||
"virtualserver_antiflood_points_needed_command_block",
|
||||
] {
|
||||
let edit = Query::new("serveredit").arg(key, 100_000);
|
||||
within("the anti-flood limits", admin.send(&edit))
|
||||
.await
|
||||
.unwrap_or_else(|e| panic!("{} refused {key}: {e}", dev.name));
|
||||
}
|
||||
// A ban of an earlier run outlives the change of the limit.
|
||||
within("the ban list", admin.send(&Query::new("bandelall")))
|
||||
.await
|
||||
.unwrap_or_else(|e| panic!("{} did not lift its bans: {e}", dev.name));
|
||||
})
|
||||
.await;
|
||||
}
|
||||
|
||||
/// A TeamSpeak session as a client of the seam sees it: made by the
|
||||
/// connector, with its push channel and media sink.
|
||||
async fn session(
|
||||
dev: &Dev,
|
||||
options: &VoiceOptions,
|
||||
) -> (Arc<dyn Session>, mpsc::Receiver<v1::Push>, MediaReceiver) {
|
||||
raise_flood_limits(dev).await;
|
||||
let (sink, media) = media_channel();
|
||||
let params = connect_params(options, sink, &Backends::empty()).expect("connect parameters");
|
||||
let connected =
|
||||
within(&format!("a connection to {}", dev.name), TsConnector::new().connect(params))
|
||||
.await
|
||||
.unwrap_or_else(|e| panic!("{} did not connect: {e}", dev.name));
|
||||
(connected.session, connected.pushes, media)
|
||||
}
|
||||
|
||||
/// A client of the TeamSpeak session that has done what an engine does after
|
||||
/// it connects (`docs/session-seam.md` 4.2, without the replica): the server
|
||||
/// listed, HOME, SERVER and LIVE subscribed and synced, a seat in voice.
|
||||
struct Client {
|
||||
session: Arc<dyn Session>,
|
||||
pushes: mpsc::Receiver<v1::Push>,
|
||||
media: MediaReceiver,
|
||||
server: u64,
|
||||
default_channel: u64,
|
||||
/// Our seat in voice (participant, slot, channel).
|
||||
seat: v1::VoiceState,
|
||||
/// The voice states of the server, as the pushes told them.
|
||||
voices: BTreeMap<u32, v1::VoiceState>,
|
||||
}
|
||||
|
||||
fn scope(kind: v1::ScopeKind, id: u64) -> v1::Scope {
|
||||
v1::Scope { kind: kind as i32, id }
|
||||
}
|
||||
|
||||
impl Client {
|
||||
async fn connect(dev: &Dev, nick: &str) -> Self {
|
||||
Self::connect_with(dev, VoiceOptions::new(dev.voice, nick)).await
|
||||
}
|
||||
|
||||
async fn connect_with(dev: &Dev, options: VoiceOptions) -> Self {
|
||||
let (session, pushes, media) = session(dev, &options).await;
|
||||
let mut client = Self {
|
||||
session,
|
||||
pushes,
|
||||
media,
|
||||
server: 0,
|
||||
default_channel: 0,
|
||||
seat: v1::VoiceState::default(),
|
||||
voices: BTreeMap::new(),
|
||||
};
|
||||
let list = Op::List(v1::List { kind: v1::EntityKind::Server as i32, ..Default::default() });
|
||||
let Answer::Entities(servers) = client.ask(list).await.expect("the server list") else {
|
||||
panic!("the server list is not entities")
|
||||
};
|
||||
let server = servers
|
||||
.items
|
||||
.iter()
|
||||
.find_map(|e| match &e.kind {
|
||||
Some(Kind::Server(server)) => Some(server.clone()),
|
||||
_ => None,
|
||||
})
|
||||
.expect("the host lists its server");
|
||||
client.server = server.id;
|
||||
client.default_channel = server.default_channel_id;
|
||||
for scope in [
|
||||
scope(v1::ScopeKind::Home, 0),
|
||||
scope(v1::ScopeKind::Server, server.id),
|
||||
scope(v1::ScopeKind::Live, server.id),
|
||||
] {
|
||||
client.subscribe(scope).await;
|
||||
}
|
||||
client.seat = client.join(client.default_channel, "").await.expect("a seat in voice");
|
||||
client.settle().await;
|
||||
client
|
||||
}
|
||||
|
||||
/// A request, answered within [`WAIT`].
|
||||
async fn ask(&self, op: Op) -> Result<Answer, SessionError> {
|
||||
within("an answer", self.session.request(op)).await
|
||||
}
|
||||
|
||||
/// Subscribe `scope` and take its sync off the push channel.
|
||||
async fn subscribe(&mut self, scope: v1::Scope) {
|
||||
let op = Op::Subscribe(v1::Subscribe { scope: Some(scope), ..Default::default() });
|
||||
self.ask(op).await.expect("a subscription");
|
||||
self.until("the end of the sync", |push| match &push.body {
|
||||
Some(v1::push::Body::SyncEnd(end)) if end.scope == Some(scope) => Some(()),
|
||||
_ => None,
|
||||
})
|
||||
.await;
|
||||
}
|
||||
|
||||
/// `JoinVoice`: our seat, or why not.
|
||||
async fn join(&self, channel: u64, password: &str) -> Result<v1::VoiceState, SessionError> {
|
||||
let join = v1::JoinVoice {
|
||||
server_id: self.server,
|
||||
channel_id: channel,
|
||||
password: password.into(),
|
||||
..Default::default()
|
||||
};
|
||||
match self.ask(Op::JoinVoice(join)).await? {
|
||||
Answer::Entities(entities) => entities
|
||||
.items
|
||||
.into_iter()
|
||||
.find_map(|e| match e.kind {
|
||||
Some(Kind::Voice(voice)) => Some(voice),
|
||||
_ => None,
|
||||
})
|
||||
.ok_or_else(|| SessionError::Protocol("no voice state in the answer".into())),
|
||||
other => Err(SessionError::Protocol(format!("unexpected answer {other:?}"))),
|
||||
}
|
||||
}
|
||||
|
||||
/// Keep track of what a push says about the server and its voice states.
|
||||
fn absorb(&mut self, push: &v1::Push) {
|
||||
let Some(v1::push::Body::Change(change)) = &push.body else { return };
|
||||
for entity in &change.put {
|
||||
match &entity.kind {
|
||||
Some(Kind::Voice(voice)) => {
|
||||
self.voices.insert(voice.participant_id, voice.clone());
|
||||
}
|
||||
Some(Kind::Server(server)) if server.default_channel_id != 0 => {
|
||||
self.default_channel = server.default_channel_id;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
for entity in &change.del {
|
||||
if let Some(Kind::Voice(voice)) = &entity.kind {
|
||||
self.voices.remove(&voice.participant_id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The next push `f` picks, skipping (and keeping track of) the others.
|
||||
async fn until<T>(&mut self, what: &str, mut f: impl FnMut(&v1::Push) -> Option<T>) -> T {
|
||||
within(what, async {
|
||||
loop {
|
||||
let push = self.pushes.recv().await.expect("the session lives");
|
||||
self.absorb(&push);
|
||||
if let Some(t) = f(&push) {
|
||||
return t;
|
||||
}
|
||||
}
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// Wait until the host shows our seat in LIVE: the first snapshot of the
|
||||
/// TeamSpeak link may come after the session was handed out, so the syncs
|
||||
/// can be empty and the voice states follow as changes. The seat then
|
||||
/// names the channel we are in.
|
||||
async fn settle(&mut self) {
|
||||
let participant = self.seat.participant_id;
|
||||
within("our voice state to appear", async {
|
||||
while !self.voices.contains_key(&participant) {
|
||||
let push = self.pushes.recv().await.expect("the session lives");
|
||||
self.absorb(&push);
|
||||
}
|
||||
})
|
||||
.await;
|
||||
self.seat = self.voices[&participant].clone();
|
||||
}
|
||||
|
||||
/// The next message `Change` of the CHAT scope of `channel` with `text`.
|
||||
async fn message(&mut self, channel: u64, text: &str) -> v1::Message {
|
||||
let chat = Some(scope(v1::ScopeKind::Chat, channel));
|
||||
self.until(&format!("the message {text:?}"), |push| match &push.body {
|
||||
Some(v1::push::Body::Change(change)) if change.scope == chat => {
|
||||
change.put.iter().find_map(|e| match &e.kind {
|
||||
Some(Kind::Message(message)) if message.text == text => Some(message.clone()),
|
||||
_ => None,
|
||||
})
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
async fn close(self) {
|
||||
self.session.close(v1::CloseCode::Normal, "");
|
||||
within("the session to close", self.session.closed()).await;
|
||||
}
|
||||
}
|
||||
|
||||
// ---- the conformance suite ----------------------------------------------------
|
||||
|
||||
/// What a case is expected to do against a TeamSpeak session, and why.
|
||||
enum Expect {
|
||||
/// Every assertion of the case holds.
|
||||
Passes,
|
||||
/// The session lacks the feature the case needs (`Verdict::Skipped`).
|
||||
Skipped(&'static str),
|
||||
/// The case does not apply: it cannot run, or cannot pass, for this reason
|
||||
/// (`cases_that_do_not_apply_fail` runs them and watches them fail).
|
||||
NotRun(&'static str),
|
||||
}
|
||||
use Expect::{NotRun, Passes, Skipped};
|
||||
|
||||
/// Every case of the suite of the protocol repository at `c5bb6b9`, in its
|
||||
/// order, with what a TeamSpeak session does with it. A case the suite gains
|
||||
/// fails `the_suite_is_known` until it is listed here.
|
||||
///
|
||||
/// The suite is written for a backend that is a `FakeHost`. A case that needs
|
||||
/// the backend gets the `FakeHandle` of an unrelated fake host, so the cases
|
||||
/// that hold, kill or read it, or push into it, cannot run against a session of
|
||||
/// a TeamSpeak server; the others write to places a TeamSpeak server does not
|
||||
/// have (the suite's channels, a server with another id, `ScheduledEvent`,
|
||||
/// `Emoji`, attachments). Each reason is what the case did when it was run.
|
||||
const EXPECTED: [(&str, Expect); 17] = [
|
||||
("welcome_matches_features", Passes),
|
||||
(
|
||||
"subscribe_syncs_the_scope",
|
||||
NotRun("writes to channel 4001: rejected (NotFound) no such channel"),
|
||||
),
|
||||
(
|
||||
"subscribe_resumes_from_a_cursor",
|
||||
NotRun("writes to channel 4002: rejected (NotFound) no such channel"),
|
||||
),
|
||||
(
|
||||
"put_answers_entities_and_pushes_the_change_with_the_same_rev",
|
||||
NotRun("writes to channel 4003: rejected (NotFound) no such channel"),
|
||||
),
|
||||
(
|
||||
"delete_answers_an_ack_and_pushes_the_removal",
|
||||
NotRun(
|
||||
"writes to channel 4004 first (no such channel); and TeamSpeak cannot delete a message, \
|
||||
where the case needs only `chat`, not `chat.delete` (P8)",
|
||||
),
|
||||
),
|
||||
(
|
||||
"a_key_names_an_entity_without_its_server",
|
||||
NotRun(
|
||||
"rejected (NotFound) no such server; and it creates a ScheduledEvent and an Emoji, \
|
||||
which TeamSpeak lacks, though it needs no feature (P8)",
|
||||
),
|
||||
),
|
||||
("a_stale_rev_conflicts_and_a_patch_writes_only_its_paths", Skipped("chat.edit")),
|
||||
("requests_apply_in_the_order_they_were_issued", Skipped("chat.edit")),
|
||||
("list_pages_history", Skipped("chat.history")),
|
||||
(
|
||||
"cancel_before_apply_is_cancelled",
|
||||
NotRun("holds the unrelated fake host, so the request is answered while it \"holds\""),
|
||||
),
|
||||
("idempotency_keys_apply_a_put_once", Skipped("idempotency")),
|
||||
(
|
||||
"notifications_are_fire_and_forget",
|
||||
NotRun("reads the request log of the unrelated fake host: the notification never arrives"),
|
||||
),
|
||||
(
|
||||
"renew_account_follows_the_feature",
|
||||
NotRun("pushes a HostUpdate into the unrelated fake session's closed push channel"),
|
||||
),
|
||||
(
|
||||
"media_loops_back",
|
||||
NotRun(
|
||||
"a TeamSpeak server does not return a client's own voice: the packet never loops back",
|
||||
),
|
||||
),
|
||||
(
|
||||
"files_round_trip",
|
||||
NotRun(
|
||||
"writes an AttachmentSlot: rejected (Unsupported) attachments are not offered; \
|
||||
TeamSpeak has channel files, and the case needs `files`, not `chat.attachments` (P8)",
|
||||
),
|
||||
),
|
||||
("close_ends_the_session", Passes),
|
||||
(
|
||||
"the_backend_can_end_the_session",
|
||||
NotRun(
|
||||
"kills the unrelated fake session, so closed() of this one never resolves; and a \
|
||||
kick is Network(text), not Remote{KICKED}, until H1",
|
||||
),
|
||||
),
|
||||
];
|
||||
|
||||
/// A fixture on a TeamSpeak session. The suite wants a `FakeHandle` on the
|
||||
/// backend behind the session; a TeamSpeak server has none, so it gets the one
|
||||
/// of an unrelated fake host, which the cases that are run never touch.
|
||||
async fn fixture(dev: Dev) -> Fixture {
|
||||
let (session, pushes, media) =
|
||||
session(&dev, &VoiceOptions::new(dev.voice, dev.nick("conf"))).await;
|
||||
let unrelated = FakeConnector::new();
|
||||
let (params, _media) = voelin_proto::test_util::connect_params("fake://unrelated");
|
||||
unrelated.connect(params).await.expect("a fake session");
|
||||
let backend = unrelated.last_session().expect("a fake session");
|
||||
Fixture::new(session, pushes, media, backend)
|
||||
}
|
||||
|
||||
fn the_suite_is_known() {
|
||||
let known: Vec<_> = EXPECTED.iter().map(|(name, _)| *name).collect();
|
||||
let cases: Vec<_> = conformance::CASES.iter().map(|case| case.name).collect();
|
||||
assert_eq!(known, cases, "the suite changed: list the new cases in EXPECTED");
|
||||
}
|
||||
|
||||
/// The cases that apply run and pass, the ones that need a feature the session
|
||||
/// lacks are skipped, and the rest are not run (their reason is in
|
||||
/// [`EXPECTED`]).
|
||||
async fn conformance_subset(dev: Dev) {
|
||||
the_suite_is_known();
|
||||
let harness = move || fixture(dev);
|
||||
let (mut passed, mut skipped) = (0, 0);
|
||||
for (case, (name, expect)) in conformance::CASES.iter().zip(&EXPECTED) {
|
||||
match expect {
|
||||
Passes => {
|
||||
let verdict = conformance::run_case(&harness, case).await;
|
||||
assert_eq!(verdict, Verdict::Passed, "{name} on {}", dev.name);
|
||||
passed += 1;
|
||||
}
|
||||
Skipped(feature) => {
|
||||
let verdict = conformance::run_case(&harness, case).await;
|
||||
assert_eq!(verdict, Verdict::Skipped(feature), "{name} on {}", dev.name);
|
||||
skipped += 1;
|
||||
}
|
||||
NotRun(reason) => eprintln!("{} {name}: not run: {reason}", dev.name),
|
||||
}
|
||||
}
|
||||
assert_eq!((passed, skipped), (2, 4));
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn ts3_conformance_subset() {
|
||||
if live() {
|
||||
conformance_subset(TS3).await;
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn ts6_conformance_subset() {
|
||||
if live() {
|
||||
conformance_subset(TS6).await;
|
||||
}
|
||||
}
|
||||
|
||||
// ---- what the suite cannot reach ----------------------------------------------
|
||||
|
||||
/// A message in the own channel is answered with the message as written, and
|
||||
/// pushed to the CHAT scope of every session in the channel: to the other one
|
||||
/// as a `Change`, and back to ours (the ids agree only with the native
|
||||
/// session of H1: the answer has a local id, the echo the one of the
|
||||
/// `Change`).
|
||||
async fn chat_in_the_own_channel(dev: Dev) {
|
||||
let mut a = Client::connect(&dev, &dev.nick("chat-a")).await;
|
||||
let mut b = Client::connect(&dev, &dev.nick("chat-b")).await;
|
||||
assert_eq!(a.seat.channel_id, b.seat.channel_id, "both sessions are in the default channel");
|
||||
let channel = a.seat.channel_id;
|
||||
a.subscribe(scope(v1::ScopeKind::Chat, channel)).await;
|
||||
b.subscribe(scope(v1::ScopeKind::Chat, channel)).await;
|
||||
|
||||
let text = format!("live-chat-{}", std::process::id());
|
||||
let message = v1::Message { channel_id: channel, text: text.clone(), ..Default::default() };
|
||||
let write = v1::Write {
|
||||
entity: Some(v1::Entity { kind: Some(Kind::Message(message)) }),
|
||||
paths: Vec::new(),
|
||||
};
|
||||
let put = Op::Put(v1::Put { writes: vec![write], ..Default::default() });
|
||||
let Answer::Entities(answer) = a.ask(put).await.expect("the message is accepted") else {
|
||||
panic!("a message is answered with entities")
|
||||
};
|
||||
let written = match &answer.items[..] {
|
||||
[v1::Entity { kind: Some(Kind::Message(message)) }] => message.clone(),
|
||||
other => panic!("one message expected, got {other:?}"),
|
||||
};
|
||||
assert_eq!((written.channel_id, written.text.as_str()), (channel, text.as_str()));
|
||||
|
||||
let heard = b.message(channel, &text).await;
|
||||
assert_ne!(heard.id, 0);
|
||||
assert_eq!(heard.channel_id, channel);
|
||||
// And ours, back from the server: the same words, once.
|
||||
let echo = a.message(channel, &text).await;
|
||||
assert_ne!(echo.id, 0);
|
||||
a.close().await;
|
||||
b.close().await;
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn ts3_chat_in_the_own_channel() {
|
||||
if live() {
|
||||
chat_in_the_own_channel(TS3).await;
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn ts6_chat_in_the_own_channel() {
|
||||
if live() {
|
||||
chat_in_the_own_channel(TS6).await;
|
||||
}
|
||||
}
|
||||
|
||||
/// A move into a channel with a password or without room is refused with the
|
||||
/// code the seam names: `PASSWORD` and `FULL`.
|
||||
async fn refused_moves(dev: Dev) {
|
||||
use voelin_query::{Command as Query, QueryClient};
|
||||
let (admin, _) = QueryClient::connect(&dev.query()).await.expect("the query login");
|
||||
let tag = std::process::id() % 10_000;
|
||||
let create = |name: &str| {
|
||||
Query::new("channelcreate")
|
||||
.arg("channel_name", format!("{name}-{tag}"))
|
||||
.arg("channel_flag_semi_permanent", 1)
|
||||
};
|
||||
let locked =
|
||||
admin.send(&create("seam-locked").arg("channel_password", "secret")).await.unwrap()[0]
|
||||
.parse::<u64>("cid")
|
||||
.unwrap();
|
||||
let full = create("seam-full")
|
||||
.arg("channel_maxclients", 0)
|
||||
.arg("channel_flag_maxclients_unlimited", 0);
|
||||
let full = admin.send(&full).await.unwrap()[0].parse::<u64>("cid").unwrap();
|
||||
// A key for the Normal group, which has to keep to passwords and limits.
|
||||
let token = group_token(&admin, "Normal").await;
|
||||
|
||||
let check = {
|
||||
let token = token.clone();
|
||||
tokio::spawn(async move {
|
||||
let mut options = VoiceOptions::new(dev.voice, dev.nick("moves"));
|
||||
options.token = Some(token);
|
||||
let client = Client::connect_with(&dev, options).await;
|
||||
let code = |result: Result<v1::VoiceState, SessionError>| match result {
|
||||
Err(SessionError::Rejected(error)) => error.code(),
|
||||
other => panic!("expected a refusal, got {other:?}"),
|
||||
};
|
||||
assert_eq!(code(client.join(locked, "").await), v1::ErrorCode::Password);
|
||||
assert_eq!(code(client.join(locked, "wrong").await), v1::ErrorCode::Password);
|
||||
let seat = client.join(locked, "secret").await.expect("the right password");
|
||||
assert_eq!(seat.channel_id, locked);
|
||||
assert_eq!(code(client.join(full, "").await), v1::ErrorCode::Full);
|
||||
client.close().await;
|
||||
})
|
||||
};
|
||||
let result = check.await;
|
||||
// Clean up before reporting a failure; the key is gone once used.
|
||||
let _ = admin.send(&Query::new("privilegekeydelete").arg("token", &token)).await;
|
||||
for cid in [locked, full] {
|
||||
admin.send(&Query::new("channeldelete").arg("cid", cid).arg("force", 1)).await.unwrap();
|
||||
}
|
||||
if let Err(error) = result {
|
||||
std::panic::resume_unwind(error.into_panic());
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn ts3_refused_moves() {
|
||||
if live() {
|
||||
refused_moves(TS3).await;
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn ts6_refused_moves() {
|
||||
if live() {
|
||||
refused_moves(TS6).await;
|
||||
}
|
||||
}
|
||||
|
||||
/// A poke is a `Signal` to a participant: the other session gets it, with
|
||||
/// the participant and the words of the sender.
|
||||
async fn poke_between_sessions(dev: Dev) {
|
||||
let a = Client::connect(&dev, &dev.nick("poke-a")).await;
|
||||
let mut b = Client::connect(&dev, &dev.nick("poke-b")).await;
|
||||
let text = format!("live-poke-{}", std::process::id());
|
||||
let target = v1::SignalTarget {
|
||||
server_id: a.server,
|
||||
participant_id: b.seat.participant_id,
|
||||
..Default::default()
|
||||
};
|
||||
let signal = v1::Signal {
|
||||
to: Some(target),
|
||||
body: Some(v1::signal::Body::Poke(v1::Poke { message: text.clone() })),
|
||||
..Default::default()
|
||||
};
|
||||
a.ask(Op::Signal(signal)).await.expect("the poke is accepted");
|
||||
let from = b
|
||||
.until("the poke", |push| match &push.body {
|
||||
Some(v1::push::Body::Signal(signal)) => match &signal.body {
|
||||
Some(v1::signal::Body::Poke(poke)) if poke.message == text => {
|
||||
Some(signal.from_participant)
|
||||
}
|
||||
_ => None,
|
||||
},
|
||||
_ => None,
|
||||
})
|
||||
.await;
|
||||
assert_eq!(from, a.seat.participant_id);
|
||||
a.close().await;
|
||||
b.close().await;
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn ts3_poke_between_sessions() {
|
||||
if live() {
|
||||
poke_between_sessions(TS3).await;
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn ts6_poke_between_sessions() {
|
||||
if live() {
|
||||
poke_between_sessions(TS6).await;
|
||||
}
|
||||
}
|
||||
|
||||
/// One frame of Opus (20 ms, mono, fullband).
|
||||
const OPUS: [u8; 3] = [0xf8, 0xff, 0xfe];
|
||||
|
||||
fn rtp(flow: FlowId, sequence: u16, marker: bool, payload: &[u8]) -> MediaPacket {
|
||||
let mut header = RtpHeader::new(PT_OPUS, sequence, u32::from(sequence) * 960);
|
||||
header.marker = marker;
|
||||
let mut out = bytes::BytesMut::new();
|
||||
header.write(flow, &mut out).expect("a header");
|
||||
out.extend_from_slice(payload);
|
||||
MediaPacket { flow, rtp: out.freeze() }
|
||||
}
|
||||
|
||||
/// Voice sent on our slot arrives on the sender's slot at the other session's
|
||||
/// media sink: the frames in order (the sequence is TeamSpeak's packet id, so
|
||||
/// it only has to count up), the marker on the first, and an empty payload at
|
||||
/// the end.
|
||||
async fn voice_between_sessions(dev: Dev) {
|
||||
let a = Client::connect(&dev, &dev.nick("voice-a")).await;
|
||||
let mut b = Client::connect(&dev, &dev.nick("voice-b")).await;
|
||||
assert_eq!(a.seat.channel_id, b.seat.channel_id);
|
||||
let flow = FlowId::new(a.seat.slot, voice_sub::CHANNEL);
|
||||
for n in 0..5u8 {
|
||||
let frame = [0xf8, 0xff, 0xfe, n];
|
||||
let packet = rtp(flow, u16::from(n), n == 0, &frame);
|
||||
a.session.send_media(MediaClass::Voice, packet).expect("our own slot");
|
||||
tokio::time::sleep(Duration::from_millis(20)).await;
|
||||
}
|
||||
a.session.send_media(MediaClass::Voice, rtp(flow, 5, false, &[])).expect("the end");
|
||||
|
||||
let mut heard = Vec::new();
|
||||
while let Some(packet) = b.media.recv_within(Duration::from_secs(5)).await {
|
||||
let view = RtpView::parse(&packet.rtp).expect("RTP");
|
||||
heard.push((packet.flow, view.sequence(), view.marker(), view.payload().to_vec()));
|
||||
if view.payload().is_empty() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
assert!(heard.len() >= 2, "{heard:?}");
|
||||
assert!(heard.iter().all(|(heard_flow, ..)| *heard_flow == flow), "{heard:?}");
|
||||
let (_, _, first_marker, first_payload) = &heard[0];
|
||||
assert!(*first_marker, "the first packet of the spurt carries the marker: {heard:?}");
|
||||
assert_eq!(&first_payload[..3], &OPUS[..], "{heard:?}");
|
||||
let (end_flow, _, end_marker, end_payload) = heard.last().expect("an end");
|
||||
assert!(
|
||||
end_payload.is_empty() && !*end_marker,
|
||||
"the spurt ends with an empty payload: {heard:?}"
|
||||
);
|
||||
assert_eq!(*end_flow, flow);
|
||||
let sequences: Vec<_> = heard.iter().map(|(_, sequence, ..)| *sequence).collect();
|
||||
assert!(
|
||||
sequences.windows(2).all(|pair| pair[1] == pair[0].wrapping_add(1)),
|
||||
"the sequence counts up by one: {sequences:?}"
|
||||
);
|
||||
// Voice on a slot that is not ours is refused before it reaches the server.
|
||||
let other = FlowId::new(a.seat.slot + 1000, voice_sub::CHANNEL);
|
||||
assert!(a.session.send_media(MediaClass::Voice, rtp(other, 0, true, &OPUS)).is_err());
|
||||
a.close().await;
|
||||
b.close().await;
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn ts3_voice_between_sessions() {
|
||||
if live() {
|
||||
voice_between_sessions(TS3).await;
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn ts6_voice_between_sessions() {
|
||||
if live() {
|
||||
voice_between_sessions(TS6).await;
|
||||
}
|
||||
}
|
||||
|
||||
/// A channel file written with `write_file` and read back from an offset with
|
||||
/// `read_file`: the head names the file and its size, the body starts where
|
||||
/// the offset says.
|
||||
async fn channel_file_from_an_offset(dev: Dev) {
|
||||
use voelin_query::{Command as Query, QueryClient};
|
||||
// Guests may not upload: a key for the Server Admin group.
|
||||
let (admin, _) = QueryClient::connect(&dev.query()).await.expect("the query login");
|
||||
let token = group_token(&admin, "Server Admin").await;
|
||||
let check = tokio::spawn({
|
||||
let token = token.clone();
|
||||
async move { channel_file_with_a_key(dev, token).await }
|
||||
});
|
||||
let result = check.await;
|
||||
let _ = admin.send(&Query::new("privilegekeydelete").arg("token", &token)).await;
|
||||
if let Err(error) = result {
|
||||
std::panic::resume_unwind(error.into_panic());
|
||||
}
|
||||
}
|
||||
|
||||
/// A one-time key for the server group `name` (a template group, type 1).
|
||||
async fn group_token(admin: &voelin_query::QueryClient, name: &str) -> String {
|
||||
use voelin_query::Command as Query;
|
||||
let groups = admin.send(&Query::new("servergrouplist")).await.unwrap();
|
||||
let group = groups
|
||||
.iter()
|
||||
.find(|g| g.get("name") == Some(name) && g.get("type") == Some("1"))
|
||||
.and_then(|g| g.parse::<u64>("sgid"))
|
||||
.unwrap_or_else(|| panic!("a {name} server group"));
|
||||
let key =
|
||||
Query::new("privilegekeyadd").arg("tokentype", 0).arg("tokenid1", group).arg("tokenid2", 0);
|
||||
admin.send(&key).await.unwrap()[0].get("token").unwrap().to_owned()
|
||||
}
|
||||
|
||||
async fn channel_file_with_a_key(dev: Dev, token: String) {
|
||||
let mut options = VoiceOptions::new(dev.voice, dev.nick("files"));
|
||||
options.token = Some(token);
|
||||
let a = Client::connect_with(&dev, options).await;
|
||||
let channel = a.seat.channel_id;
|
||||
let name = format!("seam-{}.bin", std::process::id());
|
||||
let path = format!("/{name}");
|
||||
let data: Vec<u8> = (0..3_000usize).map(|i| (i * 7 % 251) as u8).collect();
|
||||
let target = v1::FilePath { channel_id: channel, path: path.clone(), password: String::new() };
|
||||
|
||||
let write = v1::FileWrite {
|
||||
target: Some(v1::file_write::Target::Path(target.clone())),
|
||||
size: data.len() as u64,
|
||||
offset: 0,
|
||||
overwrite: true,
|
||||
sha256: Default::default(),
|
||||
};
|
||||
let mut upload =
|
||||
within("the upload to open", a.session.write_file(write)).await.expect("an upload");
|
||||
upload.body.write_all(&data).await.expect("the body");
|
||||
upload.body.shutdown().await.expect("the end of the body");
|
||||
let stored = within("the server to keep it", upload.done).await.expect("the file is stored");
|
||||
assert!(
|
||||
stored.items.iter().any(|e| matches!(&e.kind, Some(Kind::File(f)) if f.name == name)),
|
||||
"{stored:?}"
|
||||
);
|
||||
|
||||
let read = v1::FileRead {
|
||||
target: Some(v1::file_read::Target::Path(target.clone())),
|
||||
offset: 1_000,
|
||||
length: 0,
|
||||
};
|
||||
let mut download =
|
||||
within("the download to open", a.session.read_file(read)).await.expect("a download");
|
||||
let size = download.head.items.iter().find_map(|e| match &e.kind {
|
||||
Some(Kind::File(file)) => Some(file.size),
|
||||
_ => None,
|
||||
});
|
||||
assert_eq!(size, Some(3_000), "{:?}", download.head);
|
||||
let mut body = Vec::new();
|
||||
within("the body", download.body.read_to_end(&mut body)).await.expect("the body");
|
||||
assert_eq!(body, data[1_000..], "the body starts at the offset");
|
||||
|
||||
// Clean up what we put on the server.
|
||||
let key = v1::FileEntry { channel_id: channel, path: "/".into(), name, ..Default::default() };
|
||||
let delete = Op::Delete(v1::Delete {
|
||||
keys: vec![v1::Entity { kind: Some(Kind::File(key)) }],
|
||||
..Default::default()
|
||||
});
|
||||
let _ = a.ask(delete).await;
|
||||
a.close().await;
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn ts3_channel_file_from_an_offset() {
|
||||
if live() {
|
||||
channel_file_from_an_offset(TS3).await;
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn ts6_channel_file_from_an_offset() {
|
||||
if live() {
|
||||
channel_file_from_an_offset(TS6).await;
|
||||
}
|
||||
}
|
||||
|
||||
// ---- the cases that do not apply ----------------------------------------------
|
||||
|
||||
/// The cases of [`EXPECTED`] that do not apply fail against a session of a
|
||||
/// TeamSpeak server, each with a panic of its own (its first line is printed):
|
||||
/// the reasons of the table are what they did when they were run. A case that
|
||||
/// passes one day (with the native session of H1) is to be moved to `Passes`.
|
||||
///
|
||||
/// Ignored by default: the cases that wait for a backend that is not there
|
||||
/// take their three seconds each.
|
||||
async fn cases_that_do_not_apply_fail(dev: Dev) {
|
||||
// A case the suite gained is not in `EXPECTED`, and the zip below would leave
|
||||
// it out without a word.
|
||||
the_suite_is_known();
|
||||
for (case, (name, expect)) in conformance::CASES.iter().zip(&EXPECTED) {
|
||||
let NotRun(reason) = expect else { continue };
|
||||
let harness = move || async move {
|
||||
let mut fixture = fixture(dev).await;
|
||||
fixture.step = Duration::from_secs(3);
|
||||
fixture
|
||||
};
|
||||
match tokio::spawn(async move { conformance::run_case(&harness, case).await }).await {
|
||||
Err(error) if error.is_panic() => {
|
||||
let payload = error.into_panic();
|
||||
let message = payload
|
||||
.downcast_ref::<String>()
|
||||
.cloned()
|
||||
.or_else(|| payload.downcast_ref::<&str>().map(|s| (*s).to_owned()))
|
||||
.unwrap_or_default();
|
||||
let first = message.lines().next().unwrap_or_default();
|
||||
eprintln!("{} {name}: failed as expected ({reason}): {first}", dev.name);
|
||||
}
|
||||
other => panic!("{name} on {} was expected to fail, and: {other:?}", dev.name),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
#[ignore = "runs the conformance cases that cannot pass and waits for their timeouts"]
|
||||
async fn ts3_cases_that_do_not_apply_fail() {
|
||||
if live() {
|
||||
cases_that_do_not_apply_fail(TS3).await;
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
#[ignore = "runs the conformance cases that cannot pass and waits for their timeouts"]
|
||||
async fn ts6_cases_that_do_not_apply_fail() {
|
||||
if live() {
|
||||
cases_that_do_not_apply_fail(TS6).await;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,245 @@
|
||||
//! Voice across the seam, TeamSpeak side (`docs/session-seam.md` section
|
||||
//! 6.2): TeamSpeak's Opus packets as RTP on the talker's slot, and RTP on our
|
||||
//! own slot as TeamSpeak's `EncodedVoice`. Nothing is transcoded
|
||||
//! (protocol section 1.2): the Opus payload is the same bytes both ways.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use bytes::BytesMut;
|
||||
use voelin_audio::{EncodedVoice, VoiceCodec, VoicePacket};
|
||||
use voelin_proto::link::{FlowId, MediaPacket, voice_sub};
|
||||
use voelin_proto::media::opus::{self, Toc};
|
||||
use voelin_proto::media::payload::{OPUS_20_MS_TICKS, OPUS_CLOCK_RATE, PT_OPUS};
|
||||
use voelin_proto::media::{RtpHeader, RtpView};
|
||||
|
||||
use super::entities::slot;
|
||||
|
||||
/// Silence this long between two packets of a talker starts a new talk spurt
|
||||
/// (the marker bit is set on the first packet of it).
|
||||
const SPURT_GAP: Duration = Duration::from_millis(250);
|
||||
|
||||
/// What is kept of the last packet of a talker.
|
||||
struct Talker {
|
||||
timestamp: u32,
|
||||
sequence: u16,
|
||||
at: Instant,
|
||||
/// The 48 kHz ticks the last packet spans.
|
||||
ticks: u32,
|
||||
/// The last packet ended the spurt.
|
||||
ended: bool,
|
||||
}
|
||||
|
||||
/// Wraps what a TeamSpeak connection receives into RTP.
|
||||
#[derive(Default)]
|
||||
pub(super) struct Downlink {
|
||||
talkers: HashMap<u16, Talker>,
|
||||
}
|
||||
|
||||
impl Downlink {
|
||||
/// `packet` as the RTP packet of its talker's slot. The sequence number is
|
||||
/// TeamSpeak's packet id (both 16 bits); the timestamp advances by each
|
||||
/// packet's duration (its Opus table-of-contents byte) on the packet id's
|
||||
/// counter, so it never goes back when the id wraps, and by wall-clock time
|
||||
/// across silences, so a silence is not compressed. The marker is set on
|
||||
/// the first packet after an end or a gap, and an end is an empty payload.
|
||||
pub(super) fn wrap(&mut self, packet: &VoicePacket, now: Instant) -> Option<MediaPacket> {
|
||||
let id = packet.talker.0;
|
||||
let sub = if packet.whisper { voice_sub::FIRST_TALK_TARGET } else { voice_sub::CHANNEL };
|
||||
let flow = FlowId::new(slot(id), sub);
|
||||
let end = packet.is_end();
|
||||
let (timestamp, marker) = match self.talkers.get(&id) {
|
||||
None => (0, !end),
|
||||
Some(last) => {
|
||||
let gap = now.saturating_duration_since(last.at);
|
||||
if last.ended || gap > SPURT_GAP {
|
||||
// A new spurt: the time that passed since the last packet.
|
||||
let wall = (gap.as_micros() * u128::from(OPUS_CLOCK_RATE) / 1_000_000) as u32;
|
||||
(last.timestamp.wrapping_add(last.ticks.max(wall)), !end)
|
||||
} else {
|
||||
let ahead = packet.seq.wrapping_sub(last.sequence);
|
||||
if ahead == 0 || ahead >= 0x8000 {
|
||||
// A duplicate or a late packet: where it belongs, and the
|
||||
// state keeps what the latest packet said.
|
||||
let back = u32::from(last.sequence.wrapping_sub(packet.seq));
|
||||
let at = last.timestamp.wrapping_sub(back * last.ticks);
|
||||
return self.finish(flow, packet, at, false);
|
||||
}
|
||||
(last.timestamp.wrapping_add(u32::from(ahead) * last.ticks), false)
|
||||
}
|
||||
}
|
||||
};
|
||||
let ticks =
|
||||
if end { 0 } else { opus::packet_ticks(&packet.payload).unwrap_or(OPUS_20_MS_TICKS) };
|
||||
self.talkers
|
||||
.insert(id, Talker { timestamp, sequence: packet.seq, at: now, ticks, ended: end });
|
||||
self.finish(flow, packet, timestamp, marker)
|
||||
}
|
||||
|
||||
fn finish(
|
||||
&self,
|
||||
flow: FlowId,
|
||||
packet: &VoicePacket,
|
||||
timestamp: u32,
|
||||
marker: bool,
|
||||
) -> Option<MediaPacket> {
|
||||
let mut header = RtpHeader::new(PT_OPUS, packet.seq, timestamp);
|
||||
header.marker = marker;
|
||||
// An end is an empty payload, also where the server sent one byte.
|
||||
let payload = if packet.is_end() { &[][..] } else { &packet.payload[..] };
|
||||
let mut out = BytesMut::with_capacity(header.encoded_len() + payload.len());
|
||||
header.write(flow, &mut out).ok()?;
|
||||
out.extend_from_slice(payload);
|
||||
Some(MediaPacket { flow, rtp: out.freeze() })
|
||||
}
|
||||
|
||||
/// Forget a talker (it left the server).
|
||||
pub(super) fn forget(&mut self, client: u16) {
|
||||
self.talkers.remove(&client);
|
||||
}
|
||||
}
|
||||
|
||||
/// The voice a media packet of our own slot carries, for TeamSpeak: its
|
||||
/// payload, and `Music` when the Opus packet is stereo. `None` for a packet
|
||||
/// that is no RTP.
|
||||
pub(super) fn uplink(packet: &MediaPacket) -> Option<EncodedVoice> {
|
||||
let view = RtpView::parse(&packet.rtp).ok()?;
|
||||
let payload = view.payload();
|
||||
let codec = match Toc::parse(payload) {
|
||||
Ok(toc) if toc.stereo() => VoiceCodec::Music,
|
||||
_ => VoiceCodec::Voice,
|
||||
};
|
||||
Some(EncodedVoice { codec, payload: payload.to_vec() })
|
||||
}
|
||||
|
||||
/// An RTP packet of voice, for tests of both sides.
|
||||
#[cfg(test)]
|
||||
pub(super) fn rtp_packet(
|
||||
flow: FlowId,
|
||||
sequence: u16,
|
||||
timestamp: u32,
|
||||
marker: bool,
|
||||
payload: &[u8],
|
||||
) -> bytes::Bytes {
|
||||
let mut header = RtpHeader::new(PT_OPUS, sequence, timestamp);
|
||||
header.marker = marker;
|
||||
let mut out = BytesMut::new();
|
||||
header.write(flow, &mut out).unwrap();
|
||||
out.extend_from_slice(payload);
|
||||
out.freeze()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use bytes::Bytes;
|
||||
use voelin_audio::TalkerId;
|
||||
|
||||
use super::*;
|
||||
|
||||
fn voice(talker: u16, seq: u16, payload: &[u8], whisper: bool) -> VoicePacket {
|
||||
VoicePacket {
|
||||
talker: TalkerId(talker),
|
||||
seq,
|
||||
codec: VoiceCodec::Voice,
|
||||
whisper,
|
||||
payload: payload.to_vec(),
|
||||
}
|
||||
}
|
||||
|
||||
/// An Opus packet of 20 ms in a CELT-only frame (config 16 is 2.5 ms; 19
|
||||
/// is 20 ms), mono, one frame.
|
||||
const OPUS_20_MS: [u8; 3] = [0x98, 0x01, 0x02];
|
||||
|
||||
fn view(packet: &MediaPacket) -> RtpView<'_> {
|
||||
RtpView::parse(&packet.rtp).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_spurt_is_sequenced_by_the_packet_id_with_a_marker_on_its_first_packet() {
|
||||
let mut down = Downlink::default();
|
||||
let t0 = Instant::now();
|
||||
let first = down.wrap(&voice(7, 65_534, &OPUS_20_MS, false), t0).unwrap();
|
||||
let v = view(&first);
|
||||
assert!(v.marker());
|
||||
assert_eq!((v.ssrc(), first.flow), (FlowId::new(8, 0).0, FlowId::new(8, 0)));
|
||||
assert_eq!((v.sequence(), v.timestamp()), (65_534, 0));
|
||||
// The id wraps; the timestamp keeps counting.
|
||||
let t1 = t0 + Duration::from_millis(20);
|
||||
let second = down.wrap(&voice(7, 65_535, &OPUS_20_MS, false), t1).unwrap();
|
||||
let third =
|
||||
down.wrap(&voice(7, 0, &OPUS_20_MS, false), t1 + Duration::from_millis(20)).unwrap();
|
||||
assert!(!view(&second).marker() && !view(&third).marker());
|
||||
assert_eq!(view(&second).timestamp(), OPUS_20_MS_TICKS);
|
||||
assert_eq!((view(&third).sequence(), view(&third).timestamp()), (0, 2 * OPUS_20_MS_TICKS));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_end_is_an_empty_payload_and_the_next_packet_has_a_marker() {
|
||||
let mut down = Downlink::default();
|
||||
let t0 = Instant::now();
|
||||
down.wrap(&voice(7, 1, &OPUS_20_MS, false), t0).unwrap();
|
||||
let end = down.wrap(&voice(7, 2, &[], false), t0 + Duration::from_millis(20)).unwrap();
|
||||
assert!(view(&end).payload().is_empty() && !view(&end).marker());
|
||||
// TeamSpeak's single byte after a talk is an end too.
|
||||
let mut down = Downlink::default();
|
||||
down.wrap(&voice(7, 1, &OPUS_20_MS, false), t0).unwrap();
|
||||
let end = down.wrap(&voice(7, 2, &[0], false), t0 + Duration::from_millis(20)).unwrap();
|
||||
assert!(view(&end).payload().is_empty());
|
||||
let next =
|
||||
down.wrap(&voice(7, 3, &OPUS_20_MS, false), t0 + Duration::from_millis(60)).unwrap();
|
||||
assert!(view(&next).marker());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_silence_is_not_compressed() {
|
||||
let mut down = Downlink::default();
|
||||
let t0 = Instant::now();
|
||||
let first = down.wrap(&voice(7, 1, &OPUS_20_MS, false), t0).unwrap();
|
||||
let again =
|
||||
down.wrap(&voice(7, 2, &OPUS_20_MS, false), t0 + Duration::from_secs(2)).unwrap();
|
||||
assert!(view(&again).marker(), "a gap starts a spurt");
|
||||
// Two seconds of wall-clock time are 96,000 ticks of the 48 kHz clock.
|
||||
assert_eq!(view(&again).timestamp() - view(&first).timestamp(), 96_000);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn whispers_ride_sub_flow_1_and_talkers_have_slots_of_their_own() {
|
||||
let mut down = Downlink::default();
|
||||
let now = Instant::now();
|
||||
let whisper = down.wrap(&voice(300, 1, &OPUS_20_MS, true), now).unwrap();
|
||||
assert_eq!((whisper.flow.slot(), whisper.flow.sub()), (301, 1));
|
||||
let channel = down.wrap(&voice(300, 2, &OPUS_20_MS, false), now).unwrap();
|
||||
assert_eq!((channel.flow.slot(), channel.flow.sub()), (301, 0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_packet_that_is_not_in_order_keeps_the_state_of_the_latest() {
|
||||
let mut down = Downlink::default();
|
||||
let t0 = Instant::now();
|
||||
down.wrap(&voice(7, 10, &OPUS_20_MS, false), t0).unwrap();
|
||||
down.wrap(&voice(7, 11, &OPUS_20_MS, false), t0 + Duration::from_millis(20)).unwrap();
|
||||
let late =
|
||||
down.wrap(&voice(7, 10, &OPUS_20_MS, false), t0 + Duration::from_millis(25)).unwrap();
|
||||
assert_eq!(view(&late).timestamp(), 0, "where packet 10 belongs");
|
||||
let next =
|
||||
down.wrap(&voice(7, 12, &OPUS_20_MS, false), t0 + Duration::from_millis(40)).unwrap();
|
||||
assert_eq!(view(&next).timestamp(), 2 * OPUS_20_MS_TICKS);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn our_voice_loses_its_header_and_stereo_is_music() {
|
||||
let flow = FlowId::new(8, 0);
|
||||
let mono = MediaPacket { flow, rtp: rtp_packet(flow, 0, 0, true, &OPUS_20_MS) };
|
||||
let voice = uplink(&mono).unwrap();
|
||||
assert_eq!((voice.codec, voice.payload.as_slice()), (VoiceCodec::Voice, &OPUS_20_MS[..]));
|
||||
// The same TOC with the stereo bit.
|
||||
let stereo_toc = [OPUS_20_MS[0] | 0x04, 1, 2];
|
||||
let stereo = MediaPacket { flow, rtp: rtp_packet(flow, 1, 960, false, &stereo_toc) };
|
||||
assert_eq!(uplink(&stereo).unwrap().codec, VoiceCodec::Music);
|
||||
// The end of a spurt: an empty payload.
|
||||
let end = MediaPacket { flow, rtp: rtp_packet(flow, 2, 1920, false, &[]) };
|
||||
assert!(uplink(&end).unwrap().is_end());
|
||||
// Not RTP.
|
||||
assert!(uplink(&MediaPacket { flow, rtp: Bytes::from_static(&[1, 2, 3]) }).is_none());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,887 @@
|
||||
//! A TeamSpeak connection as a `voelin_proto::link::Session`
|
||||
//! (`docs/session-seam.md`, "the TeamSpeak side").
|
||||
//!
|
||||
//! [`LinkSession`] is a `Session` over any [`ServerLink`]:
|
||||
//! it turns the link's `LinkCmd`s and `LinkEvent`s (the client's older,
|
||||
//! TeamSpeak-shaped vocabulary) into v1 entities, pushes and answers. With
|
||||
//! `TsLink` inside it is the in-process TeamSpeak `Session`; with a fake link
|
||||
//! inside it is what the link tests of the engine run through. [`TsConnector`]
|
||||
//! is the `Connector` that makes them for `ts3server://` and `teamspeak://`
|
||||
//! addresses.
|
||||
//!
|
||||
//! This module and the files it is made of are TeamSpeak's: they keep the
|
||||
//! TeamSpeak types (`tsclientlib`'s identity and client version) in
|
||||
//! [`inner_options`], the reverse of what the engine's `connect_params` wrote,
|
||||
//! and everything else is v1 and the client's own model. In the second half
|
||||
//! of the decoupling plan they move, with `TsLink`, to the TeamSpeak gateway
|
||||
//! (`voelin-gateway-ts` of VoelinGateWay).
|
||||
|
||||
mod driver;
|
||||
pub(crate) mod entities;
|
||||
pub(crate) mod ids;
|
||||
#[cfg(test)]
|
||||
mod live_tests;
|
||||
mod media;
|
||||
|
||||
use std::pin::Pin;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicU32, AtomicU64, Ordering};
|
||||
use std::task::{Context, Poll};
|
||||
use std::time::Duration;
|
||||
|
||||
use base64::Engine as _;
|
||||
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
|
||||
use bytes::Bytes;
|
||||
use tokio::io::{AsyncReadExt, AsyncWrite};
|
||||
use tokio::sync::{broadcast, mpsc, oneshot, watch};
|
||||
use voelin_model::{Link, ServerDetails};
|
||||
use voelin_proto::link::{
|
||||
BoxFuture, CloseReason, ConnectParams, Connected, Connector, Credential, Download, Features,
|
||||
LinkStats, MAX_RTP, MediaClass, MediaError, MediaPacket, Placement, Sent, Session,
|
||||
SessionError, Upload, placement, voice_sub,
|
||||
};
|
||||
use voelin_proto::v1::{self, response::Result as Answer};
|
||||
|
||||
use self::driver::{Cmd, Config, Driver, Parts, rejected};
|
||||
use super::{ConnectOptions, ServerLink, TsLink, identity, versions};
|
||||
use crate::BackendInfo;
|
||||
use crate::link::{
|
||||
BoxDuplex, LinkCmd, LinkCtx, LinkEvent, LocalConnected, LocalConnector, LocalCtx, StreamPort,
|
||||
VERSION_PARAM,
|
||||
};
|
||||
|
||||
/// The `Credential::Foreign` kind of a stored TeamSpeak identity.
|
||||
const IDENTITY_KIND: &str = voelin_identity::KIND_TEAMSPEAK;
|
||||
/// How long the link may take to report its first snapshot after it said it
|
||||
/// is connected; the snapshot gives the `Welcome` its own user.
|
||||
const FIRST_SNAPSHOT: Duration = Duration::from_millis(250);
|
||||
|
||||
static SESSIONS: AtomicU64 = AtomicU64::new(1);
|
||||
|
||||
fn now_ms() -> i64 {
|
||||
std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.map(|d| d.as_millis() as i64)
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
// ---- what the engine hands a connector ------------------------------------
|
||||
|
||||
/// The options a TeamSpeak link is connected with: the reverse of
|
||||
/// `link::connect_params`. A client version spec that [`versions::resolve`]
|
||||
/// refuses fails the connect, in words.
|
||||
fn inner_options(params: &ConnectParams, ctx: &LocalCtx) -> Result<ConnectOptions, SessionError> {
|
||||
let link = match Link::parse(¶ms.address) {
|
||||
Some(Link::Server(link)) => link,
|
||||
_ => {
|
||||
// Without the query: a channel password rides in it.
|
||||
let shown = crate::link::without_query(¶ms.address);
|
||||
return Err(SessionError::Protocol(format!("not a TeamSpeak server address: {shown}")));
|
||||
}
|
||||
};
|
||||
let identity = match ¶ms.credential {
|
||||
Credential::Foreign { kind: IDENTITY_KIND, blob } if blob.is_empty() => None,
|
||||
Credential::Foreign { kind: IDENTITY_KIND, blob } => {
|
||||
// The refusal never quotes the JSON: it holds the private key, and the
|
||||
// JSON reader's own message would show a key that does not import.
|
||||
let json = std::str::from_utf8(blob).map_err(|_| {
|
||||
SessionError::Protocol(
|
||||
"the TeamSpeak identity cannot be read: it is not text".into(),
|
||||
)
|
||||
})?;
|
||||
Some(identity::from_json(json).map_err(|e| SessionError::Protocol(e.to_string()))?)
|
||||
}
|
||||
_ => {
|
||||
return Err(SessionError::Protocol(
|
||||
"a TeamSpeak server needs a TeamSpeak identity".into(),
|
||||
));
|
||||
}
|
||||
};
|
||||
let spec = params
|
||||
.address
|
||||
.split_once('?')
|
||||
.and_then(|(_, query)| {
|
||||
query.split('&').find_map(|pair| pair.strip_prefix(&format!("{VERSION_PARAM}=")))
|
||||
})
|
||||
.map(|text| {
|
||||
URL_SAFE_NO_PAD
|
||||
.decode(text)
|
||||
.ok()
|
||||
.and_then(|bytes| String::from_utf8(bytes).ok())
|
||||
.ok_or_else(|| SessionError::Protocol("the client version cannot be read".into()))
|
||||
})
|
||||
.transpose()?;
|
||||
let client_version = match spec {
|
||||
None => None,
|
||||
Some(spec) => versions::resolve(&spec).map_err(|e| {
|
||||
SessionError::Protocol(format!("invalid client compatibility version: {e}"))
|
||||
})?,
|
||||
};
|
||||
let nonempty = |text: &str| (!text.is_empty()).then(|| text.to_owned());
|
||||
Ok(ConnectOptions {
|
||||
address: link.address(),
|
||||
nickname: nonempty(¶ms.hello.nickname).or(link.nickname.clone()).unwrap_or_default(),
|
||||
identity,
|
||||
client_version,
|
||||
server_password: nonempty(¶ms.hello.password).or(link.password.clone()),
|
||||
channel: link.channel.clone(),
|
||||
channel_password: link.channel_password.clone(),
|
||||
token: nonempty(¶ms.hello.invite_code).or(link.token.clone()),
|
||||
audio: ctx.audio,
|
||||
stream_peer: ctx.stream_peer.clone(),
|
||||
})
|
||||
}
|
||||
|
||||
// ---- backend and features ---------------------------------------------------
|
||||
|
||||
/// The server software as v1 names it (table 4.7): `teamspeak` with the
|
||||
/// flavor `ts3` or `ts6`; what is not a TeamSpeak product as it is.
|
||||
pub(crate) fn backend_to_v1(backend: &BackendInfo) -> v1::BackendInfo {
|
||||
let (product, flavor) = match backend.product.as_str() {
|
||||
"TeamSpeak 3" => ("teamspeak", "ts3"),
|
||||
"TeamSpeak 6" => ("teamspeak", "ts6"),
|
||||
// A TeamSpeak server the engine does not recognise: the version it
|
||||
// sent, no flavor.
|
||||
"" => ("teamspeak", ""),
|
||||
other => (other, ""),
|
||||
};
|
||||
v1::BackendInfo {
|
||||
product: product.into(),
|
||||
version: backend.version.clone(),
|
||||
flavor: flavor.into(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The features a TeamSpeak connection offers, from what its link can do
|
||||
/// (`docs/session-seam.md` section 4.7).
|
||||
pub(crate) fn features_of(capabilities: &voelin_model::Capabilities) -> Vec<&'static str> {
|
||||
let mut features =
|
||||
vec!["voice", "chat", "chat.bbcode", "dm", "sync.delta", "roles", "roles.channel"];
|
||||
if capabilities.file_transfer {
|
||||
features.extend(["files", "files.upload"]);
|
||||
}
|
||||
if capabilities.offline_messages {
|
||||
features.push("mailbox");
|
||||
}
|
||||
if capabilities.streams {
|
||||
features.extend(["streams", "streams.p2p", "streams.audio", "streams.approval"]);
|
||||
}
|
||||
features
|
||||
}
|
||||
|
||||
// ---- the session ------------------------------------------------------------
|
||||
|
||||
/// A `Session` over a [`ServerLink`]: the TeamSpeak side of the seam.
|
||||
pub(crate) struct LinkSession {
|
||||
welcome: v1::Welcome,
|
||||
features: Features,
|
||||
cmds: mpsc::UnboundedSender<Cmd>,
|
||||
closed: watch::Receiver<Option<CloseReason>>,
|
||||
/// The media slot of our client; the driver changes it when we are another
|
||||
/// client after TeamSpeak's own reconnect.
|
||||
own_slot: Arc<AtomicU32>,
|
||||
}
|
||||
|
||||
fn closed_reason(closed: &watch::Receiver<Option<CloseReason>>) -> CloseReason {
|
||||
closed.borrow().clone().unwrap_or_else(|| CloseReason::Network("the connection ended".into()))
|
||||
}
|
||||
|
||||
impl Session for LinkSession {
|
||||
fn welcome(&self) -> &v1::Welcome {
|
||||
&self.welcome
|
||||
}
|
||||
|
||||
fn features(&self) -> Features {
|
||||
self.features.clone()
|
||||
}
|
||||
|
||||
fn request(&self, op: v1::request::Op) -> BoxFuture<Result<Answer, SessionError>> {
|
||||
let closed = self.closed.clone();
|
||||
match placement(&op) {
|
||||
Placement::Invalid => {
|
||||
return Box::pin(async {
|
||||
Err(SessionError::Protocol("a Hello is part of connecting".into()))
|
||||
});
|
||||
}
|
||||
Placement::OwnStream
|
||||
if matches!(op, v1::request::Op::FileRead(_) | v1::request::Op::FileWrite(_)) =>
|
||||
{
|
||||
return Box::pin(async {
|
||||
Err(SessionError::Protocol("files go through read_file and write_file".into()))
|
||||
});
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
// Queued now, in the order of the calls, not when the future is polled.
|
||||
let (reply, answer) = oneshot::channel();
|
||||
if self.cmds.send(Cmd::Request { op, reply }).is_err() {
|
||||
return Box::pin(async move { Err(SessionError::Closed(closed_reason(&closed))) });
|
||||
}
|
||||
Box::pin(async move {
|
||||
match answer.await {
|
||||
Ok(answer) => answer,
|
||||
Err(_) => Err(SessionError::Closed(closed_reason(&closed))),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn notify(&self, op: v1::request::Op) -> Result<(), SessionError> {
|
||||
// Only an op of the control stream can go without an answer: a Hello is
|
||||
// part of connecting, and a List and the file transfers have streams
|
||||
// (and answers) of their own.
|
||||
match placement(&op) {
|
||||
Placement::Control => {}
|
||||
Placement::Invalid => {
|
||||
return Err(SessionError::Protocol("a Hello is part of connecting".into()));
|
||||
}
|
||||
Placement::OwnStream => {
|
||||
return Err(SessionError::Protocol(
|
||||
"a List and the file transfers have a stream and an answer of their own, \
|
||||
they cannot be sent without one"
|
||||
.into(),
|
||||
));
|
||||
}
|
||||
}
|
||||
// The task may be on its way out and not have dropped its queue yet.
|
||||
if self.closed.borrow().is_some() {
|
||||
return Err(SessionError::Closed(closed_reason(&self.closed)));
|
||||
}
|
||||
self.cmds
|
||||
.send(Cmd::Notify(op))
|
||||
.map_err(|_| SessionError::Closed(closed_reason(&self.closed)))
|
||||
}
|
||||
|
||||
fn read_file(&self, request: v1::FileRead) -> BoxFuture<Result<Download, SessionError>> {
|
||||
let closed = self.closed.clone();
|
||||
let (reply, answer) = oneshot::channel();
|
||||
if self.cmds.send(Cmd::Read { request, reply }).is_err() {
|
||||
return Box::pin(async move { Err(SessionError::Closed(closed_reason(&closed))) });
|
||||
}
|
||||
Box::pin(async move {
|
||||
match answer.await {
|
||||
Ok(answer) => answer,
|
||||
Err(_) => Err(SessionError::Closed(closed_reason(&closed))),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn write_file(&self, request: v1::FileWrite) -> BoxFuture<Result<Upload, SessionError>> {
|
||||
let closed = self.closed.clone();
|
||||
let (reply, answer) = oneshot::channel();
|
||||
if self.cmds.send(Cmd::Write { request, reply }).is_err() {
|
||||
return Box::pin(async move { Err(SessionError::Closed(closed_reason(&closed))) });
|
||||
}
|
||||
Box::pin(async move {
|
||||
match answer.await {
|
||||
Ok(answer) => answer,
|
||||
Err(_) => Err(SessionError::Closed(closed_reason(&closed))),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn send_media(&self, class: MediaClass, packet: MediaPacket) -> Result<Sent, MediaError> {
|
||||
let flow = packet.flow;
|
||||
if self.closed.borrow().is_some() {
|
||||
return Err(MediaError::Closed);
|
||||
}
|
||||
if packet.rtp.len() > MAX_RTP {
|
||||
return Err(MediaError::TooLarge { len: packet.rtp.len(), max: MAX_RTP });
|
||||
}
|
||||
// Only our voice to the channel: TeamSpeak whispers and priority voice,
|
||||
// like video, are not offered here.
|
||||
if class != MediaClass::Voice
|
||||
|| flow.slot() != self.own_slot.load(Ordering::Relaxed)
|
||||
|| flow.sub() != voice_sub::CHANNEL
|
||||
{
|
||||
return Err(MediaError::NotOwned(flow));
|
||||
}
|
||||
let voice = media::uplink(&packet).ok_or(MediaError::NotOwned(flow))?;
|
||||
self.cmds.send(Cmd::Audio(voice)).map_err(|_| MediaError::Closed)?;
|
||||
Ok(Sent::Queued)
|
||||
}
|
||||
|
||||
fn stats(&self) -> LinkStats {
|
||||
LinkStats { max_rtp: MAX_RTP, ..Default::default() }
|
||||
}
|
||||
|
||||
fn close(&self, code: v1::CloseCode, reason: &str) {
|
||||
let _ = self.cmds.send(Cmd::Close { code, reason: reason.to_owned() });
|
||||
}
|
||||
|
||||
fn closed(&self) -> BoxFuture<CloseReason> {
|
||||
let mut closed = self.closed.clone();
|
||||
Box::pin(async move {
|
||||
let reason = closed.wait_for(Option::is_some).await.ok().and_then(|r| r.clone());
|
||||
reason.unwrap_or_else(|| closed_reason(&closed))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// The write half of an upload: ending it tells the other half of the
|
||||
/// upload that the file is all there.
|
||||
struct UploadBody {
|
||||
inner: tokio::io::WriteHalf<BoxDuplex>,
|
||||
ended: Option<oneshot::Sender<()>>,
|
||||
}
|
||||
|
||||
impl AsyncWrite for UploadBody {
|
||||
fn poll_write(
|
||||
mut self: Pin<&mut Self>,
|
||||
cx: &mut Context<'_>,
|
||||
buf: &[u8],
|
||||
) -> Poll<std::io::Result<usize>> {
|
||||
Pin::new(&mut self.inner).poll_write(cx, buf)
|
||||
}
|
||||
|
||||
fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
|
||||
Pin::new(&mut self.inner).poll_flush(cx)
|
||||
}
|
||||
|
||||
fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
|
||||
let done = Pin::new(&mut self.inner).poll_shutdown(cx);
|
||||
if matches!(done, Poll::Ready(Ok(())))
|
||||
&& let Some(ended) = self.ended.take()
|
||||
{
|
||||
let _ = ended.send(());
|
||||
}
|
||||
done
|
||||
}
|
||||
}
|
||||
|
||||
/// An upload over the transfer connection `stream`: the body writes to it,
|
||||
/// and `done` resolves once the body is shut down and the server has closed
|
||||
/// the connection (or 30 s passed), with the file as `stored`.
|
||||
fn upload(stream: BoxDuplex, stored: v1::FileEntry) -> Upload {
|
||||
let (mut read, write) = tokio::io::split(stream);
|
||||
let (ended, shut) = oneshot::channel();
|
||||
let done: BoxFuture<Result<v1::Entities, SessionError>> = Box::pin(async move {
|
||||
if shut.await.is_err() {
|
||||
return Err(rejected(v1::ErrorCode::Cancelled, "the upload was dropped"));
|
||||
}
|
||||
// The server closes the connection once it has everything.
|
||||
let _ = tokio::time::timeout(Duration::from_secs(30), read.read(&mut [0u8; 1])).await;
|
||||
Ok(v1::Entities {
|
||||
items: vec![v1::Entity { kind: Some(v1::entity::Kind::File(stored)) }],
|
||||
..Default::default()
|
||||
})
|
||||
});
|
||||
Upload { body: Box::pin(UploadBody { inner: write, ended: Some(ended) }), done }
|
||||
}
|
||||
|
||||
// ---- the connector ----------------------------------------------------------
|
||||
|
||||
/// The `Connector` of a [`ServerLink`]: its sessions are [`LinkSession`]s.
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct LinkConnector {
|
||||
link: Arc<dyn ServerLink>,
|
||||
schemes: &'static [&'static str],
|
||||
/// Serves every scheme (the engine's tests give a link of their own).
|
||||
any: bool,
|
||||
}
|
||||
|
||||
impl LinkConnector {
|
||||
/// A connector for `schemes`.
|
||||
pub(crate) fn new(link: Arc<dyn ServerLink>, schemes: &'static [&'static str]) -> Self {
|
||||
Self { link, schemes, any: false }
|
||||
}
|
||||
|
||||
/// A connector for addresses of every scheme.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn any(link: Arc<dyn ServerLink>) -> Self {
|
||||
Self { link, schemes: &[], any: true }
|
||||
}
|
||||
}
|
||||
|
||||
impl Connector for LinkConnector {
|
||||
fn schemes(&self) -> &'static [&'static str] {
|
||||
self.schemes
|
||||
}
|
||||
|
||||
fn connect(&self, params: ConnectParams) -> BoxFuture<Result<Connected, SessionError>> {
|
||||
let connect = connect_link(self.link.clone(), params, LocalCtx::standalone());
|
||||
Box::pin(async move { Ok(connect.await?.connected) })
|
||||
}
|
||||
}
|
||||
|
||||
impl LocalConnector for LinkConnector {
|
||||
fn accepts(&self, scheme: &str) -> bool {
|
||||
self.any || self.schemes.contains(&scheme)
|
||||
}
|
||||
|
||||
fn connect_local(
|
||||
&self,
|
||||
params: ConnectParams,
|
||||
ctx: LocalCtx,
|
||||
) -> BoxFuture<Result<LocalConnected, SessionError>> {
|
||||
Box::pin(connect_link(self.link.clone(), params, ctx))
|
||||
}
|
||||
}
|
||||
|
||||
/// Connects to TeamSpeak 3 and 6 servers (`ts3server://` and `teamspeak://`)
|
||||
/// with `tsclientlib`: a `LinkSession` over a `TsLink` for every connection.
|
||||
///
|
||||
/// Clones share one account: the main myTeamSpeak account that every
|
||||
/// connection of the connector presents ([`TsConnector::set_myts_identity`],
|
||||
/// [`TsConnector::set_myts_data`]), also those made before it was set.
|
||||
/// Register a connector in the engine's registry with
|
||||
/// [`Backends::register_teamspeak`](crate::Backends::register_teamspeak) and
|
||||
/// keep a clone to set the account.
|
||||
#[derive(Clone)]
|
||||
pub struct TsConnector {
|
||||
connector: LinkConnector,
|
||||
link: Arc<TsLink>,
|
||||
}
|
||||
|
||||
impl Default for TsConnector {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl TsConnector {
|
||||
/// A connector that presents no account until it is given one.
|
||||
pub fn new() -> Self {
|
||||
let link = Arc::new(TsLink::new());
|
||||
Self { connector: LinkConnector::new(link.clone(), &["ts3server", "teamspeak"]), link }
|
||||
}
|
||||
|
||||
/// The main account's proof for every current and future connection of
|
||||
/// this connector (and its clones): a myTS ID signed with the account's
|
||||
/// key. Connections that are up show the server the new proof, and those
|
||||
/// that connect later present it from the start; `None` is a sign-out.
|
||||
pub fn set_myts_identity(&self, identity: Option<Arc<tsproto::myts::Identity>>) {
|
||||
self.link.account().set_identity(identity);
|
||||
}
|
||||
|
||||
/// What servers are shown of the main account: its avatar and badges with
|
||||
/// their certificates, its User Tag (TeamSpeak 6). It is sent to every
|
||||
/// connection that presents the account's myTS ID, once connected and when
|
||||
/// it changes; cleared on a sign-out (`None`).
|
||||
pub fn set_myts_data(&self, data: Option<Arc<tsclientlib::MytsData>>) {
|
||||
self.link.account().set_data(data);
|
||||
}
|
||||
}
|
||||
|
||||
impl Connector for TsConnector {
|
||||
fn schemes(&self) -> &'static [&'static str] {
|
||||
self.connector.schemes()
|
||||
}
|
||||
|
||||
fn connect(&self, params: ConnectParams) -> BoxFuture<Result<Connected, SessionError>> {
|
||||
self.connector.connect(params)
|
||||
}
|
||||
}
|
||||
|
||||
impl LocalConnector for TsConnector {
|
||||
fn connect_local(
|
||||
&self,
|
||||
params: ConnectParams,
|
||||
ctx: LocalCtx,
|
||||
) -> BoxFuture<Result<LocalConnected, SessionError>> {
|
||||
self.connector.connect_local(params, ctx)
|
||||
}
|
||||
}
|
||||
|
||||
/// What the link told when it connected.
|
||||
struct Joined {
|
||||
name: String,
|
||||
backend: BackendInfo,
|
||||
capabilities: voelin_model::Capabilities,
|
||||
own_client: u16,
|
||||
server_uid: String,
|
||||
own_uid: Option<String>,
|
||||
}
|
||||
|
||||
fn ended_error(reason: Option<String>) -> SessionError {
|
||||
SessionError::Closed(match reason {
|
||||
Some(reason) => CloseReason::Network(reason),
|
||||
None => CloseReason::Remote { code: v1::CloseCode::Normal as u64, reason: String::new() },
|
||||
})
|
||||
}
|
||||
|
||||
/// Wait for the link to say it is connected (or that it failed).
|
||||
async fn wait_connected(
|
||||
events: &mut mpsc::UnboundedReceiver<LinkEvent>,
|
||||
) -> Result<Joined, SessionError> {
|
||||
loop {
|
||||
match events.recv().await {
|
||||
Some(LinkEvent::Connected {
|
||||
name,
|
||||
backend,
|
||||
capabilities,
|
||||
own_client,
|
||||
server_uid,
|
||||
own_uid,
|
||||
}) => {
|
||||
return Ok(Joined { name, backend, capabilities, own_client, server_uid, own_uid });
|
||||
}
|
||||
Some(LinkEvent::Disconnected(reason)) => return Err(ended_error(reason)),
|
||||
Some(_) => {}
|
||||
None => return Err(ended_error(Some("the connection ended".into()))),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Open a [`LinkSession`] over `link` to the address in `params`.
|
||||
async fn connect_link(
|
||||
link: Arc<dyn ServerLink>,
|
||||
params: ConnectParams,
|
||||
ctx: LocalCtx,
|
||||
) -> Result<LocalConnected, SessionError> {
|
||||
let options = inner_options(¶ms, &ctx)?;
|
||||
let nickname = options.nickname.clone();
|
||||
let (inner_tx, inner_rx) = mpsc::unbounded_channel();
|
||||
let (events_tx, mut events) = mpsc::unbounded_channel();
|
||||
// The link answers requests on a bus of its own: this session reads the
|
||||
// answers, and passes on the rest to the engine's.
|
||||
let (bus_tx, bus) = broadcast::channel(4096);
|
||||
let inner_ctx = LinkCtx { events: bus_tx, ..ctx.link.clone() };
|
||||
link.spawn(options, inner_ctx, inner_rx, events_tx);
|
||||
|
||||
let joined = match tokio::time::timeout(params.timeout, wait_connected(&mut events)).await {
|
||||
Ok(joined) => joined?,
|
||||
Err(_) => {
|
||||
let _ = inner_tx.send(LinkCmd::Disconnect);
|
||||
return Err(SessionError::Timeout);
|
||||
}
|
||||
};
|
||||
// The link reports its first snapshot right after it says it is connected;
|
||||
// the session needs it to know the own user.
|
||||
let mut early: Vec<LinkEvent> = Vec::new();
|
||||
let _ = tokio::time::timeout(FIRST_SNAPSHOT, async {
|
||||
while let Some(event) = events.recv().await {
|
||||
let stop = matches!(event, LinkEvent::Presence(_) | LinkEvent::Disconnected(_));
|
||||
early.push(event);
|
||||
if stop {
|
||||
break;
|
||||
}
|
||||
}
|
||||
})
|
||||
.await;
|
||||
if let Some(LinkEvent::Disconnected(reason)) = early.last() {
|
||||
return Err(ended_error(reason.clone()));
|
||||
}
|
||||
let own_database_id = early.iter().find_map(|event| match event {
|
||||
LinkEvent::Presence(presence) => {
|
||||
presence.clients.get(&joined.own_client).and_then(|c| c.database_id)
|
||||
}
|
||||
_ => None,
|
||||
});
|
||||
|
||||
let ts6 = joined.backend.product == "TeamSpeak 6";
|
||||
let own_user =
|
||||
own_database_id.or_else(|| joined.own_uid.as_deref().map(ids::synthetic_user)).unwrap_or(0);
|
||||
let features = features_of(&joined.capabilities);
|
||||
let welcome = v1::Welcome {
|
||||
user_id: own_user,
|
||||
session_id: SESSIONS.fetch_add(1, Ordering::Relaxed),
|
||||
uid: joined.own_uid.as_deref().and_then(ids::uid_bytes).unwrap_or_default().into(),
|
||||
host: Some(v1::HostInfo {
|
||||
host_key: Bytes::new(),
|
||||
name: joined.name.clone(),
|
||||
product: joined.backend.product.clone(),
|
||||
version: joined.backend.version.clone(),
|
||||
backend: Some(backend_to_v1(&joined.backend)),
|
||||
icon: None,
|
||||
}),
|
||||
features: features.iter().map(|f| (*f).to_owned()).collect(),
|
||||
limits: Some(v1::Limits {
|
||||
max_message_chars: 1024,
|
||||
max_page: 100,
|
||||
// HOME, SERVER and LIVE, and the chats.
|
||||
max_subscriptions: driver::MAX_CHAT_SUBSCRIPTIONS + 3,
|
||||
max_chat_subscriptions: driver::MAX_CHAT_SUBSCRIPTIONS,
|
||||
max_live_subscriptions: 8,
|
||||
..Default::default()
|
||||
}),
|
||||
time_ms: now_ms(),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let (cmds_tx, cmds_rx) = mpsc::unbounded_channel();
|
||||
let own_slot = Arc::new(AtomicU32::new(entities::slot(joined.own_client)));
|
||||
let (pushes_tx, pushes_rx) = mpsc::channel(params.push_capacity.max(16));
|
||||
let (closed_tx, closed_rx) = watch::channel(None);
|
||||
let (port, streams) = if joined.capabilities.streams {
|
||||
let (events_tx, events_rx) = mpsc::unbounded_channel();
|
||||
let cmds = cmds_tx.clone();
|
||||
let send = move |cmd| {
|
||||
let _ = cmds.send(Cmd::Stream(cmd));
|
||||
};
|
||||
(Some(events_tx), Some(StreamPort::new(send, events_rx)))
|
||||
} else {
|
||||
(None, None)
|
||||
};
|
||||
let details = ServerDetails { uid: Some(joined.server_uid.clone()), ..Default::default() };
|
||||
let driver = Driver::new(Parts {
|
||||
cfg: Config {
|
||||
ts6,
|
||||
own_client: joined.own_client,
|
||||
nickname,
|
||||
own_uid: joined.own_uid.clone(),
|
||||
files: joined.capabilities.file_transfer,
|
||||
mail: joined.capabilities.offline_messages,
|
||||
},
|
||||
inner: inner_tx,
|
||||
events,
|
||||
early,
|
||||
bus,
|
||||
engine_bus: ctx.link.events.clone(),
|
||||
pushes: pushes_tx,
|
||||
media: params.media.clone(),
|
||||
port,
|
||||
closed: closed_tx,
|
||||
own_slot: own_slot.clone(),
|
||||
server: entities::server(&details, &joined.name, 0),
|
||||
epoch: u64::try_from(now_ms()).unwrap_or(1).max(1),
|
||||
});
|
||||
let session = LinkSession {
|
||||
welcome,
|
||||
features: Features::new(features),
|
||||
cmds: cmds_tx,
|
||||
closed: closed_rx,
|
||||
own_slot,
|
||||
};
|
||||
tokio::spawn(driver.run(cmds_rx));
|
||||
Ok(LocalConnected {
|
||||
connected: Connected {
|
||||
session: Arc::new(session),
|
||||
pushes: pushes_rx,
|
||||
// A TeamSpeak server has no host key to pin.
|
||||
host_uid: [0; 32],
|
||||
},
|
||||
streams,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::link::{Backends, VoiceOptions, connect_params};
|
||||
use voelin_proto::link::IssuerTrust;
|
||||
|
||||
fn params(options: &VoiceOptions) -> ConnectParams {
|
||||
let (media, _rx) = voelin_proto::test_util::media_channel();
|
||||
connect_params(options, media, &Backends::empty()).unwrap()
|
||||
}
|
||||
|
||||
fn back(options: &VoiceOptions) -> ConnectOptions {
|
||||
inner_options(¶ms(options), &LocalCtx::standalone()).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_options_of_a_bookmark_come_back_as_they_went() {
|
||||
let mut options = VoiceOptions::new("ts.example.com:9988", "nick");
|
||||
let same = back(&options);
|
||||
assert_eq!(
|
||||
(same.address.as_str(), same.nickname.as_str()),
|
||||
("ts.example.com:9988", "nick")
|
||||
);
|
||||
assert!(same.identity.is_none() && same.client_version.is_none());
|
||||
assert!(same.channel.is_none() && same.server_password.is_none() && same.token.is_none());
|
||||
|
||||
// Everything a connection can be told: the server password and the
|
||||
// privilege key go in the hello, the channel and its password in the
|
||||
// link, the identity as a credential.
|
||||
options.server_password = Some("s3cret pass&word".into());
|
||||
options.channel = Some("Games/Raid Night".into());
|
||||
options.channel_password = Some("p w+%".into());
|
||||
options.token = Some("tokenvalue".into());
|
||||
let identity = tsclientlib::Identity::create();
|
||||
options.identity = Some(crate::ts::identity::to_blob(&identity));
|
||||
// A spec the user can give; the connector resolves it.
|
||||
options.client_version = Some("generic".into());
|
||||
options.audio = false;
|
||||
let sent = params(&options);
|
||||
assert_eq!(sent.hello.password, "s3cret pass&word");
|
||||
assert_eq!(sent.hello.invite_code, "tokenvalue");
|
||||
assert_eq!(sent.hello.nickname, "nick");
|
||||
assert!(
|
||||
sent.address.starts_with("ts3server://ts.example.com?port=9988"),
|
||||
"{}",
|
||||
sent.address
|
||||
);
|
||||
assert!(!sent.address.contains("s3cret") && !sent.address.contains("tokenvalue"));
|
||||
let got = back(&options);
|
||||
assert_eq!(got.address, "ts.example.com:9988");
|
||||
assert_eq!(got.server_password, options.server_password);
|
||||
assert_eq!(got.channel.as_deref(), Some("Games/Raid Night"));
|
||||
assert_eq!(got.channel_password, options.channel_password);
|
||||
assert_eq!(got.token.as_deref(), Some("tokenvalue"));
|
||||
assert_eq!(got.client_version, versions::resolve("generic").unwrap());
|
||||
assert!(got.client_version.is_some());
|
||||
// The identity is the same key and counters.
|
||||
let b = got.identity.as_ref().unwrap();
|
||||
assert_eq!(serde_json::to_value(&identity).unwrap(), serde_json::to_value(b).unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_channel_by_id_and_an_address_that_is_a_link_are_kept() {
|
||||
let mut options = VoiceOptions::new("[::1]:9987", "nick");
|
||||
options.channel = Some("/12".into());
|
||||
let got = back(&options);
|
||||
assert_eq!(got.address, "[::1]:9987");
|
||||
assert_eq!(got.channel.as_deref(), Some("/12"));
|
||||
|
||||
// A bookmark that is a link keeps its own parameters.
|
||||
let options = VoiceOptions::new("ts3server://ts.example.com?port=1&channel=Lobby", "nick");
|
||||
let got = back(&options);
|
||||
assert_eq!(
|
||||
(got.address.as_str(), got.channel.as_deref()),
|
||||
("ts.example.com:1", Some("Lobby"))
|
||||
);
|
||||
// Another scheme is left as it is for the connector of that scheme.
|
||||
let options = VoiceOptions::new("voelin://host/i/code", "nick");
|
||||
assert_eq!(params(&options).address, "voelin://host/i/code");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn what_is_no_teamspeak_identity_is_refused() {
|
||||
let mut sent = params(&VoiceOptions::new("ts.example.com", "nick"));
|
||||
sent.credential = Credential::Voelin(Arc::new(voelin_proto::test_util::FakeSigner));
|
||||
let error = inner_options(&sent, &LocalCtx::standalone()).unwrap_err();
|
||||
assert!(matches!(error, SessionError::Protocol(_)));
|
||||
let mut sent = params(&VoiceOptions::new("ts.example.com", "nick"));
|
||||
sent.credential =
|
||||
Credential::Account { kind: "teamspeak", integration_id: Bytes::from_static(b"id") };
|
||||
assert!(inner_options(&sent, &LocalCtx::standalone()).is_err());
|
||||
let mut sent = params(&VoiceOptions::new("ts.example.com", "nick"));
|
||||
sent.credential =
|
||||
Credential::Foreign { kind: "teamspeak", blob: Bytes::from_static(b"not json") };
|
||||
assert!(inner_options(&sent, &LocalCtx::standalone()).is_err());
|
||||
// A host that wants trust is refused: TeamSpeak has no host key.
|
||||
let backends = Backends::empty();
|
||||
let confirm = backends.trust().confirm(voelin_proto::link::HostIdentity {
|
||||
address: "x".into(),
|
||||
uid: [0; 32],
|
||||
previous: None,
|
||||
});
|
||||
assert!(!futures::executor::block_on(confirm));
|
||||
}
|
||||
|
||||
/// An identity that cannot be read ends the connect with words that say
|
||||
/// where it is wrong and hold none of the key: the JSON reader's own
|
||||
/// message quotes a key that does not import, and this text reaches the
|
||||
/// event bus and the status line.
|
||||
#[test]
|
||||
fn an_identity_that_cannot_be_read_is_refused_without_the_key() {
|
||||
let (json, cut) = identity::json_with_a_cut_key();
|
||||
let mut sent = params(&VoiceOptions::new("ts.example.com", "nick"));
|
||||
sent.credential = Credential::Foreign { kind: "teamspeak", blob: Bytes::from(json) };
|
||||
let error = inner_options(&sent, &LocalCtx::standalone()).unwrap_err();
|
||||
let SessionError::Protocol(text) = error else { panic!("a protocol error: {error:?}") };
|
||||
assert!(
|
||||
text.starts_with(
|
||||
"the TeamSpeak identity cannot be read: not an identity at line 1, column "
|
||||
),
|
||||
"{text}"
|
||||
);
|
||||
identity::assert_holds_no_piece_of(&text, &cut);
|
||||
|
||||
// Not even text.
|
||||
sent.credential =
|
||||
Credential::Foreign { kind: "teamspeak", blob: Bytes::from_static(&[b'{', 0xff]) };
|
||||
let error = inner_options(&sent, &LocalCtx::standalone()).unwrap_err();
|
||||
let SessionError::Protocol(text) = error else { panic!("a protocol error: {error:?}") };
|
||||
assert_eq!(text, "the TeamSpeak identity cannot be read: it is not text");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_params_carry_what_the_session_needs_and_no_account_yet() {
|
||||
let sent = params(&VoiceOptions::new("ts.example.com", "nick"));
|
||||
assert!(sent.account.is_none());
|
||||
assert_eq!(sent.issuer_trust, IssuerTrust::Unknown);
|
||||
assert!(sent.linked.is_empty() && sent.host_pin.is_none());
|
||||
assert_eq!((sent.push_capacity, sent.timeout), (1024, Duration::from_secs(35)));
|
||||
let client = sent.hello.client.unwrap();
|
||||
assert_eq!(client.name, "Voelin");
|
||||
assert_eq!(sent.hello.version, 1);
|
||||
}
|
||||
|
||||
/// Why `connect_params` refused an address, if it did.
|
||||
fn refused(address: &str) -> Option<String> {
|
||||
let (media, _rx) = voelin_proto::test_util::media_channel();
|
||||
match connect_params(&VoiceOptions::new(address, "nick"), media, &Backends::empty()) {
|
||||
Ok(_) => None,
|
||||
Err(SessionError::Protocol(text)) => Some(text),
|
||||
Err(other) => panic!("{address}: {other}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bookmark_the_link_would_change_is_refused() {
|
||||
// A port that is no port, in any shape: the link would drop it and the
|
||||
// connection would go to the default port.
|
||||
for address in [
|
||||
"ts.example.com:99999",
|
||||
"ts.example.com:65536",
|
||||
"ts.example.com:0",
|
||||
"ts.example.com:abc",
|
||||
"ts.example.com:",
|
||||
"[::1]:70000",
|
||||
"[::1]:",
|
||||
"[::1]x",
|
||||
] {
|
||||
let text = refused(address).unwrap_or_else(|| panic!("{address} was accepted"));
|
||||
assert!(text.contains("65535") && text.contains(address), "{text}");
|
||||
}
|
||||
// A host the link would cut or decode: a `?` hides the channel behind the
|
||||
// next one, a `/` or `#` ends the host, a `%` is decoded.
|
||||
for address in [
|
||||
"",
|
||||
" ",
|
||||
"ts.example.com?x",
|
||||
"ts.example.com#x",
|
||||
"ts.example.com/x",
|
||||
"a b",
|
||||
"h%41",
|
||||
"[::1",
|
||||
] {
|
||||
let text = refused(address).unwrap_or_else(|| panic!("{address:?} was accepted"));
|
||||
assert!(text.starts_with("not a server address"), "{text}");
|
||||
}
|
||||
// The text names no query: a link keeps secrets in it.
|
||||
let text = refused("ts.example.com?password=hunter2").unwrap();
|
||||
assert!(!text.contains("hunter2"), "{text}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_bookmarks_a_server_has_come_back_with_their_channel() {
|
||||
for (address, host) in [
|
||||
("ts.example.com", "ts.example.com"),
|
||||
("ts.example.com:9987", "ts.example.com:9987"),
|
||||
(" ts.example.com:1 ", "ts.example.com:1"),
|
||||
("127.0.0.1:65535", "127.0.0.1:65535"),
|
||||
("[::1]:9987", "[::1]:9987"),
|
||||
// The brackets of a v6 address without a port are the link's to drop;
|
||||
// the TeamSpeak library reads both forms.
|
||||
("[::1]", "::1"),
|
||||
("::1", "::1"),
|
||||
("2001:db8::1", "2001:db8::1"),
|
||||
] {
|
||||
let mut options = VoiceOptions::new(address, "nick");
|
||||
options.channel = Some("Games/Raid".into());
|
||||
let got = back(&options);
|
||||
assert_eq!((got.address.as_str(), got.channel.as_deref()), (host, Some("Games/Raid")));
|
||||
}
|
||||
}
|
||||
|
||||
/// The normalisations of the round trip, listed in `docs/session-seam.md`
|
||||
/// (13): an empty option is none, and an empty nickname stays empty.
|
||||
#[test]
|
||||
fn empty_options_come_back_as_none() {
|
||||
let mut options = VoiceOptions::new("ts.example.com", "");
|
||||
options.server_password = Some(String::new());
|
||||
options.channel = Some(String::new());
|
||||
options.channel_password = Some(String::new());
|
||||
options.token = Some(String::new());
|
||||
let got = back(&options);
|
||||
assert!(got.nickname.is_empty());
|
||||
assert!(
|
||||
got.server_password.is_none()
|
||||
&& got.channel.is_none()
|
||||
&& got.channel_password.is_none()
|
||||
&& got.token.is_none()
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -8,7 +8,7 @@ use anyhow::{Context, Result, bail};
|
||||
use base64::prelude::*;
|
||||
use tsclientlib::Version;
|
||||
|
||||
const VERSIONS_CSV: &str = include_str!("../../proto/tsproto-structs/declarations/Versions.csv");
|
||||
const VERSIONS_CSV: &str = include_str!("../../../proto/tsproto-structs/declarations/Versions.csv");
|
||||
|
||||
/// The signed generic version of every platform, tsclientlib's default.
|
||||
const GENERIC_VERSION: &str = "3.?.? [Build: 5680278000]";
|
||||
File diff suppressed because it is too large.
Load diff
@@ -960,11 +960,27 @@ pub(crate) mod tests {
|
||||
|
||||
/// What `f` logs at info (and above) on this thread: each line its
|
||||
/// message, then its fields (` name=value`).
|
||||
///
|
||||
/// One recording subscriber is installed for the whole test process, the
|
||||
/// first time this is called, and each call records into a buffer of its
|
||||
/// own thread. A scoped one (`tracing::subscriber::with_default`) loses
|
||||
/// lines: while it is the only subscriber alive, a callsite that another
|
||||
/// test's thread meets first is registered against that thread's own
|
||||
/// default, which is none, and stays disabled for every thread, so the
|
||||
/// lines of the test that reads them are gone
|
||||
/// (`session::banner_tests::a_failing_banner_is_logged_once_with_its_address`
|
||||
/// failed with no lines at all, once in about thirty runs of the suite).
|
||||
pub(crate) fn info_lines<T>(f: impl FnOnce() -> T) -> (T, Vec<String>) {
|
||||
use std::cell::RefCell;
|
||||
use std::sync::Once;
|
||||
use tracing::field::{Field, Visit};
|
||||
use tracing::span;
|
||||
|
||||
struct Lines(Arc<Mutex<Vec<String>>>);
|
||||
thread_local! {
|
||||
/// The lines of the `info_lines` running on this thread, if any.
|
||||
static LINES: RefCell<Option<Vec<String>>> = const { RefCell::new(None) };
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct Line(String, String);
|
||||
impl Visit for Line {
|
||||
@@ -975,7 +991,8 @@ pub(crate) mod tests {
|
||||
}
|
||||
}
|
||||
}
|
||||
impl tracing::Subscriber for Lines {
|
||||
struct Recorder;
|
||||
impl tracing::Subscriber for Recorder {
|
||||
fn enabled(&self, metadata: &tracing::Metadata<'_>) -> bool {
|
||||
*metadata.level() <= tracing::Level::INFO
|
||||
}
|
||||
@@ -985,19 +1002,57 @@ pub(crate) mod tests {
|
||||
fn record(&self, _: &span::Id, _: &span::Record<'_>) {}
|
||||
fn record_follows_from(&self, _: &span::Id, _: &span::Id) {}
|
||||
fn event(&self, event: &tracing::Event<'_>) {
|
||||
let mut line = Line::default();
|
||||
event.record(&mut line);
|
||||
self.0.lock().unwrap().push(line.0 + &line.1);
|
||||
LINES.with(|lines| {
|
||||
if let Some(lines) = lines.borrow_mut().as_mut() {
|
||||
let mut line = Line::default();
|
||||
event.record(&mut line);
|
||||
lines.push(line.0 + &line.1);
|
||||
}
|
||||
});
|
||||
}
|
||||
fn enter(&self, _: &span::Id) {}
|
||||
fn exit(&self, _: &span::Id) {}
|
||||
}
|
||||
let lines = Arc::new(Mutex::new(Vec::new()));
|
||||
let result = tracing::subscriber::with_default(Lines(lines.clone()), f);
|
||||
let lines = lines.lock().unwrap().clone();
|
||||
/// Ends the recording of this thread, also when `f` panics.
|
||||
struct Recording;
|
||||
impl Drop for Recording {
|
||||
fn drop(&mut self) {
|
||||
LINES.with(|lines| lines.borrow_mut().take());
|
||||
}
|
||||
}
|
||||
|
||||
static INSTALL: Once = Once::new();
|
||||
INSTALL.call_once(|| {
|
||||
tracing::subscriber::set_global_default(Recorder)
|
||||
.expect("no other global tracing subscriber in the tests");
|
||||
// Makes every callsite decide again with the subscriber in place, also
|
||||
// one that a thread was registering while it was being installed
|
||||
// (creating a `Dispatch` rebuilds the cached interest of all of them).
|
||||
drop(tracing::Dispatch::new(Recorder));
|
||||
});
|
||||
|
||||
LINES.with(|lines| *lines.borrow_mut() = Some(Vec::new()));
|
||||
let _recording = Recording;
|
||||
let result = f();
|
||||
let lines = LINES.with(|lines| lines.borrow_mut().take().unwrap_or_default());
|
||||
(result, lines)
|
||||
}
|
||||
|
||||
/// The lines of `info_lines` do not depend on which thread met a callsite
|
||||
/// first: this one is met on another thread, which records nothing, before
|
||||
/// the thread that reads the lines meets it.
|
||||
#[test]
|
||||
fn info_lines_see_a_callsite_another_thread_met_first() {
|
||||
fn log() {
|
||||
tracing::info!("met");
|
||||
}
|
||||
let ((), lines) = info_lines(|| {
|
||||
std::thread::spawn(log).join().unwrap();
|
||||
log();
|
||||
});
|
||||
assert_eq!(lines, ["met"]);
|
||||
}
|
||||
|
||||
fn temp_dir(tag: &str) -> std::path::PathBuf {
|
||||
let dir = std::env::temp_dir().join(format!("voelin-web-{tag}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
@@ -1375,9 +1430,15 @@ pub(crate) mod tests {
|
||||
};
|
||||
let mut port = [0u8; 2];
|
||||
client.read_exact(&mut port).await.unwrap();
|
||||
let target = format!("{host}:{}", u16::from_be_bytes(port));
|
||||
let port = u16::from_be_bytes(port);
|
||||
let target = format!("{host}:{port}");
|
||||
targets.send(target.clone()).unwrap();
|
||||
let mut server = TcpStream::connect(target).await.unwrap();
|
||||
// The proxy resolves the name it is given (SOCKS5h). `localhost` is
|
||||
// 127.0.0.1 to it, whatever this machine's resolver says: some answer
|
||||
// `::1` only, and the servers of the tests listen on 127.0.0.1.
|
||||
let dial =
|
||||
if host == "localhost" { format!("127.0.0.1:{port}") } else { target };
|
||||
let mut server = TcpStream::connect(dial).await.unwrap();
|
||||
client.write_all(&[5, 0, 0, 1, 0, 0, 0, 0, 0, 0]).await.unwrap();
|
||||
let _ = tokio::io::copy_bidirectional(&mut client, &mut server).await;
|
||||
});
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
//! What more than one integration test of this crate needs (a test binary
|
||||
//! that uses it declares `mod common;`).
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::Duration;
|
||||
|
||||
/// Wait until nothing has the SQLite database at `path` open any more, as when
|
||||
/// the process that had it has ended: SQLite deletes the write-ahead log
|
||||
/// (`<path>-wal`) when the last connection closes.
|
||||
///
|
||||
/// A dropped `Engine` is not that yet. Its task ends later, the history writer
|
||||
/// is joined there, and closing the connection checkpoints the log under an
|
||||
/// exclusive lock, with fsyncs. A connection opened meanwhile waits for the
|
||||
/// lock only as long as the busy timeout (5 s) and then fails with
|
||||
/// `DatabaseBusy`, which a loaded disk makes happen (with every fsync taking
|
||||
/// 6 s it happens every time).
|
||||
pub async fn closed(path: &Path) {
|
||||
let mut wal = path.as_os_str().to_owned();
|
||||
wal.push("-wal");
|
||||
let wal = PathBuf::from(wal);
|
||||
tokio::time::timeout(Duration::from_secs(120), async {
|
||||
while wal.exists() {
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.expect("the engine's database connection closed");
|
||||
}
|
||||
@@ -16,6 +16,7 @@ use tokio_tungstenite::tungstenite::handshake::server::{Request, Response};
|
||||
use voelin_core::gateway::{GatewayRequest, GatewayUpdate};
|
||||
use voelin_core::history::MessageSource;
|
||||
use voelin_core::settings::Settings;
|
||||
use voelin_core::ts::identity::to_blob;
|
||||
use voelin_core::{Command, Engine, Event, History, HistoryMessage, HistorySource, ObserveState};
|
||||
use voelin_gateway_proto::{
|
||||
ClientMsg, Envelope, ErrorCode, HistoryEntry, HistoryPage, PinInfo, ReactionCount, ServerMsg,
|
||||
@@ -23,6 +24,8 @@ use voelin_gateway_proto::{
|
||||
};
|
||||
use voelin_model::{ChatMessage, ChatTarget, PresenceSnapshot};
|
||||
|
||||
mod common;
|
||||
|
||||
const LOBBY: ChatTarget = ChatTarget::Channel(1);
|
||||
const ME: &str = "me-uid";
|
||||
|
||||
@@ -448,7 +451,7 @@ fn observe(engine: &Engine, session: u64, gw: &FakeGateway) {
|
||||
engine.send(Command::ObserveGateway {
|
||||
session,
|
||||
urls: vec![gw.url.clone()],
|
||||
identity: Box::new(identity),
|
||||
identity: Box::new(to_blob(&identity)),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -528,6 +531,8 @@ async fn history_on_open_paging_and_offline_messages() {
|
||||
assert_eq!(texts(&stored), ["m1", "m2", "m3", "m4", "m5", "while away 1", "while away 2"]);
|
||||
history.flush();
|
||||
drop((engine, history));
|
||||
// Dropping the engine does not close the database yet (see `closed`).
|
||||
common::closed(&path).await;
|
||||
|
||||
// After a restart, with the gateway down: the stored page, found by the
|
||||
// gateway's URL, which is remembered with the server's id.
|
||||
@@ -742,7 +747,7 @@ async fn an_unreachable_gateway_is_tried_again_quietly() {
|
||||
engine.send(Command::ObserveGateway {
|
||||
session: 3,
|
||||
urls: vec![format!("ws://127.0.0.1:{port}/v1")],
|
||||
identity: Box::new(tsclientlib::Identity::create()),
|
||||
identity: Box::new(to_blob(&tsclientlib::Identity::create())),
|
||||
});
|
||||
// The first attempts fail (the next ones about 1 s, then 2 s later):
|
||||
// still connecting, and the user is told nothing.
|
||||
@@ -811,7 +816,16 @@ async fn not_found_proxy() -> String {
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn the_next_published_gateway_is_used_when_one_fails() {
|
||||
let proxy = not_found_proxy().await;
|
||||
let closed = std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port();
|
||||
// A port that is taken and never listened on: connecting is refused at once,
|
||||
// and no other test of this process can be given it meanwhile (one that was
|
||||
// only free for a moment could be, the listeners of the others bind port 0).
|
||||
let reserved = tokio::net::TcpSocket::new_v4().unwrap();
|
||||
reserved.bind("127.0.0.1:0".parse().unwrap()).unwrap();
|
||||
let closed = reserved.local_addr().unwrap().port();
|
||||
assert!(
|
||||
tokio::net::TcpStream::connect(("127.0.0.1", closed)).await.is_err(),
|
||||
"something listens on port {closed}"
|
||||
);
|
||||
let gw = FakeGateway::start().await;
|
||||
let path = temp_db("fallback");
|
||||
let engine = Engine::start_with(Settings::in_memory(), History::open(&path).unwrap());
|
||||
@@ -819,7 +833,7 @@ async fn the_next_published_gateway_is_used_when_one_fails() {
|
||||
engine.send(Command::ObserveGateway {
|
||||
session: 4,
|
||||
urls: vec![proxy, format!("ws://127.0.0.1:{closed}/v1"), gw.url.clone()],
|
||||
identity: Box::new(tsclientlib::Identity::create()),
|
||||
identity: Box::new(to_blob(&tsclientlib::Identity::create())),
|
||||
});
|
||||
// Within one round: sooner than the shortest wait after a failed round
|
||||
// (1 s, less 30 %).
|
||||
@@ -904,7 +918,7 @@ async fn a_login_the_gateway_cannot_do_yet_is_tried_again() {
|
||||
engine.send(Command::ObserveGateway {
|
||||
session,
|
||||
urls: vec![gw.url.clone()],
|
||||
identity: Box::new(tsclientlib::Identity::create()),
|
||||
identity: Box::new(to_blob(&tsclientlib::Identity::create())),
|
||||
});
|
||||
// After the first wait: about 1 s.
|
||||
quietly_until(&mut rx, session, Duration::from_secs(3), "observing", observing(session))
|
||||
@@ -932,6 +946,45 @@ async fn a_refused_login_ends_observing() {
|
||||
assert_eq!(gw.logins(), 1);
|
||||
}
|
||||
|
||||
/// An identity that cannot be read will not be better tomorrow: like a refused
|
||||
/// login, observing ends, and the gateway is not even asked.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn an_identity_that_cannot_be_read_ends_observing_without_a_login() {
|
||||
let gw = FakeGateway::start().await;
|
||||
let engine = Engine::start();
|
||||
let mut rx = engine.subscribe();
|
||||
let not_an_identity = voelin_core::IdentityBlob::teamspeak("x", 0, "not an identity");
|
||||
engine.send(Command::ObserveGateway {
|
||||
session: 10,
|
||||
urls: vec![gw.url.clone()],
|
||||
identity: Box::new(not_an_identity),
|
||||
});
|
||||
wait(&mut rx, "connecting", |e| match e {
|
||||
Event::State { session: 10, state } if state.observe == ObserveState::Connecting => {
|
||||
Some(())
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.await;
|
||||
wait(&mut rx, "observing off", |e| match e {
|
||||
Event::State { session: 10, state } if state.observe == ObserveState::Off => Some(()),
|
||||
_ => None,
|
||||
})
|
||||
.await;
|
||||
tokio::time::sleep(Duration::from_millis(500)).await;
|
||||
assert_eq!(gw.logins(), 0);
|
||||
// The public entry refuses it the same way.
|
||||
let error = voelin_core::gateway::connect(
|
||||
&gw.url,
|
||||
&voelin_core::IdentityBlob::new("voelin", "x", 0, "{}"),
|
||||
)
|
||||
.await
|
||||
.err()
|
||||
.expect("a refusal");
|
||||
assert_eq!(error.code(), Some(ErrorCode::AuthFailed), "{error}");
|
||||
assert_eq!(gw.logins(), 0);
|
||||
}
|
||||
|
||||
/// Selecting the server again while its gateway is still connecting does
|
||||
/// not start it over, and ends the wait for the next attempt.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
@@ -944,7 +997,7 @@ async fn asking_again_while_connecting_tries_at_once() {
|
||||
let ask = || Command::ObserveGateway {
|
||||
session: 9,
|
||||
urls: vec![gw.url.clone()],
|
||||
identity: Box::new(identity.clone()),
|
||||
identity: Box::new(to_blob(&identity)),
|
||||
};
|
||||
engine.send(ask());
|
||||
// Three logins fail (waits of about 1 and 2 s); the next wait is about 5 s.
|
||||
|
||||
@@ -1,17 +1,33 @@
|
||||
//! Engine against the development servers (dev/docker-compose.yml).
|
||||
//! Runs only with `VOELIN_LIVE=1`; `scripts/it-smoke.sh` sets it.
|
||||
|
||||
use std::sync::LazyLock;
|
||||
use std::time::Duration;
|
||||
|
||||
use tokio::sync::RwLock;
|
||||
use tokio::sync::broadcast::Receiver;
|
||||
use tokio::time::{Instant, timeout_at};
|
||||
use voelin_core::{Command, Engine, Event, ObserveState, Source, VoiceOptions, VoiceState};
|
||||
use voelin_core::{
|
||||
Command, Engine, Event, ObserveState, QueryLogin, QueryTransport, Source, VoiceOptions,
|
||||
VoiceState,
|
||||
};
|
||||
use voelin_model::ChatTarget;
|
||||
|
||||
fn live() -> bool {
|
||||
std::env::var("VOELIN_LIVE").is_ok_and(|v| v == "1")
|
||||
}
|
||||
|
||||
/// The TeamSpeak 6 server's banners are the server's, and `ts6_banners` sets and
|
||||
/// unsets them there. While it does, whatever else connects to the server is
|
||||
/// told the addresses of those banners, and an engine fetches what it is told
|
||||
/// (as it should): the requests of such an engine reached the HTTP server of
|
||||
/// `ts6_banners`, which counts the requests of the engine under test, and the
|
||||
/// test failed on `disabled policy must prevent HTTP requests` in every run
|
||||
/// that had the tests of this file run side by side (as they do). The tests
|
||||
/// that connect to the server hold this shared, `ts6_banners` exclusively: it
|
||||
/// runs with the server to itself, and the others before or after it.
|
||||
static TS6: LazyLock<RwLock<()>> = LazyLock::new(|| RwLock::new(()));
|
||||
|
||||
/// Wait for an event matching `f`, failing after 20 s.
|
||||
async fn wait_for(
|
||||
rx: &mut Receiver<Event>,
|
||||
@@ -45,7 +61,7 @@ async fn engine_roundtrip(voice_addr: &str, query: voelin_query::Connect) {
|
||||
.await;
|
||||
|
||||
// Session 2: invisible, through own query credentials.
|
||||
engine.send(Command::ObserveQuery { session: 2, connect: Box::new(query) });
|
||||
engine.send(Command::ObserveQuery { session: 2, connect: Box::new(login(&query)) });
|
||||
let (mut observing, mut sees_voice_client) = (false, false);
|
||||
wait_for(&mut events, "query presence with the voice client", |e| {
|
||||
match e {
|
||||
@@ -93,6 +109,24 @@ async fn engine_roundtrip(voice_addr: &str, query: voelin_query::Connect) {
|
||||
tokio::time::sleep(Duration::from_millis(500)).await;
|
||||
}
|
||||
|
||||
/// The credentials of a query connection, as the engine takes them.
|
||||
fn login(connect: &voelin_query::Connect) -> QueryLogin {
|
||||
QueryLogin {
|
||||
transport: match connect.transport {
|
||||
voelin_query::Transport::Raw => QueryTransport::Raw,
|
||||
voelin_query::Transport::Ssh => QueryTransport::Ssh,
|
||||
voelin_query::Transport::Http => QueryTransport::Http,
|
||||
},
|
||||
address: connect.addr.clone(),
|
||||
user: connect.user.clone(),
|
||||
secret: connect.secret.clone(),
|
||||
server_port: connect.server_port,
|
||||
server_id: connect.server_id,
|
||||
// The development servers allowlist their clients.
|
||||
allowlisted: connect.line.rate_limit.is_none(),
|
||||
}
|
||||
}
|
||||
|
||||
fn query(transport: voelin_query::Transport, addr: &str) -> voelin_query::Connect {
|
||||
voelin_query::Connect {
|
||||
transport,
|
||||
@@ -110,6 +144,7 @@ async fn ts6_engine() {
|
||||
if !live() {
|
||||
return;
|
||||
}
|
||||
let _server = TS6.read().await;
|
||||
engine_roundtrip("127.0.0.1:9988", query(voelin_query::Transport::Ssh, "127.0.0.1:10022"))
|
||||
.await;
|
||||
}
|
||||
@@ -237,6 +272,7 @@ async fn ts6_channel_joins() {
|
||||
if !live() {
|
||||
return;
|
||||
}
|
||||
let _server = TS6.read().await;
|
||||
channel_joins("127.0.0.1:9988", query(voelin_query::Transport::Ssh, "127.0.0.1:10022")).await;
|
||||
}
|
||||
|
||||
@@ -308,6 +344,7 @@ async fn ts6_banners() {
|
||||
if !live() {
|
||||
return;
|
||||
}
|
||||
let _server = TS6.write().await;
|
||||
let voice_addr =
|
||||
std::env::var("VOELIN_BANNER_VOICE_ADDR").unwrap_or_else(|_| "127.0.0.1:9988".into());
|
||||
let query_addr =
|
||||
@@ -491,6 +528,7 @@ async fn ts6_avatars() {
|
||||
if !live() {
|
||||
return;
|
||||
}
|
||||
let _server = TS6.read().await;
|
||||
let voice_addr =
|
||||
std::env::var("VOELIN_BANNER_VOICE_ADDR").unwrap_or_else(|_| "127.0.0.1:9988".into());
|
||||
let dir = std::env::temp_dir().join(format!("voelin-live-avatars-{}", std::process::id()));
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
//! The engine on a `voelin_proto::link::Session` that no TeamSpeak code
|
||||
//! made: `Engine::start_with_backends` takes the connector registry, and the
|
||||
//! scheme of a session's address picks the connector. The fake host of the
|
||||
//! protocol repository stands for a Voelin host here (the fuller tests of the
|
||||
//! seam on the fake host come with the next slice of
|
||||
//! `docs/session-seam.md`).
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use tokio::sync::broadcast;
|
||||
use voelin_core::settings::Settings;
|
||||
use voelin_core::{
|
||||
Backends, Command, Engine, Event, History, SessionState, VoiceOptions, VoiceState,
|
||||
};
|
||||
use voelin_proto::test_util::FakeConnector;
|
||||
use voelin_proto::v1::{self, entity::Kind};
|
||||
|
||||
const SESSION: u64 = 1;
|
||||
|
||||
async fn next<T>(
|
||||
events: &mut broadcast::Receiver<Event>,
|
||||
mut f: impl FnMut(Event) -> Option<T>,
|
||||
) -> T {
|
||||
tokio::time::timeout(Duration::from_secs(10), async {
|
||||
loop {
|
||||
if let Some(t) = f(events.recv().await.expect("engine events")) {
|
||||
return t;
|
||||
}
|
||||
}
|
||||
})
|
||||
.await
|
||||
.expect("an event in time")
|
||||
}
|
||||
|
||||
fn host_with_two_channels(connector: &FakeConnector) {
|
||||
let host = connector.host();
|
||||
let put = |kind: Kind| host.put(v1::Entity { kind: Some(kind) }).unwrap();
|
||||
put(Kind::Server(v1::Server {
|
||||
id: 1,
|
||||
name: "Fake Host".into(),
|
||||
uid: "fake-host".into(),
|
||||
default_channel_id: 10,
|
||||
..Default::default()
|
||||
}));
|
||||
for (id, name, position) in [(10, "Lobby", 0), (11, "Games", 1024)] {
|
||||
put(Kind::Channel(v1::Channel {
|
||||
id,
|
||||
server_id: 1,
|
||||
kind: v1::ChannelKind::Voice as i32,
|
||||
name: name.into(),
|
||||
position,
|
||||
..Default::default()
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_session_of_a_registered_connector_is_the_engines_voice_source() {
|
||||
let connector = FakeConnector::new();
|
||||
host_with_two_channels(&connector);
|
||||
let mut backends = Backends::empty();
|
||||
backends.register(Arc::new(connector.clone()));
|
||||
let engine = Engine::start_with_backends(Settings::in_memory(), History::in_memory(), backends);
|
||||
let mut events = engine.subscribe();
|
||||
|
||||
engine.send(Command::ConnectVoice {
|
||||
session: SESSION,
|
||||
options: Box::new(VoiceOptions::new("fake://host", "tester")),
|
||||
});
|
||||
let (name, backend) = next(&mut events, |e| match e {
|
||||
Event::ServerInfo { name, backend, .. } => Some((name, backend)),
|
||||
_ => None,
|
||||
})
|
||||
.await;
|
||||
assert_eq!((name.as_str(), backend.product.as_str()), ("Fake Host", "voelin-fake"));
|
||||
let presence = next(&mut events, |e| match e {
|
||||
Event::Presence { presence, .. } if !presence.channels.is_empty() => Some(presence),
|
||||
_ => None,
|
||||
})
|
||||
.await;
|
||||
let channels: Vec<_> =
|
||||
presence.channels.values().map(|c| (c.id, c.name.as_str(), c.order)).collect();
|
||||
assert_eq!(channels, [(10, "Lobby", 0), (11, "Games", 10)]);
|
||||
// The host was asked once, with the nickname and the TeamSpeak-shaped
|
||||
// credential the engine makes of its options for now.
|
||||
let connects = connector.connects();
|
||||
assert_eq!(connects.len(), 1);
|
||||
assert_eq!(connects[0].address, "fake://host");
|
||||
assert_eq!(connects[0].hello.nickname, "tester");
|
||||
|
||||
// A move is a request to the host; the host's voice state is where we are.
|
||||
engine.send(Command::MoveToChannel { session: SESSION, channel: 11, password: None });
|
||||
let state: SessionState = next(&mut events, |e| match e {
|
||||
Event::State { state, .. } if state.own_channel == Some(11) => Some(state),
|
||||
_ => None,
|
||||
})
|
||||
.await;
|
||||
assert_eq!(state.voice, VoiceState::Connected);
|
||||
|
||||
engine.send(Command::DisconnectVoice { session: SESSION });
|
||||
next(&mut events, |e| match e {
|
||||
Event::State { state, .. } if state.voice == VoiceState::Disconnected => Some(()),
|
||||
_ => None,
|
||||
})
|
||||
.await;
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn an_address_no_connector_serves_fails_with_the_registry_s_words() {
|
||||
let engine =
|
||||
Engine::start_with_backends(Settings::in_memory(), History::in_memory(), Backends::empty());
|
||||
let mut events = engine.subscribe();
|
||||
engine.send(Command::ConnectVoice {
|
||||
session: SESSION,
|
||||
options: Box::new(VoiceOptions::new("voelin://host/i/code", "tester")),
|
||||
});
|
||||
let error = next(&mut events, |e| match e {
|
||||
Event::Error { message, .. } => Some(message),
|
||||
_ => None,
|
||||
})
|
||||
.await;
|
||||
assert_eq!(error, "voice: no connector for voelin://host/i/code");
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -167,7 +167,7 @@ async fn ts6_stream_between_sessions() {
|
||||
Event::StreamViewers { session: 1, viewers }
|
||||
if viewers
|
||||
.iter()
|
||||
.any(|v| v.client.0 == viewer && v.state == ViewerState::Connected) =>
|
||||
.any(|v| v.client == viewer && v.state == ViewerState::Connected) =>
|
||||
{
|
||||
Some(())
|
||||
}
|
||||
|
||||
@@ -10,6 +10,10 @@ use voelin_core::settings::Settings;
|
||||
use voelin_core::{Command, Contact, DownloadTo, Engine, Event, History, Relation, TransferState};
|
||||
use voelin_model::FileRef;
|
||||
|
||||
mod common;
|
||||
|
||||
use common::closed;
|
||||
|
||||
async fn next<T>(rx: &mut broadcast::Receiver<Event>, mut f: impl FnMut(Event) -> Option<T>) -> T {
|
||||
tokio::time::timeout(Duration::from_secs(10), async {
|
||||
loop {
|
||||
@@ -165,6 +169,7 @@ async fn contacts_are_kept_in_the_database() {
|
||||
engine.history().flush();
|
||||
}
|
||||
// A new engine attaches the database later: the contacts come back.
|
||||
closed(&path).await;
|
||||
let engine = Engine::start();
|
||||
let mut rx = engine.subscribe();
|
||||
engine.send(Command::AttachHistory(History::open(&path).unwrap()));
|
||||
|
||||
@@ -24,7 +24,7 @@ tokio = { version = "1", features = ["macros", "net", "rt", "sync"], optional =
|
||||
# TLS (`wss://`, as gateways run behind a proxy) with the system's
|
||||
# certificates; rustls and its crates are in the tree already (reqwest).
|
||||
tokio-tungstenite = { version = "0.30", optional = true, features = ["rustls-tls-native-roots"] }
|
||||
voelin-model = { path = "../voelin-model" }
|
||||
voelin-model = { workspace = true }
|
||||
tsproto-types = { path = "../proto/tsproto-types" }
|
||||
|
||||
[lints]
|
||||
|
||||
@@ -29,7 +29,7 @@ toml = "1.1.6"
|
||||
tracing = "0.1.44"
|
||||
tracing-subscriber = { version = "0.3.23", features = ["env-filter"] }
|
||||
voelin-gateway-proto = { path = "../voelin-gateway-proto" }
|
||||
voelin-model = { path = "../voelin-model" }
|
||||
voelin-model = { workspace = true }
|
||||
voelin-observer = { path = "../voelin-observer" }
|
||||
voelin-query = { path = "../voelin-query" }
|
||||
|
||||
|
||||
@@ -1,14 +1,29 @@
|
||||
# Build: docker build -f crates/voelin-gateway/Dockerfile -t tsgw .
|
||||
# syntax=docker/dockerfile:1
|
||||
# Build: docker build --ssh default -f crates/voelin-gateway/Dockerfile -t tsgw .
|
||||
# (--ssh default hands the build your ssh-agent, which must hold a key that
|
||||
# can read the private VoelinProtocol repository: docs/building.md,
|
||||
# "Depending on VoelinProtocol". The gateway itself does not use it, but
|
||||
# Cargo resolves the whole workspace, which includes voelin-identity.)
|
||||
# Run: docker run -d --name tsgw --init --restart unless-stopped \
|
||||
# -v ./tsgw.toml:/etc/tsgw/tsgw.toml:ro -v tsgw-data:/var/lib/tsgw \
|
||||
# -e TSGW_QUERY_PASSWORD=… -p 7788:7788 tsgw
|
||||
# Logs: docker logs -f tsgw (more: -e TSGW_LOG_LEVEL=debug; also to a file in
|
||||
# the volume: -e TSGW_LOG_FILE=logs/tsgw.log). See docs/gateway-admin.md.
|
||||
FROM rust:1.94-bookworm AS build
|
||||
FROM rust:1.95-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/*
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends cmake git libasound2-dev openssh-client && rm -rf /var/lib/apt/lists/*
|
||||
# voelin-identity comes from the private VoelinProtocol repository, fetched
|
||||
# over SSH by Cargo through the system git, with the agent that
|
||||
# `docker build --ssh default` forwards (scripts/docker-build.sh passes it):
|
||||
# the key stays in the agent and never reaches a layer. The host key is the
|
||||
# reviewed line from .gitea/known_hosts. Cargo resolves the whole workspace, so
|
||||
# every cargo command needs this, although this crate does not use
|
||||
# voelin-identity.
|
||||
COPY .gitea/known_hosts /etc/ssh/ssh_known_hosts
|
||||
ENV CARGO_NET_GIT_FETCH_WITH_CLI=true
|
||||
COPY . .
|
||||
RUN cargo build --release --locked -p voelin-gateway && cp target/release/tsgw /tsgw && mkdir /data
|
||||
RUN --mount=type=ssh,required=true \
|
||||
cargo build --release --locked -p voelin-gateway && cp target/release/tsgw /tsgw && mkdir /data
|
||||
|
||||
FROM gcr.io/distroless/cc-debian12:nonroot
|
||||
COPY --from=build /tsgw /usr/local/bin/tsgw
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
[package]
|
||||
name = "voelin-gpui"
|
||||
version = "0.0.1-alpha"
|
||||
description = "The GPUI front end of the desktop app, under construction: it runs on the same engine as the Slint front end (voelin-ui) until it reaches parity."
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
license.workspace = true
|
||||
repository.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[lib]
|
||||
name = "voelin_gpui"
|
||||
path = "src/lib.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "voelin-gpui"
|
||||
path = "src/main.rs"
|
||||
|
||||
[dependencies]
|
||||
anyhow = "1.0.104"
|
||||
# GPUI, gpui-component and gpui-kit-assets behind one pinned dependency.
|
||||
gpui-kit = { workspace = true }
|
||||
# The engine's runtime and the channel of its events (a tokio receiver needs no
|
||||
# reactor, so GPUI's executor can await it).
|
||||
tokio = { version = "1.53.1", features = ["rt-multi-thread", "sync", "time"] }
|
||||
tracing = "0.1.44"
|
||||
tracing-subscriber = { version = "0.3.23", features = ["env-filter"] }
|
||||
# The engine, with the desktop's capture and codecs: ashpd on async-io (the
|
||||
# commit that moved voelin-media and voelin-platform to it) lets this binary
|
||||
# hold both the portals and gpui-kit.
|
||||
voelin-core = { path = "../voelin-core", default-features = false, features = ["audio-device", "media-desktop"] }
|
||||
# The app's name and id, the hotkeys and portals of the slices to come.
|
||||
voelin-platform = { path = "../voelin-platform" }
|
||||
# The Host trait's types (what the store knows of a chat's read marker).
|
||||
voelin-store = { path = "../voelin-store" }
|
||||
# The view models and the state, shared with the Slint front end.
|
||||
voelin-ui-vm = { path = "../voelin-ui-vm" }
|
||||
|
||||
# The meter reads /proc/self (CPU ticks per second, the page size).
|
||||
[target.'cfg(target_os = "linux")'.dependencies]
|
||||
rustix = { version = "1.1.5", features = ["param"] }
|
||||
|
||||
[dev-dependencies]
|
||||
# GPUI's test platform (`#[gpui::test]`, `TestAppContext`): the front end's tests
|
||||
# need no display. gpui-kit's own `test-support` feature is not used: it names
|
||||
# the optional `gpui-fast` backend in weak features, which puts gpui-fast and
|
||||
# its tree into Cargo.lock and pins taffy to 0.15.0 for every build. gpui-kit
|
||||
# pins `gpui-pre` exactly, so this line moves with its `=` pin (a mismatch does
|
||||
# not resolve).
|
||||
gpui = { package = "gpui-pre", version = "=0.3.10", features = ["test-support"] }
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -0,0 +1,34 @@
|
||||
//! Embeds the client's Lucide icons: `crates/voelin-ui/ui/assets/icons/*.svg`
|
||||
//! (Lucide 1.48, the set the Slint front end draws) become a sorted table of
|
||||
//! `include_bytes!` in `$OUT_DIR/icons.rs`, which `assets.rs` serves as
|
||||
//! gpui-component's `icons/<name>.svg` paths before gpui-kit-assets' own
|
||||
//! (Lucide 1.43) catalogue. No dependency: the directory is read and the
|
||||
//! table written with `std`.
|
||||
|
||||
use std::fmt::Write as _;
|
||||
use std::path::PathBuf;
|
||||
|
||||
fn main() {
|
||||
let manifest =
|
||||
PathBuf::from(std::env::var_os("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR"));
|
||||
let dir = manifest.join("../voelin-ui/ui/assets/icons");
|
||||
println!("cargo:rerun-if-changed={}", dir.display());
|
||||
let mut names: Vec<String> = std::fs::read_dir(&dir)
|
||||
.unwrap_or_else(|e| panic!("the client's icons are at {}: {e}", dir.display()))
|
||||
.filter_map(|entry| entry.ok()?.file_name().into_string().ok())
|
||||
.filter(|name| name.ends_with(".svg"))
|
||||
.collect();
|
||||
names.sort();
|
||||
assert!(!names.is_empty(), "no icons in {}", dir.display());
|
||||
let mut table = String::from(
|
||||
"/// The client's icons by file name, sorted.\npub static ICONS: &[(&str, &[u8])] = &[\n",
|
||||
);
|
||||
for name in &names {
|
||||
let path = dir.join(name);
|
||||
let path = path.canonicalize().unwrap_or(path);
|
||||
let _ = writeln!(table, "\t({name:?}, include_bytes!({:?})),", path.display().to_string());
|
||||
}
|
||||
table.push_str("];\n");
|
||||
let out = PathBuf::from(std::env::var_os("OUT_DIR").expect("OUT_DIR")).join("icons.rs");
|
||||
std::fs::write(out, table).expect("write icons.rs");
|
||||
}
|
||||
@@ -0,0 +1,453 @@
|
||||
//! The root state of the window, `Entity<AppState>`: everything the client
|
||||
//! knows (the toolkit-free [`voelin_ui_vm`] state and the friends and pokes
|
||||
//! beside it) and the three loops that keep it current on GPUI's thread:
|
||||
//!
|
||||
//! - the **engine's events**: a foreground task awaits the receiver of
|
||||
//! [`crate::engine::HostedEngine`] (a tokio channel needs no reactor, so
|
||||
//! GPUI's executor can poll it), hands every event to
|
||||
//! [`events::handle`] and tells the entity to redraw (`cx.notify()`), the
|
||||
//! pattern of spike 3's hotkey task;
|
||||
//! - the **tick**, once a second, a loop of `background_executor().timer`
|
||||
//! (the Slint front end's `slint::Timer` calling `App::tick`);
|
||||
//! - **later**: other threads (a hotkey, a camera, a decoder) cannot touch the
|
||||
//! entity, and GPUI's `AsyncApp` is not `Send`, so they hold a [`Later`], a
|
||||
//! channel of jobs a third foreground task runs on GPUI's thread, as
|
||||
//! `later(|app| ...)` does in the Slint front end.
|
||||
//!
|
||||
//! What a transition asks for besides the state (`Update`: which parts to
|
||||
//! draw again, what to keep, the streams' capture and decoder) belongs to
|
||||
//! the slices that have those parts; today only the engine commands go out
|
||||
//! and the warnings are logged.
|
||||
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use gpui_kit::Context;
|
||||
use tokio::sync::mpsc::{self, UnboundedReceiver, UnboundedSender};
|
||||
use voelin_core::{AudioSettings, Command, Engine, Event, VoiceState};
|
||||
use voelin_store::{ChatRead, ChatTarget as StoredTarget};
|
||||
use voelin_ui_vm::bridge::ChatLine;
|
||||
use voelin_ui_vm::events;
|
||||
use voelin_ui_vm::host::{Host, Update};
|
||||
use voelin_ui_vm::settings::UiSettings;
|
||||
use voelin_ui_vm::social::logic::Social;
|
||||
|
||||
use crate::meter::Counters;
|
||||
|
||||
/// The toolkit-free state of the client, with the chat lines of a tab as plain
|
||||
/// rows (what a front end that draws again from the list needs).
|
||||
pub type VmState = voelin_ui_vm::state::AppState<Vec<ChatLine>>;
|
||||
|
||||
/// A job for GPUI's thread, from any thread.
|
||||
type Job = Box<dyn FnOnce(&mut AppState, &mut Context<AppState>) + Send>;
|
||||
|
||||
/// How other threads reach the root state: `later.run(|app, cx| ...)` runs
|
||||
/// the closure on GPUI's thread with the entity (the Slint front end's
|
||||
/// `later`). Cloneable and `Send`; the closure must be `Send` too.
|
||||
#[derive(Clone)]
|
||||
pub struct Later(UnboundedSender<Job>);
|
||||
|
||||
impl Later {
|
||||
/// Run `job` on GPUI's thread soon. `false` once a job has found the
|
||||
/// window gone (the entity released): the loop that runs the jobs notices
|
||||
/// that only when a job reaches it, ends and drops the channel, so the
|
||||
/// first job sent after the window went answers `true` and is never run.
|
||||
/// `true` is a promise of nothing more than that the job was queued.
|
||||
pub fn run(
|
||||
&self,
|
||||
job: impl FnOnce(&mut AppState, &mut Context<AppState>) + Send + 'static,
|
||||
) -> bool {
|
||||
self.0.send(Box::new(job)).is_ok()
|
||||
}
|
||||
}
|
||||
|
||||
/// What the transitions of the state ask of this front end while they run.
|
||||
/// There is no store yet (the shell slice opens it): nothing was read, and
|
||||
/// nothing is kept.
|
||||
#[derive(Debug, Default)]
|
||||
struct ShellHost;
|
||||
|
||||
impl Host for ShellHost {
|
||||
fn demo_ui(&self) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
fn chat_shown(&self) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
fn watching(&self) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
fn autowatch(&self) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
fn studio_streams_to(&self, _session: i64) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
fn preview_limit(&self) -> u64 {
|
||||
0
|
||||
}
|
||||
|
||||
fn fetch_images(&self) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
fn dm_shown(&self, _session: i64, _uid: &str) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
fn chat_reads(&self, _server_uid: &str) -> Result<Vec<(StoredTarget, ChatRead)>, String> {
|
||||
Ok(Vec::new())
|
||||
}
|
||||
|
||||
fn set_chat_read(
|
||||
&self,
|
||||
_server_uid: &str,
|
||||
_target: &StoredTarget,
|
||||
_read: &ChatRead,
|
||||
) -> Result<(), String> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// The root entity.
|
||||
pub struct AppState {
|
||||
/// What the client knows apart from the window.
|
||||
pub vm: VmState,
|
||||
/// The friends, pokes and notices the social screens keep.
|
||||
pub social: Social<()>,
|
||||
/// Engine events handled since the window opened.
|
||||
pub events_handled: u64,
|
||||
/// One-second ticks since the window opened.
|
||||
pub ticks: u64,
|
||||
engine: Option<Engine>,
|
||||
host: ShellHost,
|
||||
started: Instant,
|
||||
counters: Counters,
|
||||
later: Later,
|
||||
}
|
||||
|
||||
impl AppState {
|
||||
/// The state at start, with its three loops running: the engine's
|
||||
/// `events` (the engine is `None` in tests that need none), the tick and
|
||||
/// the jobs of [`Later`]. They end when the entity is released.
|
||||
pub fn new(
|
||||
engine: Option<Engine>,
|
||||
events: UnboundedReceiver<Event>,
|
||||
counters: Counters,
|
||||
cx: &mut Context<Self>,
|
||||
) -> Self {
|
||||
let (later, mut jobs) = mpsc::unbounded_channel::<Job>();
|
||||
|
||||
cx.spawn(async move |this, cx| {
|
||||
let mut events = events;
|
||||
while let Some(event) = events.recv().await {
|
||||
if this.update(cx, |state, cx| state.handle_event(event, cx)).is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
})
|
||||
.detach();
|
||||
|
||||
cx.spawn(async move |this, cx| {
|
||||
loop {
|
||||
cx.background_executor().timer(Duration::from_secs(1)).await;
|
||||
if this.update(cx, |state, cx| state.tick(cx)).is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
})
|
||||
.detach();
|
||||
|
||||
cx.spawn(async move |this, cx| {
|
||||
while let Some(job) = jobs.recv().await {
|
||||
if this
|
||||
.update(cx, |state, cx| {
|
||||
state.counters.later_jobs.incr();
|
||||
job(state, cx);
|
||||
cx.notify();
|
||||
})
|
||||
.is_err()
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
})
|
||||
.detach();
|
||||
|
||||
Self {
|
||||
vm: VmState::new(
|
||||
Vec::new(),
|
||||
UiSettings::default(),
|
||||
AudioSettings::default(),
|
||||
Default::default(),
|
||||
),
|
||||
social: Social::default(),
|
||||
events_handled: 0,
|
||||
ticks: 0,
|
||||
engine,
|
||||
host: ShellHost,
|
||||
started: Instant::now(),
|
||||
counters,
|
||||
later: Later(later),
|
||||
}
|
||||
}
|
||||
|
||||
/// The handle other threads use to run something on GPUI's thread.
|
||||
pub fn later(&self) -> Later {
|
||||
self.later.clone()
|
||||
}
|
||||
|
||||
/// What an engine event does to the state ([`events::handle`], the one
|
||||
/// dispatch of both front ends), and what comes of it for the engine.
|
||||
pub fn handle_event(&mut self, event: Event, cx: &mut Context<Self>) {
|
||||
self.events_handled += 1;
|
||||
self.counters.engine_events.incr();
|
||||
let update = events::handle(&mut self.vm, &mut self.social, &self.host, event);
|
||||
self.perform(update);
|
||||
self.counters.connections.set(self.connections() as u64);
|
||||
cx.notify();
|
||||
}
|
||||
|
||||
/// Do what an update asks that this front end has the parts for: the
|
||||
/// engine's commands go out, the warnings are logged.
|
||||
fn perform(&mut self, update: Update) {
|
||||
if let Some(engine) = &self.engine {
|
||||
for command in update.commands {
|
||||
engine.send(command);
|
||||
}
|
||||
}
|
||||
for warning in update.warnings {
|
||||
tracing::warn!("{warning}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The once-a-second work: what the Slint front end's `App::tick` will be
|
||||
/// here (stream statistics, stored settings); today it counts.
|
||||
pub fn tick(&mut self, cx: &mut Context<Self>) {
|
||||
self.ticks += 1;
|
||||
self.counters.ticks.incr();
|
||||
cx.notify();
|
||||
}
|
||||
|
||||
/// Voice connections that are up.
|
||||
pub fn connections(&self) -> usize {
|
||||
self.vm.sessions.values().filter(|view| view.state.voice == VoiceState::Connected).count()
|
||||
}
|
||||
|
||||
/// Seconds since the window opened.
|
||||
pub fn uptime(&self) -> Duration {
|
||||
self.started.elapsed()
|
||||
}
|
||||
|
||||
/// The one line of state the window shows: the version, how many voice
|
||||
/// connections are up, how many engine events came and how long the
|
||||
/// window has run. Each part moves by a loop above, so a line that
|
||||
/// changes shows that the loop runs.
|
||||
pub fn state_line(&self) -> String {
|
||||
let connections = self.connections();
|
||||
format!(
|
||||
"{} {} · {} connection{} · {} engine event{} · {} s up",
|
||||
voelin_platform::APP_NAME,
|
||||
env!("CARGO_PKG_VERSION"),
|
||||
connections,
|
||||
if connections == 1 { "" } else { "s" },
|
||||
self.events_handled,
|
||||
if self.events_handled == 1 { "" } else { "s" },
|
||||
self.ticks,
|
||||
)
|
||||
}
|
||||
|
||||
/// Leave the servers properly, so no ghost client stays behind until it
|
||||
/// times out (the window is closing): tell the engine to close every
|
||||
/// session. Returns how many it told, so that the caller can give the
|
||||
/// engine time to act on them before the runtime goes (none without an
|
||||
/// engine).
|
||||
pub fn shutdown(&self) -> usize {
|
||||
let Some(engine) = &self.engine else { return 0 };
|
||||
for id in self.vm.sessions.keys() {
|
||||
engine.send(Command::CloseSession { session: *id as u64 });
|
||||
}
|
||||
self.vm.sessions.len()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::time::Duration;
|
||||
|
||||
use gpui::TestAppContext;
|
||||
use gpui_kit::AppContext as _;
|
||||
use voelin_core::{Command, Event, SessionState, VoiceState};
|
||||
|
||||
use super::*;
|
||||
use crate::engine::HostedEngine;
|
||||
|
||||
fn voice(voice: VoiceState) -> Event {
|
||||
Event::State { session: 1, state: SessionState { voice, ..Default::default() } }
|
||||
}
|
||||
|
||||
/// The entity of a test with no engine behind it: `tx` stands in for the
|
||||
/// engine's events.
|
||||
fn entity(
|
||||
cx: &mut TestAppContext,
|
||||
) -> (gpui_kit::Entity<AppState>, UnboundedSender<Event>, Counters) {
|
||||
let (tx, rx) = mpsc::unbounded_channel();
|
||||
let counters = Counters::default();
|
||||
let app = cx.new({
|
||||
let counters = counters.clone();
|
||||
move |cx| AppState::new(None, rx, counters, cx)
|
||||
});
|
||||
(app, tx, counters)
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
fn an_injected_engine_event_reaches_the_entity(cx: &mut TestAppContext) {
|
||||
let (app, tx, counters) = entity(cx);
|
||||
app.read_with(cx, |app, _| {
|
||||
assert_eq!(app.connections(), 0);
|
||||
assert!(app.state_line().contains("0 connections · 0 engine events"));
|
||||
});
|
||||
|
||||
tx.send(voice(VoiceState::Connected)).unwrap();
|
||||
cx.run_until_parked();
|
||||
app.read_with(cx, |app, _| {
|
||||
assert_eq!(app.events_handled, 1);
|
||||
assert_eq!(app.connections(), 1);
|
||||
assert_eq!(app.vm.status, "Connected", "the transition's status line");
|
||||
assert!(
|
||||
app.state_line().contains("1 connection · 1 engine event"),
|
||||
"{}",
|
||||
app.state_line()
|
||||
);
|
||||
});
|
||||
assert_eq!(counters.engine_events.get(), 1);
|
||||
assert_eq!(counters.connections.get(), 1);
|
||||
|
||||
tx.send(voice(VoiceState::Disconnected)).unwrap();
|
||||
cx.run_until_parked();
|
||||
app.read_with(cx, |app, _| {
|
||||
assert_eq!((app.events_handled, app.connections()), (2, 0));
|
||||
});
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
fn the_entity_redraws_on_an_event(cx: &mut TestAppContext) {
|
||||
let (app, tx, _) = entity(cx);
|
||||
let notified = std::rc::Rc::new(std::cell::Cell::new(0));
|
||||
let _subscription = cx.update(|cx| {
|
||||
let notified = notified.clone();
|
||||
cx.observe(&app, move |_, _| notified.set(notified.get() + 1))
|
||||
});
|
||||
tx.send(voice(VoiceState::Connecting)).unwrap();
|
||||
cx.run_until_parked();
|
||||
assert_eq!(notified.get(), 1);
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
fn the_tick_runs_once_a_second(cx: &mut TestAppContext) {
|
||||
let (app, _tx, counters) = entity(cx);
|
||||
cx.run_until_parked();
|
||||
assert_eq!(app.read_with(cx, |app, _| app.ticks), 0);
|
||||
for second in 1..=3 {
|
||||
cx.executor().advance_clock(Duration::from_secs(1));
|
||||
cx.run_until_parked();
|
||||
assert_eq!(app.read_with(cx, |app, _| app.ticks), second);
|
||||
}
|
||||
assert_eq!(counters.ticks.get(), 3);
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
fn another_thread_runs_a_job_on_the_entity_through_later(cx: &mut TestAppContext) {
|
||||
let (app, _tx, counters) = entity(cx);
|
||||
let later = app.read_with(cx, |app, _| app.later());
|
||||
let sent = std::thread::spawn(move || {
|
||||
later.run(|app, _| app.vm.status = "from another thread".into())
|
||||
})
|
||||
.join()
|
||||
.unwrap();
|
||||
assert!(sent);
|
||||
cx.run_until_parked();
|
||||
assert_eq!(app.read_with(cx, |app, _| app.vm.status.clone()), "from another thread");
|
||||
assert_eq!(counters.later_jobs.get(), 1);
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
fn a_job_sent_after_the_window_went_is_dropped_and_the_next_one_is_refused(
|
||||
cx: &mut TestAppContext,
|
||||
) {
|
||||
let (app, _tx, counters) = entity(cx);
|
||||
let later = app.read_with(cx, |app, _| app.later());
|
||||
drop(app);
|
||||
cx.update(|_| {});
|
||||
cx.run_until_parked();
|
||||
assert!(later.run(|_, _| {}), "queued: nothing has found the entity gone yet");
|
||||
cx.run_until_parked();
|
||||
assert_eq!(counters.later_jobs.get(), 0, "never run");
|
||||
assert!(!later.run(|_, _| {}), "the first job found the entity gone");
|
||||
}
|
||||
|
||||
/// What closing the window hands the runtime's shutdown: the number of
|
||||
/// sessions the engine was told to close, which `run` gives time to act
|
||||
/// on (the Slint front end does the same). The engine ignores a close for
|
||||
/// a session it never opened, so the sessions here are only the state's.
|
||||
#[gpui::test]
|
||||
fn closing_counts_the_sessions_the_engine_was_told_to_close(cx: &mut TestAppContext) {
|
||||
let runtime = tokio::runtime::Builder::new_multi_thread()
|
||||
.worker_threads(2)
|
||||
.enable_all()
|
||||
.build()
|
||||
.unwrap();
|
||||
let hosted = HostedEngine::start(&runtime);
|
||||
let (tx, rx) = mpsc::unbounded_channel();
|
||||
let app =
|
||||
cx.new(|cx| AppState::new(Some(hosted.engine.clone()), rx, Counters::default(), cx));
|
||||
assert_eq!(app.read_with(cx, |app, _| app.shutdown()), 0, "no session open yet");
|
||||
tx.send(voice(VoiceState::Connected)).unwrap();
|
||||
cx.run_until_parked();
|
||||
assert_eq!(app.read_with(cx, |app, _| app.shutdown()), 1);
|
||||
runtime.shutdown_timeout(Duration::from_secs(2));
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
fn closing_without_an_engine_tells_nothing(cx: &mut TestAppContext) {
|
||||
let (app, tx, _) = entity(cx);
|
||||
tx.send(voice(VoiceState::Connected)).unwrap();
|
||||
cx.run_until_parked();
|
||||
assert_eq!(app.read_with(cx, |app, _| (app.connections(), app.shutdown())), (1, 0));
|
||||
}
|
||||
|
||||
/// The whole path with a real engine: a command makes the engine report a
|
||||
/// setting change, which its forwarder hands to the window's channel and
|
||||
/// the foreground task to the entity. The engine's tasks run on tokio
|
||||
/// threads, so the test looks again until the event is in (no bound on
|
||||
/// how long the loaded machine takes, a generous one on the whole wait);
|
||||
/// the test scheduler is told that other threads wake it
|
||||
/// (`allow_parking`), which it otherwise reports as a test that is not
|
||||
/// deterministic.
|
||||
#[gpui::test]
|
||||
fn a_real_engine_event_reaches_the_entity(cx: &mut TestAppContext) {
|
||||
cx.executor().allow_parking();
|
||||
let runtime = tokio::runtime::Builder::new_multi_thread()
|
||||
.worker_threads(2)
|
||||
.enable_all()
|
||||
.build()
|
||||
.unwrap();
|
||||
let hosted = HostedEngine::start(&runtime);
|
||||
let engine = hosted.engine.clone();
|
||||
let counters = Counters::default();
|
||||
let app = cx.new(|cx| AppState::new(Some(engine.clone()), hosted.events, counters, cx));
|
||||
engine.send(Command::SetSetting { key: "stream.fps".into(), value: 144.into() });
|
||||
let deadline = Instant::now() + Duration::from_secs(120);
|
||||
while app.read_with(cx, |app, _| app.events_handled) == 0 {
|
||||
assert!(Instant::now() < deadline, "the engine's event never arrived");
|
||||
cx.run_until_parked();
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
}
|
||||
assert!(app.read_with(cx, |app, _| app.events_handled) >= 1);
|
||||
runtime.shutdown_timeout(Duration::from_secs(2));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
//! What `svg()` and gpui-component's `Icon` load by path. The client's own
|
||||
//! Lucide 1.48 icons (the 147 SVGs of the Slint front end, embedded by
|
||||
//! `build.rs`) answer `icons/<name>.svg` first, so every widget draws the
|
||||
//! icons the client draws; anything else (the rest of gpui-kit-assets'
|
||||
//! Lucide 1.43 catalogue, which gpui-component's `IconName` names) comes from
|
||||
//! gpui-kit-assets.
|
||||
|
||||
use std::borrow::Cow;
|
||||
|
||||
use gpui_kit::{AssetSource, Result, SharedString};
|
||||
|
||||
include!(concat!(env!("OUT_DIR"), "/icons.rs"));
|
||||
|
||||
/// The client's icons first, then gpui-kit-assets'.
|
||||
#[derive(Clone, Copy, Debug, Default)]
|
||||
pub struct Assets;
|
||||
|
||||
/// The client's icon of a file name (`mic.svg`), if it has one.
|
||||
pub fn client_icon(name: &str) -> Option<&'static [u8]> {
|
||||
ICONS.binary_search_by_key(&name, |(n, _)| n).ok().map(|i| ICONS[i].1)
|
||||
}
|
||||
|
||||
/// The names of the client's icons, sorted.
|
||||
pub fn client_icon_names() -> impl Iterator<Item = &'static str> {
|
||||
ICONS.iter().map(|(name, _)| *name)
|
||||
}
|
||||
|
||||
impl AssetSource for Assets {
|
||||
fn load(&self, path: &str) -> Result<Option<Cow<'static, [u8]>>> {
|
||||
if let Some(bytes) = path.strip_prefix("icons/").and_then(client_icon) {
|
||||
return Ok(Some(Cow::Borrowed(bytes)));
|
||||
}
|
||||
gpui_kit::assets::AllAssets.load(path)
|
||||
}
|
||||
|
||||
fn list(&self, path: &str) -> Result<Vec<SharedString>> {
|
||||
gpui_kit::assets::AllAssets.list(path)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn the_client_set_is_embedded_and_sorted() {
|
||||
assert!(ICONS.len() >= 140, "{} icons", ICONS.len());
|
||||
assert!(ICONS.windows(2).all(|pair| pair[0].0 < pair[1].0));
|
||||
for (name, bytes) in ICONS {
|
||||
assert!(std::str::from_utf8(bytes).is_ok_and(|text| text.contains("<svg")), "{name}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_client_icon_answers_before_gpui_kit_assets() {
|
||||
let name = client_icon_names().find(|n| *n == "mic.svg").expect("the client has a mic");
|
||||
let ours = client_icon(name).unwrap();
|
||||
let kit = gpui_kit::assets::AllAssets
|
||||
.load(&format!("icons/{name}"))
|
||||
.unwrap()
|
||||
.expect("gpui-kit-assets has a mic too");
|
||||
let served = Assets.load(&format!("icons/{name}")).unwrap().unwrap();
|
||||
assert_eq!(&*served, ours);
|
||||
assert_ne!(&*kit, ours, "Lucide 1.43 and 1.48 draw it differently, or this test is moot");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn other_icons_and_other_paths_fall_through_to_gpui_kit_assets() {
|
||||
let kit = gpui_kit::assets::AllAssets.list("icons/").unwrap();
|
||||
let only_in_kit = kit
|
||||
.iter()
|
||||
.find(|path| client_icon(path.trim_start_matches("icons/")).is_none())
|
||||
.expect("the catalogue has icons the client lacks");
|
||||
assert!(Assets.load(only_in_kit).unwrap().is_some(), "{only_in_kit}");
|
||||
// gpui-kit-assets answers a path it does not have with an error, so do we.
|
||||
assert!(Assets.load("icons/no-such-icon.svg").is_err());
|
||||
assert!(Assets.load("nothing/here").is_err());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
//! The development switches of the GPUI front end, read from the
|
||||
//! environment. They are the Slint front end's (docs/ui.md, "Development
|
||||
//! switches and screenshots") where the GPUI one has the same thing to
|
||||
//! switch, so that one recipe serves both; the rest are new.
|
||||
//!
|
||||
//! - `VOELIN_OPEN=swatch`: the swatch page (every theme token, a few
|
||||
//! components, the icons) in place of the shell. The Slint front end's
|
||||
//! other pages do not exist here yet; they are named in a warning and
|
||||
//! skipped.
|
||||
//! - `VOELIN_DEV_THEME=dark|light|system`: the theme mode, in place of the
|
||||
//! one the settings will give (`ui.theme` in the Slint front end).
|
||||
//! - `VOELIN_FONT_SCALE=1.25`: the text size factor (`ui.font_scale`).
|
||||
//! - `VOELIN_WINDOW_SIZE=1440x960`: the window's size.
|
||||
//! - `VOELIN_METER=1`: the cost meter, one log line a second
|
||||
//! ([`crate::meter`]).
|
||||
|
||||
use crate::theme::Choice;
|
||||
|
||||
/// A page the window can be opened on.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Page {
|
||||
/// The shell. Today an empty window with the state line.
|
||||
Shell,
|
||||
/// Every theme token, a few components and the icons.
|
||||
Swatch,
|
||||
}
|
||||
|
||||
/// What the environment switched.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Switches {
|
||||
/// The page to open on.
|
||||
pub open: Page,
|
||||
/// The theme mode, when the switch names one.
|
||||
pub theme: Option<Choice>,
|
||||
/// The text size factor, when the switch names one.
|
||||
pub font_scale: Option<f32>,
|
||||
/// The window's size in pixels, when the switch names one.
|
||||
pub window: Option<(f32, f32)>,
|
||||
/// Log the cost meter.
|
||||
pub meter: bool,
|
||||
}
|
||||
|
||||
impl Default for Switches {
|
||||
fn default() -> Self {
|
||||
Self { open: Page::Shell, theme: None, font_scale: None, window: None, meter: false }
|
||||
}
|
||||
}
|
||||
|
||||
impl Switches {
|
||||
/// The switches of this process's environment.
|
||||
pub fn from_env() -> Self {
|
||||
Self::parse(|name| std::env::var(name).ok())
|
||||
}
|
||||
|
||||
/// The switches `get` answers for; what it does not understand is logged
|
||||
/// and left out.
|
||||
pub fn parse(get: impl Fn(&str) -> Option<String>) -> Self {
|
||||
let mut switches = Self::default();
|
||||
if let Some(list) = get("VOELIN_OPEN") {
|
||||
for what in list.split(',').map(str::trim).filter(|w| !w.is_empty()) {
|
||||
match what {
|
||||
"swatch" => switches.open = Page::Swatch,
|
||||
other => tracing::warn!(
|
||||
"VOELIN_OPEN={other}: this page is not in the GPUI front end yet (swatch is)"
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(name) = get("VOELIN_DEV_THEME") {
|
||||
match Choice::parse(name.trim()) {
|
||||
Some(choice) => switches.theme = Some(choice),
|
||||
None => tracing::warn!("VOELIN_DEV_THEME={name}: dark, light or system"),
|
||||
}
|
||||
}
|
||||
if let Some(text) = get("VOELIN_FONT_SCALE") {
|
||||
match text.trim().parse::<f32>() {
|
||||
Ok(scale) if (0.5..=3.0).contains(&scale) => switches.font_scale = Some(scale),
|
||||
_ => tracing::warn!("VOELIN_FONT_SCALE={text}: a number from 0.5 to 3"),
|
||||
}
|
||||
}
|
||||
if let Some(text) = get("VOELIN_WINDOW_SIZE") {
|
||||
match parse_size(&text) {
|
||||
Some(size) => switches.window = Some(size),
|
||||
None => tracing::warn!("VOELIN_WINDOW_SIZE={text}: WIDTHxHEIGHT, such as 1440x960"),
|
||||
}
|
||||
}
|
||||
switches.meter = get("VOELIN_METER").is_some_and(|v| !matches!(v.trim(), "" | "0"));
|
||||
switches
|
||||
}
|
||||
}
|
||||
|
||||
/// `WIDTHxHEIGHT` in pixels, at least 320 by 240 and at most 16384 each way.
|
||||
fn parse_size(text: &str) -> Option<(f32, f32)> {
|
||||
let (w, h) = text.trim().split_once('x')?;
|
||||
let (w, h): (u32, u32) = (w.parse().ok()?, h.parse().ok()?);
|
||||
((320..=16384).contains(&w) && (240..=16384).contains(&h)).then_some((w as f32, h as f32))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::collections::HashMap;
|
||||
|
||||
use super::*;
|
||||
|
||||
fn env(pairs: &[(&str, &str)]) -> Switches {
|
||||
let map: HashMap<String, String> =
|
||||
pairs.iter().map(|(k, v)| ((*k).to_owned(), (*v).to_owned())).collect();
|
||||
Switches::parse(|name| map.get(name).cloned())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nothing_switched_is_the_shell_in_the_settings_theme() {
|
||||
assert_eq!(env(&[]), Switches::default());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_switch_is_read() {
|
||||
let s = env(&[
|
||||
("VOELIN_OPEN", "swatch"),
|
||||
("VOELIN_DEV_THEME", "light"),
|
||||
("VOELIN_FONT_SCALE", "1.25"),
|
||||
("VOELIN_WINDOW_SIZE", "1440x960"),
|
||||
("VOELIN_METER", "1"),
|
||||
]);
|
||||
assert_eq!(s.open, Page::Swatch);
|
||||
assert_eq!(s.theme, Some(Choice::Light));
|
||||
assert_eq!(s.font_scale, Some(1.25));
|
||||
assert_eq!(s.window, Some((1440.0, 960.0)));
|
||||
assert!(s.meter);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn what_makes_no_sense_is_left_out() {
|
||||
let s = env(&[
|
||||
("VOELIN_OPEN", "settings:voice,home"),
|
||||
("VOELIN_DEV_THEME", "blue"),
|
||||
("VOELIN_FONT_SCALE", "9"),
|
||||
("VOELIN_WINDOW_SIZE", "10x10"),
|
||||
("VOELIN_METER", "0"),
|
||||
]);
|
||||
assert_eq!(s, Switches::default());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
//! The engine this front end runs on, the same one the Slint front end
|
||||
//! hosts (`voelin_ui::HostedEngine`, `crates/voelin-ui/src/app.rs`): started
|
||||
//! on a tokio runtime, its events forwarded into a channel the window reads.
|
||||
//! The Slint crate cannot be a dependency here (it brings Slint in), so the
|
||||
//! few lines are repeated; both go into `voelin-ui-vm` when the Slint front
|
||||
//! end is retired.
|
||||
|
||||
use tokio::runtime::{Handle, Runtime};
|
||||
use tokio::sync::{broadcast, mpsc};
|
||||
use voelin_core::{Engine, Event};
|
||||
|
||||
/// An engine owned by the caller of [`crate::run`].
|
||||
pub struct HostedEngine {
|
||||
/// The handle: commands go in through it.
|
||||
pub engine: Engine,
|
||||
/// The runtime the engine runs on; the window's helpers run there too.
|
||||
pub runtime: Handle,
|
||||
/// The engine's events for the window: first those that rebuild the
|
||||
/// current state of every session, then new ones. Reading them needs no
|
||||
/// reactor, so the window's foreground executor can await it.
|
||||
pub events: mpsc::UnboundedReceiver<Event>,
|
||||
}
|
||||
|
||||
impl HostedEngine {
|
||||
/// A new engine on `runtime`, all of whose events go to the window.
|
||||
pub fn start(runtime: &Runtime) -> Self {
|
||||
let engine = runtime.block_on(async { Engine::start() });
|
||||
let (tx, events) = mpsc::unbounded_channel();
|
||||
let mut rx = engine.subscribe();
|
||||
runtime.spawn(async move {
|
||||
loop {
|
||||
match rx.recv().await {
|
||||
Ok(event) => {
|
||||
if tx.send(event).is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
Err(broadcast::error::RecvError::Lagged(_)) => continue,
|
||||
Err(_) => break,
|
||||
}
|
||||
}
|
||||
});
|
||||
Self { engine, runtime: runtime.handle().clone(), events }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
//! Inter, the UI font, as the Slint front end bundles it
|
||||
//! (`crates/voelin-ui/ui/assets/fonts`, OFL): the five files go into GPUI's
|
||||
//! text system and are used by family name ([`crate::theme::FONT_FAMILY`]),
|
||||
//! so nothing depends on what fontconfig finds for Latin text. Colour emoji
|
||||
//! come later (the chat slice; docs/design/gpui-spikes.md, "Open choices for step 3").
|
||||
|
||||
use std::borrow::Cow;
|
||||
|
||||
use gpui_kit::App;
|
||||
|
||||
/// The files of the family: regular, medium, semibold, bold, italic.
|
||||
const INTER: [&[u8]; 5] = [
|
||||
include_bytes!("../../voelin-ui/ui/assets/fonts/Inter-Regular.ttf"),
|
||||
include_bytes!("../../voelin-ui/ui/assets/fonts/Inter-Medium.ttf"),
|
||||
include_bytes!("../../voelin-ui/ui/assets/fonts/Inter-SemiBold.ttf"),
|
||||
include_bytes!("../../voelin-ui/ui/assets/fonts/Inter-Bold.ttf"),
|
||||
include_bytes!("../../voelin-ui/ui/assets/fonts/Inter-Italic.ttf"),
|
||||
];
|
||||
|
||||
/// Add Inter to GPUI's text system.
|
||||
pub fn load(cx: &mut App) {
|
||||
let fonts: Vec<Cow<'static, [u8]>> = INTER.iter().map(|bytes| Cow::Borrowed(*bytes)).collect();
|
||||
if let Err(error) = cx.text_system().add_fonts(fonts) {
|
||||
tracing::warn!(%error, "cannot add Inter to the text system");
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn the_files_are_fonts() {
|
||||
for bytes in INTER {
|
||||
assert!(bytes.len() > 100_000, "a font file, not {} bytes", bytes.len());
|
||||
assert!(matches!(&bytes[..4], [0, 1, 0, 0] | b"OTTO" | b"true"), "an sfnt header");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
//! The GPUI front end of the desktop app, under construction (plan section 6
|
||||
//! of the migration from Slint; docs/ui.md, "The GPUI front end"). The Slint
|
||||
//! front end (`voelin-ui`, the `voelin` binary) stays the app until this one
|
||||
//! reaches parity; both run on the same engine.
|
||||
|
||||
#![warn(missing_docs)]
|
||||
|
||||
pub mod app;
|
||||
pub mod assets;
|
||||
pub mod dev;
|
||||
pub mod engine;
|
||||
pub mod fonts;
|
||||
pub mod meter;
|
||||
pub mod swatch;
|
||||
pub mod theme;
|
||||
pub mod view;
|
||||
|
||||
use std::cell::{Cell, RefCell};
|
||||
use std::rc::Rc;
|
||||
use std::time::Duration;
|
||||
|
||||
use anyhow::{Context as _, Result};
|
||||
use gpui_kit::{App, AppContext as _, TitlebarOptions, WindowBounds, WindowOptions, px, size};
|
||||
use tracing_subscriber::{EnvFilter, fmt, prelude::*};
|
||||
|
||||
use crate::app::AppState;
|
||||
use crate::assets::Assets;
|
||||
use crate::dev::Switches;
|
||||
use crate::engine::HostedEngine;
|
||||
use crate::meter::Counters;
|
||||
use crate::theme::{Choice, VoelinTheme};
|
||||
use crate::view::MainView;
|
||||
|
||||
/// How long the engine gets, after the window closed, to act on the
|
||||
/// `CloseSession` commands the close sent (the Slint front end waits as long):
|
||||
/// its tasks run on the runtime, and shutting the runtime down drops them.
|
||||
const CLOSE_GRACE: Duration = Duration::from_millis(500);
|
||||
|
||||
/// What the log gets without `VOELIN_LOG` or `RUST_LOG`: warnings of every
|
||||
/// crate, this front end's information, and what GPUI says about the display
|
||||
/// and the GPU adapter it picked (which device a run used). Two warnings are
|
||||
/// left out because they are harmless: zbus's, as in the Slint front end (it
|
||||
/// warns when a desktop portal's request object is gone before it reads its
|
||||
/// properties), and GPUI's "failed to load font .SystemUIFont" (gpui-component
|
||||
/// asks for the platform's UI font, which Linux has no name for, before the
|
||||
/// theme names Inter; the text system falls back).
|
||||
const LOG_FILTER: &str =
|
||||
"warn,zbus=error,gpui::text_system=error,voelin_gpui=info,gpui_wgpu=info,gpui_linux=info";
|
||||
|
||||
/// Log to the terminal: `VOELIN_LOG`, else `RUST_LOG`, else [`LOG_FILTER`].
|
||||
/// GPUI logs through the `log` crate; the subscriber carries those records.
|
||||
pub fn init_logging() {
|
||||
let filter = EnvFilter::try_from_env("VOELIN_LOG")
|
||||
.or_else(|_| EnvFilter::try_from_default_env())
|
||||
.unwrap_or_else(|_| EnvFilter::new(LOG_FILTER));
|
||||
let _ = tracing_subscriber::registry()
|
||||
.with(fmt::layer().with_writer(std::io::stderr).with_filter(filter))
|
||||
.try_init();
|
||||
}
|
||||
|
||||
/// The main window's options: titled with the app's name, grouped by its id,
|
||||
/// centred, 1280 by 800 unless `VOELIN_WINDOW_SIZE` says otherwise.
|
||||
fn window_options(switches: &Switches, cx: &App) -> WindowOptions {
|
||||
let (width, height) = switches.window.unwrap_or((1280.0, 800.0));
|
||||
WindowOptions {
|
||||
titlebar: Some(TitlebarOptions {
|
||||
title: Some(voelin_platform::APP_NAME.into()),
|
||||
..Default::default()
|
||||
}),
|
||||
app_id: Some(voelin_platform::APP_ID.to_owned()),
|
||||
window_min_size: Some(size(px(640.0), px(480.0))),
|
||||
window_bounds: Some(WindowBounds::centered(size(px(width), px(height)), cx)),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// Open the main window on the root state; closing it leaves the servers and
|
||||
/// ends the app. `closed_sessions` is set to how many sessions the close told
|
||||
/// the engine to close, which [`run`] needs after GPUI's loop has ended.
|
||||
fn open_main_window(
|
||||
cx: &mut App,
|
||||
switches: &Switches,
|
||||
engine: HostedEngine,
|
||||
counters: Counters,
|
||||
closed_sessions: Rc<Cell<usize>>,
|
||||
) -> Result<()> {
|
||||
// Without a display server GPUI falls back to a headless platform, which
|
||||
// opens windows that draw nothing and runs until it is stopped.
|
||||
if cx.compositor_name() == "headless" {
|
||||
return Err(anyhow::anyhow!(
|
||||
"no display: neither DISPLAY nor WAYLAND_DISPLAY names a display server"
|
||||
))
|
||||
.context("cannot open the main window");
|
||||
}
|
||||
let HostedEngine { engine, events, .. } = engine;
|
||||
let app = cx.new({
|
||||
let counters = counters.clone();
|
||||
move |cx| AppState::new(Some(engine), events, counters, cx)
|
||||
});
|
||||
let options = window_options(switches, cx);
|
||||
let page = switches.open;
|
||||
gpui_kit::open_window(options, cx, {
|
||||
let app = app.clone();
|
||||
move |window, cx| {
|
||||
// The window's own appearance, which may differ from the system's before
|
||||
// the window exists.
|
||||
VoelinTheme::set_system_appearance(cx, window.appearance());
|
||||
window.on_window_should_close(cx, {
|
||||
let app = app.clone();
|
||||
move |_, cx| {
|
||||
closed_sessions.set(app.read(cx).shutdown());
|
||||
cx.quit();
|
||||
true
|
||||
}
|
||||
});
|
||||
cx.new(|cx| MainView::new(app, page, counters, window, cx))
|
||||
}
|
||||
})
|
||||
.context("cannot open the main window")?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Run the app on the current thread until its window closes.
|
||||
pub fn run() -> Result<()> {
|
||||
init_logging();
|
||||
let switches = Switches::from_env();
|
||||
tracing::info!(
|
||||
version = env!("CARGO_PKG_VERSION"),
|
||||
os = std::env::consts::OS,
|
||||
"Voelin (GPUI) starting"
|
||||
);
|
||||
let counters = Counters::default();
|
||||
if switches.meter {
|
||||
meter::start(counters.clone());
|
||||
}
|
||||
// The engine runs on tokio threads of its own; the window is GPUI's.
|
||||
let runtime = tokio::runtime::Builder::new_multi_thread()
|
||||
.enable_all()
|
||||
.build()
|
||||
.context("cannot start the engine's runtime")?;
|
||||
let hosted = HostedEngine::start(&runtime);
|
||||
let failure: Rc<RefCell<Option<anyhow::Error>>> = Rc::default();
|
||||
let closed_sessions: Rc<Cell<usize>> = Rc::default();
|
||||
gpui_kit::application().with_assets(Assets).run({
|
||||
let failure = failure.clone();
|
||||
let closed_sessions = closed_sessions.clone();
|
||||
move |cx| {
|
||||
gpui_kit::init(cx);
|
||||
fonts::load(cx);
|
||||
// Until the settings are read here (the shell slice), the mode and
|
||||
// the text size are the development switches' or the defaults.
|
||||
VoelinTheme::init(
|
||||
cx,
|
||||
switches.theme.unwrap_or(Choice::System),
|
||||
cx.window_appearance(),
|
||||
switches.font_scale.unwrap_or(1.0),
|
||||
);
|
||||
if let Err(e) = open_main_window(cx, &switches, hosted, counters, closed_sessions) {
|
||||
*failure.borrow_mut() = Some(e);
|
||||
// Not `cx.quit()` here: GPUI's Linux platform runs this callback
|
||||
// before it starts its event loop, and the loop forgets a stop
|
||||
// asked for earlier (calloop clears its stop signal when it
|
||||
// starts), so the process would stay with no window and no
|
||||
// message. A task runs inside the loop.
|
||||
cx.spawn(async move |cx| cx.update(|cx| cx.quit())).detach();
|
||||
}
|
||||
}
|
||||
});
|
||||
// The close told the engine to close the sessions; give its tasks time to
|
||||
// send that before the runtime drops them (`shutdown_timeout` waits for
|
||||
// blocking tasks only), as the Slint front end does, or ghost clients stay
|
||||
// on the servers until they time out. Any other way to end the app that
|
||||
// the slices add must call `AppState::shutdown` too.
|
||||
if closed_sessions.get() > 0 {
|
||||
runtime.block_on(tokio::time::sleep(CLOSE_GRACE));
|
||||
}
|
||||
runtime.shutdown_timeout(Duration::from_secs(2));
|
||||
match failure.take() {
|
||||
Some(e) => Err(e),
|
||||
None => Ok(()),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
//! `voelin-gpui`: the GPUI front end of the desktop app (docs/ui.md, "The
|
||||
//! GPUI front end").
|
||||
|
||||
fn main() -> anyhow::Result<()> {
|
||||
voelin_gpui::run()
|
||||
}
|
||||
@@ -0,0 +1,303 @@
|
||||
//! What the app costs, once a second, in the log: the CPU of the process and
|
||||
//! of each group of threads, the resident memory, and the app's own counters
|
||||
//! (a development switch, `VOELIN_METER=1`, so that every slice can say what
|
||||
//! it costs). It is `spike_common::meter` of the GPUI spikes
|
||||
//! (`spikes/gpui/common/src/meter.rs`, docs/design/gpui-spikes.md) without the
|
||||
//! measuring run's summary and exit, writing log lines instead of JSON.
|
||||
//!
|
||||
//! CPU is in percent of one core (200 means two cores busy). Threads are
|
||||
//! grouped by name without a trailing number (`llvmpipe-12` becomes
|
||||
//! `llvmpipe`), which tells the software renderer's share (Mesa's `llvmpipe-*`
|
||||
//! threads, work a GPU would take over) from GPUI's thread, the engine's
|
||||
//! runtime and the codecs. The numbers come from `/proc/self`: on other
|
||||
//! systems the meter says it cannot read them and stops.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::fmt::Write as _;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
/// A number the app counts up (events handled, frames drawn) or sets (open
|
||||
/// connections); the meter reports counters per second and gauges as they
|
||||
/// are.
|
||||
#[derive(Clone, Default, Debug)]
|
||||
pub struct Counter(Arc<AtomicU64>);
|
||||
|
||||
impl Counter {
|
||||
/// Add one.
|
||||
pub fn incr(&self) {
|
||||
self.0.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
/// Set (gauges).
|
||||
pub fn set(&self, value: u64) {
|
||||
self.0.store(value, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
/// The current value.
|
||||
pub fn get(&self) -> u64 {
|
||||
self.0.load(Ordering::Relaxed)
|
||||
}
|
||||
}
|
||||
|
||||
/// The app's own numbers the meter reports besides the process's.
|
||||
#[derive(Clone, Default, Debug)]
|
||||
pub struct Counters {
|
||||
/// Engine events handled by the root state (per second).
|
||||
pub engine_events: Counter,
|
||||
/// One-second ticks of the root state (per second: 1).
|
||||
pub ticks: Counter,
|
||||
/// Windows drawn (frames, per second).
|
||||
pub renders: Counter,
|
||||
/// Jobs other threads handed to the foreground through
|
||||
/// [`crate::app::Later`] (per second).
|
||||
pub later_jobs: Counter,
|
||||
/// Voice connections that are up (a gauge).
|
||||
pub connections: Counter,
|
||||
}
|
||||
|
||||
/// CPU ticks of the process and of each thread group, and the resident
|
||||
/// memory, at one moment.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Snapshot {
|
||||
at: Instant,
|
||||
process: u64,
|
||||
threads: BTreeMap<String, u64>,
|
||||
rss_bytes: u64,
|
||||
}
|
||||
|
||||
/// The size of a page of memory, for `statm`'s page counts.
|
||||
#[cfg(target_os = "linux")]
|
||||
fn page_size() -> u64 {
|
||||
rustix::param::page_size() as u64
|
||||
}
|
||||
|
||||
/// The size of a page of memory (Linux only matters: `/proc`).
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
fn page_size() -> u64 {
|
||||
4096
|
||||
}
|
||||
|
||||
/// The unit of the CPU times in `stat`.
|
||||
#[cfg(target_os = "linux")]
|
||||
fn clock_ticks_per_second() -> u64 {
|
||||
rustix::param::clock_ticks_per_second()
|
||||
}
|
||||
|
||||
/// The unit of the CPU times in `stat` (Linux only matters: `/proc`).
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
fn clock_ticks_per_second() -> u64 {
|
||||
100
|
||||
}
|
||||
|
||||
/// `utime + stime` and the name of a `/proc/.../stat` line.
|
||||
fn ticks_of(stat: &str) -> Option<(String, u64)> {
|
||||
let open = stat.find('(')?;
|
||||
let close = stat.rfind(')')?;
|
||||
let name = stat.get(open + 1..close)?.to_owned();
|
||||
let fields: Vec<&str> = stat.get(close + 1..)?.split_whitespace().collect();
|
||||
// Fields 14 and 15 of proc(5); the remainder starts at field 3.
|
||||
let utime: u64 = fields.get(11)?.parse().ok()?;
|
||||
let stime: u64 = fields.get(12)?.parse().ok()?;
|
||||
Some((name, utime + stime))
|
||||
}
|
||||
|
||||
/// A thread's group: its name without a trailing number or separator.
|
||||
pub fn group_of(name: &str) -> String {
|
||||
let trimmed = name.trim_end_matches(|c: char| c.is_ascii_digit());
|
||||
let trimmed = trimmed.trim_end_matches(['-', '_', ':', ' ', '#']);
|
||||
if trimmed.is_empty() { name.to_owned() } else { trimmed.to_owned() }
|
||||
}
|
||||
|
||||
impl Snapshot {
|
||||
/// Read `/proc/self` now; `None` where there is none.
|
||||
pub fn now() -> Option<Self> {
|
||||
let process = std::fs::read_to_string("/proc/self/stat").ok().and_then(|s| ticks_of(&s))?.1;
|
||||
let mut threads = BTreeMap::new();
|
||||
if let Ok(dir) = std::fs::read_dir("/proc/self/task") {
|
||||
for entry in dir.flatten() {
|
||||
let Ok(stat) = std::fs::read_to_string(entry.path().join("stat")) else { continue };
|
||||
if let Some((name, ticks)) = ticks_of(&stat) {
|
||||
*threads.entry(group_of(&name)).or_insert(0) += ticks;
|
||||
}
|
||||
}
|
||||
}
|
||||
let rss_bytes = std::fs::read_to_string("/proc/self/statm")
|
||||
.ok()
|
||||
.and_then(|s| s.split_whitespace().nth(1)?.parse::<u64>().ok())
|
||||
.map_or(0, |pages| pages * page_size());
|
||||
Some(Self { at: Instant::now(), process, threads, rss_bytes })
|
||||
}
|
||||
|
||||
/// Resident memory in MiB.
|
||||
pub fn rss_mib(&self) -> f64 {
|
||||
self.rss_bytes as f64 / (1024.0 * 1024.0)
|
||||
}
|
||||
}
|
||||
|
||||
/// CPU in percent of one core between two snapshots: the process's and each
|
||||
/// thread group's that used any (groups that exited in between count from
|
||||
/// zero).
|
||||
pub fn cpu_between(a: &Snapshot, b: &Snapshot) -> (f64, BTreeMap<String, f64>) {
|
||||
let hz = clock_ticks_per_second() as f64;
|
||||
let secs = b.at.duration_since(a.at).as_secs_f64().max(1e-6);
|
||||
let pct = |ticks: u64| ticks as f64 / hz / secs * 100.0;
|
||||
let process = pct(b.process.saturating_sub(a.process));
|
||||
let threads = b
|
||||
.threads
|
||||
.iter()
|
||||
.map(|(name, &t)| (name.clone(), pct(t.saturating_sub(*a.threads.get(name).unwrap_or(&0)))))
|
||||
.filter(|(_, p)| *p > 0.0)
|
||||
.collect();
|
||||
(process, threads)
|
||||
}
|
||||
|
||||
/// One second of the meter as a log line: `cpu 42.0% rss 210.4 MiB threads
|
||||
/// llvmpipe 31.0 main 5.0 | engine_events 0.0/s ... | connections 1`.
|
||||
pub fn line(
|
||||
cpu: f64,
|
||||
rss_mib: f64,
|
||||
threads: &BTreeMap<String, f64>,
|
||||
rates: &[(&str, f64)],
|
||||
gauges: &[(&str, u64)],
|
||||
) -> String {
|
||||
let mut text = format!("cpu {cpu:.1}% rss {rss_mib:.1} MiB");
|
||||
// The busiest groups first; a thread group under 0.5 % is noise.
|
||||
let mut busy: Vec<(&String, &f64)> = threads.iter().filter(|(_, p)| **p >= 0.5).collect();
|
||||
busy.sort_by(|a, b| b.1.total_cmp(a.1).then_with(|| a.0.cmp(b.0)));
|
||||
if !busy.is_empty() {
|
||||
text.push_str(" | threads");
|
||||
for (name, pct) in busy {
|
||||
let _ = write!(text, " {name} {pct:.1}");
|
||||
}
|
||||
}
|
||||
text.push_str(" |");
|
||||
for (name, rate) in rates {
|
||||
let _ = write!(text, " {name} {rate:.1}/s");
|
||||
}
|
||||
if !gauges.is_empty() {
|
||||
text.push_str(" |");
|
||||
for (name, value) in gauges {
|
||||
let _ = write!(text, " {name} {value}");
|
||||
}
|
||||
}
|
||||
text
|
||||
}
|
||||
|
||||
/// Start the meter on a thread of its own: once a second, a log line (target
|
||||
/// `voelin_gpui::meter`, level info) with the process's CPU and memory and
|
||||
/// `counters`' rates. It ends with the process.
|
||||
pub fn start(counters: Counters) {
|
||||
let spawned = std::thread::Builder::new().name("voelin-meter".into()).spawn(move || {
|
||||
let Some(mut last) = Snapshot::now() else {
|
||||
tracing::warn!(target: "voelin_gpui::meter", "the meter reads /proc/self; there is none here");
|
||||
return;
|
||||
};
|
||||
let rated = [
|
||||
("engine_events", counters.engine_events.clone()),
|
||||
("ticks", counters.ticks.clone()),
|
||||
("renders", counters.renders.clone()),
|
||||
("later_jobs", counters.later_jobs.clone()),
|
||||
];
|
||||
let mut last_counts: Vec<u64> = rated.iter().map(|(_, c)| c.get()).collect();
|
||||
tracing::info!(target: "voelin_gpui::meter", "meter on: one line a second (VOELIN_METER)");
|
||||
loop {
|
||||
std::thread::sleep(Duration::from_secs(1));
|
||||
let Some(now) = Snapshot::now() else { return };
|
||||
let secs = now.at.duration_since(last.at).as_secs_f64().max(1e-6);
|
||||
let (cpu, threads) = cpu_between(&last, &now);
|
||||
let counts: Vec<u64> = rated.iter().map(|(_, c)| c.get()).collect();
|
||||
let rates: Vec<(&str, f64)> = rated
|
||||
.iter()
|
||||
.zip(counts.iter().zip(&last_counts))
|
||||
.map(|((name, _), (c, l))| (*name, c.saturating_sub(*l) as f64 / secs))
|
||||
.collect();
|
||||
let gauges = [("connections", counters.connections.get())];
|
||||
tracing::info!(
|
||||
target: "voelin_gpui::meter",
|
||||
"{}",
|
||||
line(cpu, now.rss_mib(), &threads, &rates, &gauges)
|
||||
);
|
||||
last = now;
|
||||
last_counts = counts;
|
||||
}
|
||||
});
|
||||
if let Err(error) = spawned {
|
||||
tracing::warn!(target: "voelin_gpui::meter", %error, "no meter thread");
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn groups_drop_trailing_numbers() {
|
||||
assert_eq!(group_of("llvmpipe-12"), "llvmpipe");
|
||||
assert_eq!(group_of("tokio-runtime-w"), "tokio-runtime-w");
|
||||
assert_eq!(group_of("voelin-meter"), "voelin-meter");
|
||||
assert_eq!(group_of("1234"), "1234");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stat_lines_parse_with_spaces_in_names() {
|
||||
let line = "42 (a b) c) S 1 2 3 4 5 6 7 8 9 10 100 23 0 0 20 0 1 0 0";
|
||||
assert_eq!(ticks_of(line), Some(("a b) c".to_owned(), 123)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_line_names_the_busiest_threads_first_and_hides_the_idle_ones() {
|
||||
let threads = BTreeMap::from([
|
||||
("main".to_owned(), 5.04),
|
||||
("llvmpipe".to_owned(), 310.0),
|
||||
("idle".to_owned(), 0.2),
|
||||
]);
|
||||
let text = line(
|
||||
317.0,
|
||||
210.44,
|
||||
&threads,
|
||||
&[("engine_events", 0.0), ("renders", 59.96)],
|
||||
&[("connections", 1)],
|
||||
);
|
||||
assert_eq!(
|
||||
text,
|
||||
"cpu 317.0% rss 210.4 MiB | threads llvmpipe 310.0 main 5.0 | engine_events 0.0/s renders 60.0/s | connections 1"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn this_process_can_be_read_on_linux() {
|
||||
if !cfg!(target_os = "linux") {
|
||||
return;
|
||||
}
|
||||
let a = Snapshot::now().expect("/proc/self");
|
||||
// The kernel counts a process's CPU in ticks of 10 ms, and on a busy
|
||||
// machine this thread gets a tick's worth of CPU only after a long wall
|
||||
// time: burn CPU until a second reading shows the process's ticks above
|
||||
// the first, and in a thread group (the process's total and a thread's
|
||||
// own are rounded separately). The deadline only ends a hang
|
||||
// (docs/testing/load.md); it never decides the result.
|
||||
let deadline = Instant::now() + Duration::from_secs(30);
|
||||
let (b, cpu) = loop {
|
||||
let burn = Instant::now();
|
||||
let mut x = 0u64;
|
||||
while burn.elapsed() < Duration::from_millis(2) {
|
||||
x = x.wrapping_mul(31).wrapping_add(7);
|
||||
}
|
||||
std::hint::black_box(x);
|
||||
let b = Snapshot::now().expect("/proc/self");
|
||||
let (cpu, threads) = cpu_between(&a, &b);
|
||||
if b.process > a.process && !threads.is_empty() {
|
||||
break (b, cpu);
|
||||
}
|
||||
assert!(
|
||||
Instant::now() < deadline,
|
||||
"no CPU tick showed in 30 s: {} -> {}",
|
||||
a.process,
|
||||
b.process
|
||||
);
|
||||
};
|
||||
assert!(cpu > 0.0 && b.rss_mib() > 1.0, "{cpu} {}", b.rss_mib());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,389 @@
|
||||
//! The swatch page: every colour token of the theme with its name and value,
|
||||
//! the radii, the spacing, the type scale, a few gpui-component widgets (drawn
|
||||
//! from the second layer of the theme) and the client's icons, in the mode
|
||||
//! the theme is in. A development page (`VOELIN_OPEN=swatch`): the screenshots
|
||||
//! of a theme change, and what the screenshots in docs/ui/ show.
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use gpui_kit::component::button::{Button, ButtonVariants as _};
|
||||
use gpui_kit::component::checkbox::Checkbox;
|
||||
use gpui_kit::component::switch::Switch;
|
||||
use gpui_kit::{
|
||||
FontWeight, InteractiveElement as _, IntoElement, ParentElement as _,
|
||||
StatefulInteractiveElement as _, Styled as _, div, px, svg,
|
||||
};
|
||||
|
||||
use crate::theme::{VoelinTheme, hsla, tokens::Rgba};
|
||||
|
||||
/// The colour tokens by the groups of docs/ui.md's "Theme tokens" table.
|
||||
pub const GROUPS: [(&str, &[&str]); 6] = [
|
||||
(
|
||||
"Backgrounds",
|
||||
&[
|
||||
"bg-app",
|
||||
"bg-rail",
|
||||
"surface",
|
||||
"surface-2",
|
||||
"surface-3",
|
||||
"surface-4",
|
||||
"scrim",
|
||||
"scrim-light",
|
||||
"overlay",
|
||||
],
|
||||
),
|
||||
("Lines", &["border", "border-strong", "border-popup", "glow"]),
|
||||
(
|
||||
"Accent",
|
||||
&[
|
||||
"accent",
|
||||
"accent-hover",
|
||||
"accent-pressed",
|
||||
"accent-soft",
|
||||
"accent-soft-hover",
|
||||
"accent-text",
|
||||
"name-text",
|
||||
"on-accent",
|
||||
],
|
||||
),
|
||||
(
|
||||
"States",
|
||||
&[
|
||||
"live",
|
||||
"live-soft",
|
||||
"danger",
|
||||
"danger-soft",
|
||||
"success",
|
||||
"success-soft",
|
||||
"warning",
|
||||
"warning-soft",
|
||||
"idle",
|
||||
"dnd",
|
||||
"offline",
|
||||
"gold",
|
||||
"info",
|
||||
],
|
||||
),
|
||||
("Text", &["text", "text-secondary", "text-muted", "text-disabled", "icon"]),
|
||||
("Meter", &["meter-low", "meter-mid", "meter-high", "meter-off"]),
|
||||
];
|
||||
|
||||
/// Icons shown, by the name of the client's file.
|
||||
const ICONS: [&str; 16] = [
|
||||
"mic.svg",
|
||||
"mic-off.svg",
|
||||
"headphones.svg",
|
||||
"volume-2.svg",
|
||||
"settings.svg",
|
||||
"search.svg",
|
||||
"bell.svg",
|
||||
"users.svg",
|
||||
"message-square.svg",
|
||||
"monitor-up.svg",
|
||||
"hash.svg",
|
||||
"lock.svg",
|
||||
"crown.svg",
|
||||
"plus.svg",
|
||||
"x.svg",
|
||||
"check.svg",
|
||||
];
|
||||
|
||||
fn heading(theme: &VoelinTheme, text: &str) -> impl IntoElement {
|
||||
let m = &theme.metrics;
|
||||
div()
|
||||
.text_size(px(m.font_md))
|
||||
.font_weight(FontWeight::SEMIBOLD)
|
||||
.text_color(hsla(theme.colors.text))
|
||||
.child(text.to_owned())
|
||||
}
|
||||
|
||||
fn chip(theme: &VoelinTheme, name: &str, color: Rgba) -> impl IntoElement {
|
||||
let (c, m) = (&theme.colors, &theme.metrics);
|
||||
div()
|
||||
.w(px(100.0))
|
||||
.flex()
|
||||
.flex_col()
|
||||
.gap(px(2.0))
|
||||
.child(
|
||||
div()
|
||||
.h(px(24.0))
|
||||
.rounded(px(m.radius_xs))
|
||||
.border_1()
|
||||
.border_color(hsla(c.border_strong))
|
||||
.bg(hsla(color)),
|
||||
)
|
||||
.child(
|
||||
div()
|
||||
.text_size(px(m.font_xs))
|
||||
.text_color(hsla(c.text_secondary))
|
||||
.child(name.to_owned()),
|
||||
)
|
||||
.child(
|
||||
div().text_size(px(m.font_xs)).text_color(hsla(c.text_muted)).child(color.to_string()),
|
||||
)
|
||||
}
|
||||
|
||||
fn colours(theme: &VoelinTheme) -> impl IntoElement {
|
||||
let (c, m) = (&theme.colors, &theme.metrics);
|
||||
let by_name: HashMap<&str, Rgba> = c.entries().into_iter().collect();
|
||||
let mut column = div().flex().flex_col().gap(px(m.space_4));
|
||||
for (group, names) in GROUPS {
|
||||
let mut row = div().flex().flex_row().flex_wrap().gap(px(m.space_3));
|
||||
for name in names {
|
||||
row = row.child(chip(theme, name, by_name[name]));
|
||||
}
|
||||
column = column.child(
|
||||
div().flex().flex_col().gap(px(m.space_2)).child(heading(theme, group)).child(row),
|
||||
);
|
||||
}
|
||||
column
|
||||
}
|
||||
|
||||
fn radii(theme: &VoelinTheme) -> impl IntoElement {
|
||||
let (c, m) = (&theme.colors, &theme.metrics);
|
||||
let mut row = div().flex().flex_row().gap(px(m.space_4));
|
||||
for (name, radius) in [
|
||||
("xs", m.radius_xs),
|
||||
("sm", m.radius_sm),
|
||||
("md", m.radius_md),
|
||||
("lg", m.radius_lg),
|
||||
("xl", m.radius_xl),
|
||||
("pill", m.radius_pill),
|
||||
] {
|
||||
row = row.child(
|
||||
div()
|
||||
.flex()
|
||||
.flex_col()
|
||||
.items_center()
|
||||
.gap(px(m.space_2))
|
||||
.child(
|
||||
div()
|
||||
.size(px(40.0))
|
||||
.rounded(px(radius))
|
||||
.bg(hsla(c.surface_4))
|
||||
.border_1()
|
||||
.border_color(hsla(c.border_popup)),
|
||||
)
|
||||
.child(div().text_size(px(m.font_xs)).text_color(hsla(c.text_muted)).child(name)),
|
||||
);
|
||||
}
|
||||
div().flex().flex_col().gap(px(m.space_3)).child(heading(theme, "Radii")).child(row)
|
||||
}
|
||||
|
||||
fn spacing(theme: &VoelinTheme) -> impl IntoElement {
|
||||
let (c, m) = (&theme.colors, &theme.metrics);
|
||||
let mut rows = div().flex().flex_col().gap(px(m.space_1));
|
||||
for (name, space) in [
|
||||
("space-1", m.space_1),
|
||||
("space-2", m.space_2),
|
||||
("space-3", m.space_3),
|
||||
("space-4", m.space_4),
|
||||
("space-5", m.space_5),
|
||||
("space-6", m.space_6),
|
||||
("space-7", m.space_7),
|
||||
("space-8", m.space_8),
|
||||
] {
|
||||
rows = rows.child(
|
||||
div()
|
||||
.flex()
|
||||
.flex_row()
|
||||
.items_center()
|
||||
.gap(px(m.space_3))
|
||||
.child(
|
||||
div()
|
||||
.w(px(56.0))
|
||||
.text_size(px(m.font_xs))
|
||||
.text_color(hsla(c.text_muted))
|
||||
.child(name),
|
||||
)
|
||||
.child(div().h(px(6.0)).w(px(space * 4.0)).rounded(px(2.0)).bg(hsla(c.accent)))
|
||||
.child(
|
||||
div()
|
||||
.text_size(px(m.font_xs))
|
||||
.text_color(hsla(c.text_muted))
|
||||
.child(format!("{space} px")),
|
||||
),
|
||||
);
|
||||
}
|
||||
div().flex().flex_col().gap(px(m.space_3)).child(heading(theme, "Spacing")).child(rows)
|
||||
}
|
||||
|
||||
fn type_scale(theme: &VoelinTheme) -> impl IntoElement {
|
||||
let (c, m) = (&theme.colors, &theme.metrics);
|
||||
let mut rows = div().flex().flex_col();
|
||||
for (name, size, weight) in [
|
||||
("font-3xl", m.font_3xl, FontWeight::BOLD),
|
||||
("font-2xl", m.font_2xl, FontWeight::SEMIBOLD),
|
||||
("font-xl", m.font_xl, FontWeight::SEMIBOLD),
|
||||
("font-lg", m.font_lg, FontWeight::MEDIUM),
|
||||
("font-md", m.font_md, FontWeight::MEDIUM),
|
||||
("font-body", m.font_body, FontWeight::NORMAL),
|
||||
("font-sm", m.font_sm, FontWeight::NORMAL),
|
||||
("font-xs", m.font_xs, FontWeight::NORMAL),
|
||||
] {
|
||||
rows = rows.child(
|
||||
div()
|
||||
.text_size(px(size))
|
||||
.font_weight(weight)
|
||||
.text_color(hsla(c.text))
|
||||
.child(format!("{name} {size}: Raid tonight at 21:00")),
|
||||
);
|
||||
}
|
||||
div().flex().flex_col().gap(px(m.space_3)).child(heading(theme, "Type")).child(rows)
|
||||
}
|
||||
|
||||
fn components(theme: &VoelinTheme) -> impl IntoElement {
|
||||
let m = &theme.metrics;
|
||||
div()
|
||||
.flex()
|
||||
.flex_col()
|
||||
.gap(px(m.space_3))
|
||||
.child(heading(theme, "Components (gpui-component, through ThemeColor)"))
|
||||
.child(
|
||||
div()
|
||||
.flex()
|
||||
.flex_row()
|
||||
.flex_wrap()
|
||||
.gap(px(m.space_3))
|
||||
.child(Button::new("primary").primary().label("Primary"))
|
||||
.child(Button::new("secondary").label("Secondary"))
|
||||
.child(Button::new("danger").danger().label("Danger"))
|
||||
.child(Button::new("success").success().label("Success"))
|
||||
.child(Button::new("warning").warning().label("Warning"))
|
||||
.child(Button::new("info").info().label("Info")),
|
||||
)
|
||||
.child(
|
||||
div()
|
||||
.flex()
|
||||
.flex_row()
|
||||
.items_center()
|
||||
.gap(px(m.space_5))
|
||||
.child(Switch::new("on").checked(true))
|
||||
.child(Switch::new("off").checked(false))
|
||||
.child(Checkbox::new("checked").checked(true).label("Checked"))
|
||||
.child(Checkbox::new("unchecked").checked(false).label("Unchecked")),
|
||||
)
|
||||
}
|
||||
|
||||
fn backdrop(theme: &VoelinTheme) -> impl IntoElement {
|
||||
let (c, m, b) = (&theme.colors, &theme.metrics, &theme.backdrop);
|
||||
let [first, _, last] = b.stops;
|
||||
div().flex().flex_col().gap(px(m.space_3)).child(heading(theme, "Backdrop")).child(
|
||||
div()
|
||||
.h(px(36.0))
|
||||
.rounded(px(m.radius_md))
|
||||
.border_1()
|
||||
.border_color(hsla(c.border))
|
||||
.bg(b.to_gpui())
|
||||
.px(px(m.space_3))
|
||||
.py(px(m.space_2))
|
||||
.text_size(px(m.font_xs))
|
||||
.text_color(hsla(c.text_secondary))
|
||||
.child(format!(
|
||||
"{}deg: {} to {}; the middle stop, {} at {}%, is not drawn",
|
||||
b.angle,
|
||||
first.0,
|
||||
last.0,
|
||||
b.stops[1].0,
|
||||
(b.stops[1].1 * 100.0).round()
|
||||
)),
|
||||
)
|
||||
}
|
||||
|
||||
fn icons(theme: &VoelinTheme) -> impl IntoElement {
|
||||
let (c, m) = (&theme.colors, &theme.metrics);
|
||||
let mut row = div().flex().flex_row().flex_wrap().gap(px(m.space_5));
|
||||
for name in ICONS {
|
||||
row = row.child(
|
||||
svg().path(format!("icons/{name}")).size(px(m.icon_lg)).text_color(hsla(c.icon)),
|
||||
);
|
||||
}
|
||||
div()
|
||||
.flex()
|
||||
.flex_col()
|
||||
.gap(px(m.space_3))
|
||||
.child(heading(theme, "Icons (the client's Lucide 1.48, as gpui-component's icons/ paths)"))
|
||||
.child(row)
|
||||
}
|
||||
|
||||
/// The page: the colours on the left, the rest on the right; it scrolls when
|
||||
/// the window is smaller than it.
|
||||
pub fn swatch(theme: &VoelinTheme) -> impl IntoElement {
|
||||
let (c, m) = (&theme.colors, &theme.metrics);
|
||||
div()
|
||||
.id("swatch")
|
||||
.size_full()
|
||||
.overflow_y_scroll()
|
||||
.flex()
|
||||
.flex_col()
|
||||
.gap(px(m.space_4))
|
||||
.p(px(m.space_6))
|
||||
.bg(hsla(c.bg_app))
|
||||
.child(
|
||||
div()
|
||||
.flex()
|
||||
.flex_row()
|
||||
.items_baseline()
|
||||
.gap(px(m.space_4))
|
||||
.child(
|
||||
div()
|
||||
.text_size(px(m.font_2xl))
|
||||
.font_weight(FontWeight::BOLD)
|
||||
.text_color(hsla(c.text))
|
||||
.child("Voelin theme"),
|
||||
)
|
||||
.child(div().text_size(px(m.font_sm)).text_color(hsla(c.text_muted)).child(
|
||||
format!(
|
||||
"{} (setting {}), text size {}",
|
||||
if theme.is_dark() { "dark" } else { "light" },
|
||||
theme.choice().name(),
|
||||
m.font_scale
|
||||
),
|
||||
)),
|
||||
)
|
||||
.child(
|
||||
div()
|
||||
.flex()
|
||||
.flex_row()
|
||||
.gap(px(m.space_8))
|
||||
.child(div().w(px(752.0)).flex_none().child(colours(theme)))
|
||||
.child(
|
||||
div()
|
||||
.w(px(600.0))
|
||||
.flex()
|
||||
.flex_col()
|
||||
.gap(px(m.space_4))
|
||||
.child(backdrop(theme))
|
||||
.child(radii(theme))
|
||||
.child(spacing(theme))
|
||||
.child(type_scale(theme))
|
||||
.child(components(theme))
|
||||
.child(icons(theme)),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
use super::*;
|
||||
use crate::assets::client_icon;
|
||||
use crate::theme::Palette;
|
||||
|
||||
#[test]
|
||||
fn every_colour_token_is_in_exactly_one_group() {
|
||||
let shown: Vec<&str> = GROUPS.iter().flat_map(|(_, names)| names.iter().copied()).collect();
|
||||
let unique: BTreeSet<&str> = shown.iter().copied().collect();
|
||||
assert_eq!(shown.len(), unique.len(), "a token in two groups");
|
||||
let tokens: BTreeSet<&str> = Palette::DARK.entries().into_iter().map(|(n, _)| n).collect();
|
||||
assert_eq!(unique, tokens);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_icons_shown_are_the_clients() {
|
||||
for name in ICONS {
|
||||
assert!(client_icon(name).is_some(), "{name}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,278 @@
|
||||
//! The second layer of the theme: the colours gpui-component's widgets read,
|
||||
//! written from the Voelin palette. gpui-component's `ThemeColor` is shadcn's
|
||||
//! vocabulary (about 135 colours: a background, a primary, a muted, one set
|
||||
//! for the list, one for the table, one for each kind of button); the
|
||||
//! client's tokens map onto it as docs/ui.md ("The GPUI front end") lists.
|
||||
//! What has no counterpart stays as the registered theme of the mode has it
|
||||
//! (charts' bullish and bearish colours, the cyan and magenta of the base
|
||||
//! palette).
|
||||
//!
|
||||
//! gpui-component's "accent" is a hover background, not a brand colour: the
|
||||
//! client's `accent` is its `primary`.
|
||||
|
||||
use gpui_kit::Hsla;
|
||||
use gpui_kit::component::ThemeColor;
|
||||
|
||||
use super::tokens::{Palette, Rgba};
|
||||
|
||||
/// A palette colour as GPUI's.
|
||||
pub fn hsla(color: Rgba) -> Hsla {
|
||||
gpui_kit::rgba(color.0).into()
|
||||
}
|
||||
|
||||
/// Of `base`, the colours a status button needs: hover, active, and a text
|
||||
/// that reads on it (white or the window's ink, whichever contrasts more).
|
||||
struct Status {
|
||||
base: Hsla,
|
||||
hover: Hsla,
|
||||
active: Hsla,
|
||||
foreground: Hsla,
|
||||
}
|
||||
|
||||
fn status(base: Rgba, ink: Rgba, dark: bool) -> Status {
|
||||
let toward_hover = if dark { Rgba(0xffff_ffff) } else { Rgba(0x0000_00ff) };
|
||||
Status {
|
||||
base: hsla(base),
|
||||
hover: hsla(base.mix(toward_hover, 0.14)),
|
||||
active: hsla(base.mix(Rgba(0x0000_00ff), 0.18)),
|
||||
foreground: hsla(base.readable(ink)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Write the palette's colours into `colors`, over what the registered theme
|
||||
/// of the mode left there. Every field that gpui-component's themes derive
|
||||
/// from another (the buttons fall back to `primary`, `danger`, ...) is written
|
||||
/// too, so that none keeps the default theme's blue.
|
||||
pub fn write(p: &Palette, dark: bool, colors: &mut ThemeColor) {
|
||||
let c = colors;
|
||||
let h = hsla;
|
||||
let clear = Hsla::transparent_black();
|
||||
|
||||
// The window and its text.
|
||||
c.background = h(p.bg_app);
|
||||
c.foreground = h(p.text);
|
||||
c.border = h(p.border);
|
||||
c.input = h(p.border_strong);
|
||||
c.ring = h(p.glow);
|
||||
c.overlay = h(p.scrim);
|
||||
c.window_border = h(p.border);
|
||||
c.caret = h(p.text);
|
||||
c.selection = h(p.accent_soft);
|
||||
c.drag_border = h(p.accent);
|
||||
c.drop_target = h(p.accent_soft);
|
||||
|
||||
// Links: one colour for all three states, as the client has one.
|
||||
c.link = h(p.accent_text);
|
||||
c.link_hover = h(p.accent_text);
|
||||
c.link_active = h(p.accent_text);
|
||||
|
||||
// The brand colour, and gpui-component's hover "accent".
|
||||
c.primary = h(p.accent);
|
||||
c.primary_hover = h(p.accent_hover);
|
||||
c.primary_active = h(p.accent_pressed);
|
||||
c.primary_foreground = h(p.on_accent);
|
||||
c.accent = h(p.surface_3);
|
||||
c.accent_foreground = h(p.text);
|
||||
|
||||
// Cards, inputs, menus, popovers.
|
||||
c.secondary = h(p.surface_2);
|
||||
c.secondary_hover = h(p.surface_3);
|
||||
c.secondary_active = h(p.surface_4);
|
||||
c.secondary_foreground = h(p.text);
|
||||
c.muted = h(p.surface_2);
|
||||
c.muted_foreground = h(p.text_muted);
|
||||
c.popover = h(p.surface_3);
|
||||
c.popover_foreground = h(p.text);
|
||||
c.group_box = h(p.surface_2);
|
||||
c.group_box_foreground = h(p.text);
|
||||
c.accordion = h(p.surface_2);
|
||||
c.description_list_label = h(p.surface_2);
|
||||
c.description_list_label_foreground = h(p.text_secondary);
|
||||
|
||||
// The status colours, with the text that reads on each.
|
||||
let [danger, success, warning, info] =
|
||||
[p.danger, p.success, p.warning, p.info].map(|base| status(base, p.bg_app, dark));
|
||||
(c.danger, c.danger_hover, c.danger_active, c.danger_foreground) =
|
||||
(danger.base, danger.hover, danger.active, danger.foreground);
|
||||
(c.success, c.success_hover, c.success_active, c.success_foreground) =
|
||||
(success.base, success.hover, success.active, success.foreground);
|
||||
(c.warning, c.warning_hover, c.warning_active, c.warning_foreground) =
|
||||
(warning.base, warning.hover, warning.active, warning.foreground);
|
||||
(c.info, c.info_hover, c.info_active, c.info_foreground) =
|
||||
(info.base, info.hover, info.active, info.foreground);
|
||||
|
||||
// Lists and tables: rows on the panel, hovered rows raised, the selected
|
||||
// row the soft accent with the accent's edge.
|
||||
c.list = h(p.surface);
|
||||
c.list_hover = h(p.surface_3);
|
||||
c.list_active = h(p.accent_soft);
|
||||
c.list_active_border = h(p.accent);
|
||||
c.list_even = h(p.surface);
|
||||
c.list_head = h(p.surface_2);
|
||||
c.table = h(p.surface);
|
||||
c.table_hover = h(p.surface_3);
|
||||
c.table_active = h(p.accent_soft);
|
||||
c.table_active_border = h(p.accent);
|
||||
c.table_even = h(p.surface);
|
||||
c.table_head = h(p.surface_2);
|
||||
c.table_head_foreground = h(p.text_secondary);
|
||||
c.table_foot = h(p.surface_2);
|
||||
c.table_foot_foreground = h(p.text_secondary);
|
||||
c.table_row_border = h(p.border);
|
||||
|
||||
// The panels around the content: the sidebar, the title and status bars.
|
||||
c.sidebar = h(p.surface);
|
||||
c.sidebar_foreground = h(p.text);
|
||||
c.sidebar_border = h(p.border);
|
||||
c.sidebar_accent = h(p.surface_3);
|
||||
c.sidebar_accent_foreground = h(p.text);
|
||||
c.sidebar_primary = h(p.accent);
|
||||
c.sidebar_primary_foreground = h(p.on_accent);
|
||||
c.title_bar = h(p.surface);
|
||||
c.title_bar_border = h(p.border);
|
||||
c.status_bar = h(p.surface);
|
||||
c.status_bar_border = h(p.border);
|
||||
|
||||
// Small widgets.
|
||||
c.scrollbar = clear;
|
||||
c.scrollbar_thumb = h(p.border_strong);
|
||||
c.scrollbar_thumb_hover = h(p.text_muted);
|
||||
c.slider_bar = h(p.accent);
|
||||
c.slider_thumb = h(p.on_accent);
|
||||
c.switch = h(p.surface_4);
|
||||
c.switch_thumb = h(p.on_accent);
|
||||
c.progress_bar = h(p.accent);
|
||||
c.skeleton = h(p.surface_3);
|
||||
c.tab = clear;
|
||||
c.tab_active = h(p.surface_2);
|
||||
c.tab_active_foreground = h(p.text);
|
||||
c.tab_bar = h(p.surface);
|
||||
c.tab_bar_segmented = h(p.surface_2);
|
||||
c.tab_foreground = h(p.text_secondary);
|
||||
|
||||
// The base palette and the charts: the client's state colours.
|
||||
c.red = h(p.danger);
|
||||
c.red_light = h(p.danger_soft);
|
||||
c.green = h(p.success);
|
||||
c.green_light = h(p.success_soft);
|
||||
c.yellow = h(p.warning);
|
||||
c.yellow_light = h(p.warning_soft);
|
||||
c.blue = h(p.info);
|
||||
c.blue_light = h(p.accent_soft);
|
||||
c.chart_1 = h(p.accent);
|
||||
c.chart_2 = h(p.success);
|
||||
c.chart_3 = h(p.warning);
|
||||
c.chart_4 = h(p.danger);
|
||||
c.chart_5 = h(p.info);
|
||||
|
||||
// The buttons: what a theme file leaves out they take from the colours
|
||||
// above, so they are written from them here.
|
||||
c.button = c.secondary;
|
||||
c.button_hover = c.secondary_hover;
|
||||
c.button_active = c.secondary_active;
|
||||
c.button_foreground = c.secondary_foreground;
|
||||
c.button_primary = c.primary;
|
||||
c.button_primary_hover = c.primary_hover;
|
||||
c.button_primary_active = c.primary_active;
|
||||
c.button_primary_foreground = c.primary_foreground;
|
||||
c.button_secondary = c.secondary;
|
||||
c.button_secondary_hover = c.secondary_hover;
|
||||
c.button_secondary_active = c.secondary_active;
|
||||
c.button_secondary_foreground = c.secondary_foreground;
|
||||
c.button_danger = c.danger;
|
||||
c.button_danger_hover = c.danger_hover;
|
||||
c.button_danger_active = c.danger_active;
|
||||
c.button_danger_foreground = c.danger_foreground;
|
||||
c.button_success = c.success;
|
||||
c.button_success_hover = c.success_hover;
|
||||
c.button_success_active = c.success_active;
|
||||
c.button_success_foreground = c.success_foreground;
|
||||
c.button_warning = c.warning;
|
||||
c.button_warning_hover = c.warning_hover;
|
||||
c.button_warning_active = c.warning_active;
|
||||
c.button_warning_foreground = c.warning_foreground;
|
||||
c.button_info = c.info;
|
||||
c.button_info_hover = c.info_hover;
|
||||
c.button_info_active = c.info_active;
|
||||
c.button_info_foreground = c.info_foreground;
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn written(dark: bool) -> (Palette, ThemeColor) {
|
||||
let palette = if dark { Palette::DARK } else { Palette::LIGHT };
|
||||
let mut colors = ThemeColor::default();
|
||||
write(&palette, dark, &mut colors);
|
||||
(palette, colors)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_client_tokens_land_where_the_table_says() {
|
||||
for dark in [true, false] {
|
||||
let (p, c) = written(dark);
|
||||
assert_eq!(c.background, hsla(p.bg_app));
|
||||
assert_eq!(c.foreground, hsla(p.text));
|
||||
assert_eq!(c.primary, hsla(p.accent));
|
||||
assert_eq!(c.primary_hover, hsla(p.accent_hover));
|
||||
assert_eq!(c.primary_active, hsla(p.accent_pressed));
|
||||
assert_eq!(c.primary_foreground, hsla(p.on_accent));
|
||||
assert_eq!(
|
||||
c.accent,
|
||||
hsla(p.surface_3),
|
||||
"gpui-component's accent is a hover background"
|
||||
);
|
||||
assert_eq!(c.secondary, hsla(p.surface_2));
|
||||
assert_eq!(c.secondary_active, hsla(p.surface_4));
|
||||
assert_eq!(c.border, hsla(p.border));
|
||||
assert_eq!(c.input, hsla(p.border_strong));
|
||||
assert_eq!(c.ring, hsla(p.glow));
|
||||
assert_eq!(c.overlay, hsla(p.scrim));
|
||||
assert_eq!(c.list_active, hsla(p.accent_soft));
|
||||
assert_eq!(c.link, hsla(p.accent_text));
|
||||
assert_eq!(c.muted_foreground, hsla(p.text_muted));
|
||||
assert_eq!(c.sidebar, hsla(p.surface));
|
||||
assert_eq!(c.danger, hsla(p.danger));
|
||||
assert_eq!(c.success, hsla(p.success));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_buttons_follow_the_colours_they_fall_back_to() {
|
||||
let (_, c) = written(true);
|
||||
assert_eq!(c.button_primary, c.primary);
|
||||
assert_eq!(c.button_primary_hover, c.primary_hover);
|
||||
assert_eq!(c.button_danger_foreground, c.danger_foreground);
|
||||
assert_eq!(c.button, c.secondary);
|
||||
assert_eq!(c.button_info_active, c.info_active);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_text_on_a_status_colour_is_the_one_that_reads_better() {
|
||||
for (p, dark) in [(Palette::DARK, true), (Palette::LIGHT, false)] {
|
||||
for base in [p.danger, p.success, p.warning, p.info] {
|
||||
let s = status(base, p.bg_app, dark);
|
||||
let chosen = base.readable(p.bg_app);
|
||||
let other = if chosen == Rgba(0xffff_ffff) { p.bg_app } else { Rgba(0xffff_ffff) };
|
||||
assert!(base.contrast(chosen) >= base.contrast(other), "{base} on {chosen}");
|
||||
assert_eq!(s.foreground, hsla(chosen));
|
||||
assert_ne!(s.hover, s.base);
|
||||
assert_ne!(s.active, s.base);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mixing_and_contrast_do_what_they_say() {
|
||||
let (black, white) = (Rgba(0x0000_00ff), Rgba(0xffff_ffff));
|
||||
assert_eq!(black.mix(white, 0.0), black);
|
||||
assert_eq!(black.mix(white, 1.0), white);
|
||||
assert_eq!(Rgba(0x1020_30c0).mix(white, 0.0), Rgba(0x1020_30c0), "opacity stays");
|
||||
assert!((black.contrast(white) - 21.0).abs() < 0.01);
|
||||
assert_eq!(black.readable(black), white);
|
||||
assert_eq!(Rgba(0xf5b3_01ff).readable(Rgba(0x060a_18ff)), Rgba(0x060a_18ff));
|
||||
assert_eq!(Rgba(0x12ab_34ff).to_string(), "#12ab34");
|
||||
assert_eq!(Rgba(0x12ab_3480).to_string(), "#12ab3480");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,293 @@
|
||||
//! The Voelin theme, in two layers (docs/ui.md, "The GPUI front end"):
|
||||
//!
|
||||
//! 1. [`VoelinTheme`], a GPUI global with every token of
|
||||
//! `crates/voelin-ui/ui/theme.slint`, light and dark ([`tokens`]), which a
|
||||
//! test keeps equal to the Slint file ([`slint_parity`]). The shell's own
|
||||
//! elements (the server rail, presence dots, meters, the backdrop) read it.
|
||||
//! 2. gpui-component's `ThemeColor`, the colours its widgets (inputs, lists,
|
||||
//! menus, dialogs) read, written from the first on every change
|
||||
//! ([`components`]), so that they look like ours.
|
||||
//!
|
||||
//! The mode is the client's `ui.theme`: `system` follows the window's
|
||||
//! appearance (and its changes), `light` and `dark` do not.
|
||||
|
||||
mod components;
|
||||
#[cfg(test)]
|
||||
mod slint_parity;
|
||||
pub mod tokens;
|
||||
|
||||
pub use components::hsla;
|
||||
use gpui_kit::component::{Theme, ThemeMode};
|
||||
use gpui_kit::{App, Background, Global, WindowAppearance, linear_color_stop, linear_gradient, px};
|
||||
pub use tokens::{Backdrop, FONT_FAMILY, Metrics, Palette, Rgba};
|
||||
|
||||
impl Backdrop {
|
||||
/// What GPUI draws: its gradient has two colour stops, so the first and the
|
||||
/// last of the three; the middle one is not drawn.
|
||||
pub fn to_gpui(&self) -> Background {
|
||||
let [first, _, last] = self.stops;
|
||||
linear_gradient(
|
||||
self.angle,
|
||||
linear_color_stop(hsla(first.0), first.1),
|
||||
linear_color_stop(hsla(last.0), last.1),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// The theme mode setting (`ui.theme` of the Slint front end).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub enum Choice {
|
||||
/// Follow the window's appearance.
|
||||
System,
|
||||
/// Always light.
|
||||
Light,
|
||||
/// Always dark.
|
||||
Dark,
|
||||
}
|
||||
|
||||
impl Choice {
|
||||
/// `system`, `light` or `dark`.
|
||||
pub fn parse(text: &str) -> Option<Self> {
|
||||
match text {
|
||||
"system" => Some(Self::System),
|
||||
"light" => Some(Self::Light),
|
||||
"dark" => Some(Self::Dark),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The setting's value.
|
||||
pub fn name(self) -> &'static str {
|
||||
match self {
|
||||
Self::System => "system",
|
||||
Self::Light => "light",
|
||||
Self::Dark => "dark",
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the theme is dark, given whether the window's appearance is.
|
||||
pub fn resolve(self, system_dark: bool) -> bool {
|
||||
match self {
|
||||
Self::System => system_dark,
|
||||
Self::Light => false,
|
||||
Self::Dark => true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a window's appearance is a dark one.
|
||||
pub fn is_dark(appearance: WindowAppearance) -> bool {
|
||||
matches!(appearance, WindowAppearance::Dark | WindowAppearance::VibrantDark)
|
||||
}
|
||||
|
||||
/// Every token of `theme.slint` for the resolved mode and text size; a GPUI
|
||||
/// global.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct VoelinTheme {
|
||||
choice: Choice,
|
||||
dark: bool,
|
||||
/// The colours of the resolved mode.
|
||||
pub colors: Palette,
|
||||
/// The window's backdrop gradient of the resolved mode.
|
||||
pub backdrop: Backdrop,
|
||||
/// The sizes, radii, type and durations at the text size factor.
|
||||
pub metrics: Metrics,
|
||||
}
|
||||
|
||||
impl Global for VoelinTheme {}
|
||||
|
||||
impl VoelinTheme {
|
||||
/// The tokens for a mode (resolved against `system_dark`) and a text size
|
||||
/// factor.
|
||||
pub fn new(choice: Choice, system_dark: bool, font_scale: f32) -> Self {
|
||||
let dark = choice.resolve(system_dark);
|
||||
Self {
|
||||
choice,
|
||||
dark,
|
||||
colors: if dark { Palette::DARK } else { Palette::LIGHT },
|
||||
backdrop: if dark { Backdrop::DARK } else { Backdrop::LIGHT },
|
||||
metrics: Metrics::new(font_scale),
|
||||
}
|
||||
}
|
||||
|
||||
/// The theme mode that was set.
|
||||
pub fn choice(&self) -> Choice {
|
||||
self.choice
|
||||
}
|
||||
|
||||
/// Whether the colours are the dark ones.
|
||||
pub fn is_dark(&self) -> bool {
|
||||
self.dark
|
||||
}
|
||||
|
||||
/// Install the theme as the global and write it into gpui-component, which
|
||||
/// `gpui_kit::init` must have set up. `appearance` is the window's (or
|
||||
/// the system's before there is a window).
|
||||
pub fn init(cx: &mut App, choice: Choice, appearance: WindowAppearance, font_scale: f32) {
|
||||
cx.set_global(Self::new(choice, is_dark(appearance), font_scale));
|
||||
Self::apply(cx);
|
||||
}
|
||||
|
||||
/// The theme global.
|
||||
pub fn global(cx: &App) -> &Self {
|
||||
cx.global::<Self>()
|
||||
}
|
||||
|
||||
/// Change the mode (a setting changed), given the window's appearance now.
|
||||
pub fn set_choice(cx: &mut App, choice: Choice, appearance: WindowAppearance) {
|
||||
let (scale, current) = {
|
||||
let this = Self::global(cx);
|
||||
(this.metrics.font_scale, this.choice)
|
||||
};
|
||||
if current == choice && Self::global(cx).dark == choice.resolve(is_dark(appearance)) {
|
||||
return;
|
||||
}
|
||||
cx.set_global(Self::new(choice, is_dark(appearance), scale));
|
||||
Self::apply(cx);
|
||||
}
|
||||
|
||||
/// The window's appearance changed; it matters only in `system` mode.
|
||||
pub fn set_system_appearance(cx: &mut App, appearance: WindowAppearance) {
|
||||
let this = Self::global(cx);
|
||||
if this.choice == Choice::System && this.dark != is_dark(appearance) {
|
||||
let (choice, scale) = (this.choice, this.metrics.font_scale);
|
||||
cx.set_global(Self::new(choice, is_dark(appearance), scale));
|
||||
Self::apply(cx);
|
||||
}
|
||||
}
|
||||
|
||||
/// The text size factor changed (`ui.font_scale`).
|
||||
pub fn set_font_scale(cx: &mut App, font_scale: f32) {
|
||||
let this = Self::global(cx);
|
||||
if (this.metrics.font_scale - font_scale).abs() < f32::EPSILON {
|
||||
return;
|
||||
}
|
||||
// `dark` is what the mode resolved to: for every mode, resolving it again
|
||||
// against it gives the same.
|
||||
let (choice, dark) = (this.choice, this.dark);
|
||||
cx.set_global(Self::new(choice, dark, font_scale));
|
||||
Self::apply(cx);
|
||||
}
|
||||
|
||||
/// Write the global into gpui-component's theme: the mode, the colours of
|
||||
/// the second layer, the font, the base size and the radii.
|
||||
fn apply(cx: &mut App) {
|
||||
let this = Self::global(cx).clone();
|
||||
// The registered theme of the mode first (it sets whatever the second
|
||||
// layer leaves alone), then our colours over it in a second update, as
|
||||
// `Theme::update` says a mode change must be.
|
||||
Theme::change(if this.dark { ThemeMode::Dark } else { ThemeMode::Light }, None, cx);
|
||||
Theme::update(cx, |theme| {
|
||||
components::write(&this.colors, this.dark, &mut theme.colors);
|
||||
theme.font_family = FONT_FAMILY.into();
|
||||
theme.font_size = px(this.metrics.font_body);
|
||||
theme.radius = px(this.metrics.radius_sm);
|
||||
theme.radius_lg = px(this.metrics.radius_lg);
|
||||
});
|
||||
// Where the platform draws the window's frame itself (macOS), it follows
|
||||
// the mode; elsewhere this does nothing.
|
||||
cx.set_window_appearance(match this.choice {
|
||||
Choice::System => None,
|
||||
Choice::Light => Some(WindowAppearance::Light),
|
||||
Choice::Dark => Some(WindowAppearance::Dark),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use gpui::TestAppContext;
|
||||
use gpui_kit::component::ActiveTheme as _;
|
||||
|
||||
use super::*;
|
||||
|
||||
fn start(cx: &mut TestAppContext, choice: Choice, appearance: WindowAppearance) {
|
||||
cx.update(|cx| {
|
||||
gpui_kit::init(cx);
|
||||
VoelinTheme::init(cx, choice, appearance, 1.0);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_mode_resolves_against_the_window() {
|
||||
assert!(Choice::System.resolve(true) && !Choice::System.resolve(false));
|
||||
assert!(Choice::Dark.resolve(false) && !Choice::Light.resolve(true));
|
||||
for choice in [Choice::System, Choice::Light, Choice::Dark] {
|
||||
assert_eq!(Choice::parse(choice.name()), Some(choice));
|
||||
}
|
||||
assert_eq!(Choice::parse("blue"), None);
|
||||
assert!(is_dark(WindowAppearance::VibrantDark) && !is_dark(WindowAppearance::VibrantLight));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_backdrop_draws_the_first_and_the_last_of_its_three_stops() {
|
||||
let b = Backdrop::DARK;
|
||||
let [first, middle, last] = b.stops;
|
||||
assert_eq!(
|
||||
b.to_gpui(),
|
||||
linear_gradient(
|
||||
160.0,
|
||||
linear_color_stop(hsla(first.0), 0.0),
|
||||
linear_color_stop(hsla(last.0), 1.0)
|
||||
)
|
||||
);
|
||||
assert_ne!(
|
||||
b.to_gpui(),
|
||||
linear_gradient(
|
||||
160.0,
|
||||
linear_color_stop(hsla(first.0), 0.0),
|
||||
linear_color_stop(hsla(middle.0), 1.0)
|
||||
),
|
||||
"the middle stop is not the end one"
|
||||
);
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
fn the_tokens_reach_gpui_component(cx: &mut TestAppContext) {
|
||||
start(cx, Choice::Dark, WindowAppearance::Light);
|
||||
cx.update(|cx| {
|
||||
let theme = cx.theme();
|
||||
assert!(theme.is_dark());
|
||||
assert_eq!(theme.colors.primary, hsla(Palette::DARK.accent));
|
||||
assert_eq!(theme.colors.background, hsla(Palette::DARK.bg_app));
|
||||
assert_eq!(theme.colors.button_primary, hsla(Palette::DARK.accent));
|
||||
assert_eq!(theme.font_family.as_ref(), "Inter");
|
||||
assert_eq!(theme.font_size, px(14.0));
|
||||
assert_eq!(theme.radius, px(6.0));
|
||||
assert_eq!(theme.radius_lg, px(12.0));
|
||||
assert_eq!(VoelinTheme::global(cx).colors, Palette::DARK);
|
||||
assert_eq!(VoelinTheme::global(cx).backdrop, Backdrop::DARK);
|
||||
});
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
fn system_follows_the_window_appearance_and_light_and_dark_do_not(cx: &mut TestAppContext) {
|
||||
start(cx, Choice::System, WindowAppearance::Light);
|
||||
let primary = |cx: &mut TestAppContext| cx.update(|cx| cx.theme().colors.primary);
|
||||
assert_eq!(primary(cx), hsla(Palette::LIGHT.accent));
|
||||
cx.update(|cx| VoelinTheme::set_system_appearance(cx, WindowAppearance::Dark));
|
||||
assert_eq!(primary(cx), hsla(Palette::DARK.accent));
|
||||
cx.update(|cx| VoelinTheme::set_system_appearance(cx, WindowAppearance::VibrantLight));
|
||||
assert_eq!(primary(cx), hsla(Palette::LIGHT.accent));
|
||||
|
||||
cx.update(|cx| VoelinTheme::set_choice(cx, Choice::Dark, WindowAppearance::Light));
|
||||
assert_eq!(primary(cx), hsla(Palette::DARK.accent));
|
||||
cx.update(|cx| VoelinTheme::set_system_appearance(cx, WindowAppearance::Light));
|
||||
assert_eq!(primary(cx), hsla(Palette::DARK.accent), "a dark choice ignores the window");
|
||||
cx.update(|cx| VoelinTheme::set_choice(cx, Choice::Light, WindowAppearance::Dark));
|
||||
assert_eq!(primary(cx), hsla(Palette::LIGHT.accent), "so does a light one");
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
fn the_text_size_scales_the_type_and_the_controls(cx: &mut TestAppContext) {
|
||||
start(cx, Choice::Dark, WindowAppearance::Dark);
|
||||
cx.update(|cx| VoelinTheme::set_font_scale(cx, 1.25));
|
||||
cx.update(|cx| {
|
||||
let theme = VoelinTheme::global(cx);
|
||||
assert!(theme.is_dark(), "the mode stays");
|
||||
assert_eq!(theme.metrics.font_body, 17.5);
|
||||
assert_eq!(theme.metrics.control_height, 45.0);
|
||||
assert_eq!(cx.theme().font_size, px(17.5));
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,318 @@
|
||||
//! `crates/voelin-ui/ui/theme.slint` against `tokens.rs`: the Slint file is
|
||||
//! read and every token in it is compared with the Rust value of the same
|
||||
//! name, light and dark and at four text sizes; a token on one side only, a
|
||||
//! value that differs, or a declaration of a kind this test does not know
|
||||
//! (or a second brush or string, of which it knows `backdrop`, `mode` and
|
||||
//! `font-family`) fails it. While both front ends live, a token changed in
|
||||
//! one place and not the other is caught here.
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
use super::tokens::{Backdrop, FONT_FAMILY, Metrics, Palette, Rgba};
|
||||
|
||||
const SLINT: &str = include_str!("../../../voelin-ui/ui/theme.slint");
|
||||
|
||||
/// What `theme.slint` declares: the kind and the expression of each property
|
||||
/// of the `Theme` global, in file order.
|
||||
fn declarations() -> Vec<(String, String, String)> {
|
||||
declarations_of(SLINT)
|
||||
}
|
||||
|
||||
/// The same for the text of a `.slint` file (the tests below also read
|
||||
/// altered copies of `theme.slint`).
|
||||
fn declarations_of(source: &str) -> Vec<(String, String, String)> {
|
||||
let without_comments: String = source
|
||||
.lines()
|
||||
.map(|line| line.split("//").next().unwrap_or(""))
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n");
|
||||
let body = without_comments.split_once("export global Theme {").expect("the Theme global").1;
|
||||
let mut found = Vec::new();
|
||||
for statement in body.split(';') {
|
||||
let statement = statement.trim();
|
||||
let Some(rest) = ["in-out property", "out property", "in property"]
|
||||
.iter()
|
||||
.find_map(|prefix| statement.strip_prefix(prefix))
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
let (kind, rest) =
|
||||
rest.trim().strip_prefix('<').expect("<kind>").split_once('>').expect("<kind>");
|
||||
let (name, expr) = rest.trim().split_once(':').expect("name: expression");
|
||||
// One line, single spaces: `backdrop` is written over several.
|
||||
let expr = expr.split_whitespace().collect::<Vec<_>>().join(" ");
|
||||
found.push((name.trim().to_owned(), kind.trim().to_owned(), expr));
|
||||
}
|
||||
found
|
||||
}
|
||||
|
||||
/// `#rgb`-style literal as `Rgba`.
|
||||
fn colour(text: &str) -> Rgba {
|
||||
let hex = text.trim().strip_prefix('#').unwrap_or_else(|| panic!("a colour, not {text:?}"));
|
||||
let value = u32::from_str_radix(hex, 16).unwrap_or_else(|_| panic!("hex digits in {text:?}"));
|
||||
match hex.len() {
|
||||
6 => Rgba(value << 8 | 0xff),
|
||||
8 => Rgba(value),
|
||||
_ => panic!("#rrggbb or #rrggbbaa, not {text:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Split `dark ? A : B` at its top-level `?` and `:`; `A` for a plain `A`.
|
||||
fn by_mode(expr: &str) -> (String, String) {
|
||||
let Some(rest) = expr.strip_prefix("dark ?") else {
|
||||
return (expr.to_owned(), expr.to_owned());
|
||||
};
|
||||
let mut depth = 0;
|
||||
for (i, c) in rest.char_indices() {
|
||||
match c {
|
||||
'(' => depth += 1,
|
||||
')' => depth -= 1,
|
||||
':' if depth == 0 => {
|
||||
return (rest[..i].trim().to_owned(), rest[i + 1..].trim().to_owned());
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
panic!("no `:` in {expr:?}");
|
||||
}
|
||||
|
||||
/// The arithmetic of the length tokens: numbers with a unit, other tokens,
|
||||
/// `*`, `+`, `max(a, b)` and parentheses.
|
||||
struct Eval<'a> {
|
||||
tokens: Vec<String>,
|
||||
at: usize,
|
||||
env: &'a BTreeMap<String, String>,
|
||||
scale: f64,
|
||||
}
|
||||
|
||||
impl<'a> Eval<'a> {
|
||||
fn run(expr: &str, env: &'a BTreeMap<String, String>, scale: f64) -> f64 {
|
||||
let mut tokens = Vec::new();
|
||||
let mut word = String::new();
|
||||
for c in expr.chars() {
|
||||
if c.is_alphanumeric() || matches!(c, '-' | '.' | '%') {
|
||||
word.push(c);
|
||||
} else {
|
||||
if !word.is_empty() {
|
||||
tokens.push(std::mem::take(&mut word));
|
||||
}
|
||||
if !c.is_whitespace() {
|
||||
tokens.push(c.to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
if !word.is_empty() {
|
||||
tokens.push(word);
|
||||
}
|
||||
let mut eval = Eval { tokens, at: 0, env, scale };
|
||||
let value = eval.sum();
|
||||
assert_eq!(eval.at, eval.tokens.len(), "all of {expr:?} is read");
|
||||
value
|
||||
}
|
||||
|
||||
fn peek(&self) -> Option<&str> {
|
||||
self.tokens.get(self.at).map(String::as_str)
|
||||
}
|
||||
|
||||
fn take(&mut self) -> String {
|
||||
self.at += 1;
|
||||
self.tokens[self.at - 1].clone()
|
||||
}
|
||||
|
||||
fn sum(&mut self) -> f64 {
|
||||
let mut value = self.product();
|
||||
while self.peek() == Some("+") {
|
||||
self.take();
|
||||
value += self.product();
|
||||
}
|
||||
value
|
||||
}
|
||||
|
||||
fn product(&mut self) -> f64 {
|
||||
let mut value = self.factor();
|
||||
while self.peek() == Some("*") {
|
||||
self.take();
|
||||
value *= self.factor();
|
||||
}
|
||||
value
|
||||
}
|
||||
|
||||
fn factor(&mut self) -> f64 {
|
||||
let token = self.take();
|
||||
if token == "(" {
|
||||
let value = self.sum();
|
||||
assert_eq!(self.take(), ")");
|
||||
return value;
|
||||
}
|
||||
if token == "max" {
|
||||
assert_eq!(self.take(), "(");
|
||||
let a = self.sum();
|
||||
assert_eq!(self.take(), ",");
|
||||
let b = self.sum();
|
||||
assert_eq!(self.take(), ")");
|
||||
return a.max(b);
|
||||
}
|
||||
if token == "font-scale" {
|
||||
return self.scale;
|
||||
}
|
||||
if token.starts_with(|c: char| c.is_ascii_digit()) {
|
||||
let number: String =
|
||||
token.chars().take_while(|c| c.is_ascii_digit() || *c == '.').collect();
|
||||
return number.parse().unwrap_or_else(|_| panic!("a number in {token:?}"));
|
||||
}
|
||||
let expr =
|
||||
self.env.get(&token).unwrap_or_else(|| panic!("a token named {token:?}")).clone();
|
||||
Eval::run(&expr, self.env, self.scale)
|
||||
}
|
||||
}
|
||||
|
||||
/// The names `theme.slint` declares that are state, not tokens: the mode and
|
||||
/// what it resolves to, and the text size factor (the factor is a parameter
|
||||
/// of [`Metrics`]).
|
||||
const STATE: [&str; 4] = ["mode", "system-dark", "dark", "font-scale"];
|
||||
|
||||
#[test]
|
||||
fn every_colour_is_the_same_in_both_files() {
|
||||
let slint: Vec<(String, String, String)> =
|
||||
declarations().into_iter().filter(|(_, kind, _)| kind == "color").collect();
|
||||
assert!(slint.len() > 40, "the colours were found: {}", slint.len());
|
||||
let dark: BTreeMap<_, _> = Palette::DARK.entries().into_iter().collect();
|
||||
let light: BTreeMap<_, _> = Palette::LIGHT.entries().into_iter().collect();
|
||||
let mut names = BTreeSet::new();
|
||||
for (name, _, expr) in &slint {
|
||||
let (d, l) = by_mode(expr);
|
||||
assert_eq!(dark.get(name.as_str()), Some(&colour(&d)), "{name} (dark)");
|
||||
assert_eq!(light.get(name.as_str()), Some(&colour(&l)), "{name} (light)");
|
||||
names.insert(name.as_str());
|
||||
}
|
||||
let ours: BTreeSet<&str> = dark.keys().copied().collect();
|
||||
assert_eq!(ours, names, "colours in tokens.rs and not in theme.slint, or the other way");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_length_weight_and_duration_is_the_same_in_both_files() {
|
||||
let all = declarations();
|
||||
let env: BTreeMap<String, String> =
|
||||
all.iter().map(|(name, _, expr)| (name.clone(), expr.clone())).collect();
|
||||
let numeric: Vec<&(String, String, String)> = all
|
||||
.iter()
|
||||
.filter(|(name, kind, _)| {
|
||||
matches!(kind.as_str(), "length" | "int" | "duration")
|
||||
&& !STATE.contains(&name.as_str())
|
||||
})
|
||||
.collect();
|
||||
assert!(numeric.len() > 30, "the numbers were found: {}", numeric.len());
|
||||
for scale in [1.0_f32, 1.25, 0.8, 2.0] {
|
||||
let ours: BTreeMap<&str, f64> = Metrics::new(scale).entries().into_iter().collect();
|
||||
let mut names = BTreeSet::new();
|
||||
for (name, _, expr) in &numeric {
|
||||
let slint = Eval::run(expr, &env, f64::from(scale));
|
||||
let ours = *ours.get(name.as_str()).unwrap_or_else(|| panic!("{name} is in tokens.rs"));
|
||||
assert!(
|
||||
(slint - ours).abs() < 1e-3,
|
||||
"{name} at {scale}: theme.slint {slint}, tokens.rs {ours}"
|
||||
);
|
||||
names.insert(name.as_str());
|
||||
}
|
||||
let rust: BTreeSet<&str> = ours.keys().copied().collect();
|
||||
assert_eq!(rust, names, "numbers in tokens.rs and not in theme.slint, or the other way");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_backdrop_and_the_font_are_the_same_in_both_files() {
|
||||
let all = declarations();
|
||||
let get = |name: &str| {
|
||||
all.iter().find(|(n, _, _)| n == name).unwrap_or_else(|| panic!("{name}")).2.clone()
|
||||
};
|
||||
let gradient = |text: &str| -> Backdrop {
|
||||
let inner = text
|
||||
.trim()
|
||||
.strip_prefix("@linear-gradient(")
|
||||
.and_then(|t| t.strip_suffix(')'))
|
||||
.unwrap_or_else(|| panic!("a linear gradient, not {text:?}"));
|
||||
let mut parts = inner.split(',').map(str::trim);
|
||||
let angle: f32 = parts.next().unwrap().trim_end_matches("deg").parse().unwrap();
|
||||
let stops: Vec<(Rgba, f32)> = parts
|
||||
.map(|stop| {
|
||||
let (colour_text, position) = stop.split_once(' ').unwrap();
|
||||
let percent: f32 = position.trim().trim_end_matches('%').parse().unwrap();
|
||||
(colour(colour_text), percent / 100.0)
|
||||
})
|
||||
.collect();
|
||||
Backdrop { angle, stops: stops.try_into().expect("three stops") }
|
||||
};
|
||||
let (dark, light) = by_mode(&get("backdrop"));
|
||||
assert_eq!(gradient(&dark), Backdrop::DARK);
|
||||
assert_eq!(gradient(&light), Backdrop::LIGHT);
|
||||
assert_eq!(get("font-family"), format!("\"{FONT_FAMILY}\""));
|
||||
}
|
||||
|
||||
/// What the declarations hold that no comparison above covers, one sentence
|
||||
/// each; empty when there is none: a kind of declaration this test does not
|
||||
/// know, a brush other than `backdrop` or a string other than `mode` and
|
||||
/// `font-family` (the two comparisons of those go by name, so a second one
|
||||
/// would pass unseen), a state name that is no longer declared.
|
||||
fn unknown_to_this_test(declared: &[(String, String, String)]) -> Vec<String> {
|
||||
let mut problems = Vec::new();
|
||||
let kinds: BTreeSet<&str> = declared
|
||||
.iter()
|
||||
.filter(|(name, _, _)| !STATE.contains(&name.as_str()))
|
||||
.map(|(_, kind, _)| kind.as_str())
|
||||
.collect();
|
||||
let known = BTreeSet::from(["color", "brush", "length", "int", "duration", "string"]);
|
||||
if kinds != known {
|
||||
problems.push(format!("kinds of declaration {kinds:?}, this test knows {known:?}"));
|
||||
}
|
||||
for (kind, expected) in [("brush", &["backdrop"][..]), ("string", &["mode", "font-family"])] {
|
||||
let found: BTreeSet<&str> = declared
|
||||
.iter()
|
||||
.filter(|(_, declared_kind, _)| declared_kind == kind)
|
||||
.map(|(name, _, _)| name.as_str())
|
||||
.collect();
|
||||
let expected: BTreeSet<&str> = expected.iter().copied().collect();
|
||||
for name in found.symmetric_difference(&expected) {
|
||||
problems.push(format!(
|
||||
"{name}: the <{kind}> declarations are {found:?}, this test compares {expected:?}"
|
||||
));
|
||||
}
|
||||
}
|
||||
for name in STATE {
|
||||
if !declared.iter().any(|(declared, _, _)| declared == name) {
|
||||
problems.push(format!("{name} is not declared"));
|
||||
}
|
||||
}
|
||||
problems
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_file_declares_nothing_this_test_does_not_know() {
|
||||
let problems = unknown_to_this_test(&declarations());
|
||||
assert!(problems.is_empty(), "{problems:#?}");
|
||||
}
|
||||
|
||||
/// `theme.slint` with one more declaration in its `Theme` global.
|
||||
fn with_declaration(declaration: &str) -> String {
|
||||
let opening = "export global Theme {";
|
||||
assert!(SLINT.contains(opening));
|
||||
SLINT.replacen(opening, &format!("{opening}\n {declaration}"), 1)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_second_brush_or_string_is_not_passed_unseen() {
|
||||
// Mutants of the Slint file: a token on one side only.
|
||||
for (declaration, name) in [
|
||||
("out property <brush> backdrop-soft: #123456;", "backdrop-soft"),
|
||||
("out property <string> font-mono: \"Mono\";", "font-mono"),
|
||||
] {
|
||||
let mutant = declarations_of(&with_declaration(declaration));
|
||||
assert!(mutant.iter().any(|(declared, _, _)| declared == name), "the mutant has {name}");
|
||||
let problems = unknown_to_this_test(&mutant);
|
||||
assert!(
|
||||
problems.iter().any(|problem| problem.contains(name)),
|
||||
"{name} goes unnoticed: {problems:#?}"
|
||||
);
|
||||
}
|
||||
// And the file as it is has neither.
|
||||
assert_eq!(unknown_to_this_test(&declarations()), Vec::<String>::new());
|
||||
}
|
||||
@@ -0,0 +1,372 @@
|
||||
//! The tokens of `crates/voelin-ui/ui/theme.slint`, light and dark, as Rust
|
||||
//! values: the source of truth the GPUI front end copies. `theme.slint` stays
|
||||
//! the original while the Slint front end lives; the test in
|
||||
//! `theme/slint_parity.rs` reads it and fails when a value, a name or a
|
||||
//! formula here differs from it, so the two cannot drift apart.
|
||||
|
||||
use std::fmt;
|
||||
|
||||
/// A colour as `0xRRGGBBAA`, as the Slint file writes `#rrggbbaa` (`#rrggbb`
|
||||
/// is opaque).
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
|
||||
pub struct Rgba(pub u32);
|
||||
|
||||
impl fmt::Debug for Rgba {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
write!(f, "{self}")
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for Rgba {
|
||||
/// `#rrggbb`, or `#rrggbbaa` when not opaque.
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
if self.alpha() == 255 {
|
||||
write!(f, "#{:06x}", self.0 >> 8)
|
||||
} else {
|
||||
write!(f, "#{:08x}", self.0)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Rgba {
|
||||
/// Transparent black, for the widgets that draw nothing.
|
||||
pub const TRANSPARENT: Self = Self(0);
|
||||
|
||||
/// The opacity, 0 to 255.
|
||||
pub fn alpha(self) -> u8 {
|
||||
(self.0 & 0xff) as u8
|
||||
}
|
||||
|
||||
/// The same colour with another opacity.
|
||||
pub fn with_alpha(self, alpha: u8) -> Self {
|
||||
Self((self.0 & 0xffff_ff00) | u32::from(alpha))
|
||||
}
|
||||
|
||||
/// The channels, 0 to 1.
|
||||
pub fn channels(self) -> [f32; 3] {
|
||||
[24, 16, 8].map(|shift| ((self.0 >> shift) & 0xff) as f32 / 255.0)
|
||||
}
|
||||
|
||||
/// Mixed with `other` (of `amount`, 0 to 1), channel by channel, opacity
|
||||
/// from `self`.
|
||||
pub fn mix(self, other: Self, amount: f32) -> Self {
|
||||
let (a, b) = (self.channels(), other.channels());
|
||||
let channel =
|
||||
|i: usize| ((a[i] + (b[i] - a[i]) * amount) * 255.0).round().clamp(0.0, 255.0) as u32;
|
||||
Self(channel(0) << 24 | channel(1) << 16 | channel(2) << 8 | u32::from(self.alpha()))
|
||||
}
|
||||
|
||||
/// The relative luminance of WCAG 2, 0 (black) to 1 (white).
|
||||
pub fn luminance(self) -> f32 {
|
||||
let [r, g, b] = self
|
||||
.channels()
|
||||
.map(|c| if c <= 0.03928 { c / 12.92 } else { ((c + 0.055) / 1.055).powf(2.4) });
|
||||
0.2126 * r + 0.7152 * g + 0.0722 * b
|
||||
}
|
||||
|
||||
/// The contrast ratio of WCAG 2 between two colours, 1 to 21.
|
||||
pub fn contrast(self, other: Self) -> f32 {
|
||||
let (a, b) = (self.luminance(), other.luminance());
|
||||
(a.max(b) + 0.05) / (a.min(b) + 0.05)
|
||||
}
|
||||
|
||||
/// Of white and `ink`, the one that reads better on `self`.
|
||||
pub fn readable(self, ink: Self) -> Self {
|
||||
let white = Self(0xffff_ffff);
|
||||
if self.contrast(white) >= self.contrast(ink) { white } else { ink }
|
||||
}
|
||||
}
|
||||
|
||||
macro_rules! palette {
|
||||
($($field:ident $name:literal: $dark:literal, $light:literal;)*) => {
|
||||
/// Every colour token of `theme.slint` for one mode.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct Palette {
|
||||
$(
|
||||
#[doc = concat!("`", $name, "` of `theme.slint`.")]
|
||||
pub $field: Rgba,
|
||||
)*
|
||||
}
|
||||
|
||||
impl Palette {
|
||||
/// The dark palette.
|
||||
pub const DARK: Self = Self { $($field: Rgba($dark),)* };
|
||||
/// The light palette.
|
||||
pub const LIGHT: Self = Self { $($field: Rgba($light),)* };
|
||||
|
||||
/// Every colour by the name it has in `theme.slint`, in its order.
|
||||
pub fn entries(&self) -> Vec<(&'static str, Rgba)> {
|
||||
vec![$(($name, self.$field),)*]
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
palette! {
|
||||
bg_app "bg-app": 0x060a18ff, 0xe9eef9ff;
|
||||
bg_rail "bg-rail": 0x070c1dff, 0xdfe6f4ff;
|
||||
surface "surface": 0x0b1330ff, 0xf7f9feff;
|
||||
surface_2 "surface-2": 0x101a3cff, 0xffffffff;
|
||||
surface_3 "surface-3": 0x16224bff, 0xeaf0fbff;
|
||||
surface_4 "surface-4": 0x1c2b5cff, 0xdce5f7ff;
|
||||
scrim "scrim": 0x02050fc0, 0x0b132b80;
|
||||
scrim_light "scrim-light": 0x02050f73, 0x0b132b33;
|
||||
overlay "overlay": 0x060a18c8, 0x0b1330b0;
|
||||
border "border": 0x1b2750ff, 0xd3dceeff;
|
||||
border_strong "border-strong": 0x2a3a6eff, 0xb9c6e2ff;
|
||||
border_popup "border-popup": 0x3d5296ff, 0x9fb0d4ff;
|
||||
accent "accent": 0x2d6bffff, 0x2458e6ff;
|
||||
accent_hover "accent-hover": 0x4a82ffff, 0x3a6cf0ff;
|
||||
accent_pressed "accent-pressed": 0x1f55d9ff, 0x1b47c0ff;
|
||||
accent_soft "accent-soft": 0x18348aff, 0xd6e2ffff;
|
||||
accent_soft_hover "accent-soft-hover": 0x1d3d9cff, 0xc8d8ffff;
|
||||
accent_text "accent-text": 0x5c9dffff, 0x1d4fd6ff;
|
||||
name_text "name-text": 0x45b9ffff, 0x0f6cc4ff;
|
||||
on_accent "on-accent": 0xffffffff, 0xffffffff;
|
||||
glow "glow": 0x3f7bff90, 0x2458e660;
|
||||
live "live": 0xff2d55ff, 0xe0203fff;
|
||||
live_soft "live-soft": 0x3a0f22ff, 0xffe0e6ff;
|
||||
danger "danger": 0xff4d5eff, 0xd92c3cff;
|
||||
danger_soft "danger-soft": 0x3b1020ff, 0xffe3e6ff;
|
||||
success "success": 0x22d36bff, 0x16a557ff;
|
||||
success_soft "success-soft": 0x0d3326ff, 0xd7f5e4ff;
|
||||
warning "warning": 0xf5b301ff, 0xb77f00ff;
|
||||
warning_soft "warning-soft": 0x3a2a06ff, 0xfff0c8ff;
|
||||
idle "idle": 0xf5b301ff, 0xc98b00ff;
|
||||
dnd "dnd": 0xff4d5eff, 0xd92c3cff;
|
||||
offline "offline": 0x5f6d93ff, 0x8d99b5ff;
|
||||
gold "gold": 0xffc233ff, 0xd99a00ff;
|
||||
info "info": 0x3fb3ffff, 0x1180d6ff;
|
||||
text "text": 0xeef2ffff, 0x0e1733ff;
|
||||
text_secondary "text-secondary": 0xaeb9d8ff, 0x43506fff;
|
||||
text_muted "text-muted": 0x6d7ca6ff, 0x6f7b98ff;
|
||||
text_disabled "text-disabled": 0x46527aff, 0xa7b1c8ff;
|
||||
icon "icon": 0xb9c4e2ff, 0x43506fff;
|
||||
meter_low "meter-low": 0x21d07aff, 0x21d07aff;
|
||||
meter_mid "meter-mid": 0xf5d000ff, 0xf5d000ff;
|
||||
meter_high "meter-high": 0xff4d5eff, 0xff4d5eff;
|
||||
meter_off "meter-off": 0x1a2550ff, 0xd5ddefff;
|
||||
}
|
||||
|
||||
/// `@linear-gradient(angle, stop 0%, stop 55%, stop 100%)`: the window's
|
||||
/// backdrop. GPUI's `Background` has two colour stops, so what it draws
|
||||
/// (`Backdrop::to_gpui`, in the theme module) is the first and the last; the
|
||||
/// middle one stays here for a front end that can use it.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct Backdrop {
|
||||
/// The direction in degrees, as CSS and Slint take it (0 is to the top).
|
||||
pub angle: f32,
|
||||
/// Three stops: colour and position (0 to 1).
|
||||
pub stops: [(Rgba, f32); 3],
|
||||
}
|
||||
|
||||
impl Backdrop {
|
||||
/// The dark backdrop.
|
||||
pub const DARK: Self = Self {
|
||||
angle: 160.0,
|
||||
stops: [(Rgba(0x0a1230ff), 0.0), (Rgba(0x060a18ff), 0.55), (Rgba(0x0a1638ff), 1.0)],
|
||||
};
|
||||
/// The light backdrop.
|
||||
pub const LIGHT: Self = Self {
|
||||
angle: 160.0,
|
||||
stops: [(Rgba(0xf4f7fdff), 0.0), (Rgba(0xe6ecf8ff), 0.60), (Rgba(0xdde6f7ff), 1.0)],
|
||||
};
|
||||
}
|
||||
|
||||
/// The family of the UI font (`font-family` of `theme.slint`).
|
||||
pub const FONT_FAMILY: &str = "Inter";
|
||||
|
||||
/// Every size, radius, weight and duration token of `theme.slint` for one
|
||||
/// text size factor: lengths in logical pixels.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct Metrics {
|
||||
/// `font-scale`: multiplies every type size and the sizes that follow text.
|
||||
pub font_scale: f32,
|
||||
/// `radius-xs`.
|
||||
pub radius_xs: f32,
|
||||
/// `radius-sm`.
|
||||
pub radius_sm: f32,
|
||||
/// `radius-md`.
|
||||
pub radius_md: f32,
|
||||
/// `radius-lg`.
|
||||
pub radius_lg: f32,
|
||||
/// `radius-xl`.
|
||||
pub radius_xl: f32,
|
||||
/// `radius-pill`.
|
||||
pub radius_pill: f32,
|
||||
/// `space-1`.
|
||||
pub space_1: f32,
|
||||
/// `space-2`.
|
||||
pub space_2: f32,
|
||||
/// `space-3`.
|
||||
pub space_3: f32,
|
||||
/// `space-4`.
|
||||
pub space_4: f32,
|
||||
/// `space-5`.
|
||||
pub space_5: f32,
|
||||
/// `space-6`.
|
||||
pub space_6: f32,
|
||||
/// `space-7`.
|
||||
pub space_7: f32,
|
||||
/// `space-8`.
|
||||
pub space_8: f32,
|
||||
/// `font-xs` (scaled).
|
||||
pub font_xs: f32,
|
||||
/// `font-sm` (scaled).
|
||||
pub font_sm: f32,
|
||||
/// `font-body` (scaled).
|
||||
pub font_body: f32,
|
||||
/// `font-md` (scaled).
|
||||
pub font_md: f32,
|
||||
/// `font-lg` (scaled).
|
||||
pub font_lg: f32,
|
||||
/// `font-xl` (scaled).
|
||||
pub font_xl: f32,
|
||||
/// `font-2xl` (scaled).
|
||||
pub font_2xl: f32,
|
||||
/// `font-3xl` (scaled).
|
||||
pub font_3xl: f32,
|
||||
/// `weight-regular`.
|
||||
pub weight_regular: u16,
|
||||
/// `weight-medium`.
|
||||
pub weight_medium: u16,
|
||||
/// `weight-semibold`.
|
||||
pub weight_semibold: u16,
|
||||
/// `weight-bold`.
|
||||
pub weight_bold: u16,
|
||||
/// `row-height` (scaled).
|
||||
pub row_height: f32,
|
||||
/// `control-height` (scaled).
|
||||
pub control_height: f32,
|
||||
/// `control-height-sm` (scaled).
|
||||
pub control_height_sm: f32,
|
||||
/// `icon-sm`.
|
||||
pub icon_sm: f32,
|
||||
/// `icon-md`.
|
||||
pub icon_md: f32,
|
||||
/// `icon-lg`.
|
||||
pub icon_lg: f32,
|
||||
/// `glow-width`: the ring around focused and selected items.
|
||||
pub glow_width: f32,
|
||||
/// `rail-width`.
|
||||
pub rail_width: f32,
|
||||
/// `sidebar-width`: 264 and more with large text.
|
||||
pub sidebar_width: f32,
|
||||
/// `topbar-height`: 44, taller when large text makes the controls taller.
|
||||
pub topbar_height: f32,
|
||||
/// `right-panel-min`.
|
||||
pub right_panel_min: f32,
|
||||
/// `fast`, in milliseconds.
|
||||
pub fast_ms: u32,
|
||||
/// `normal`, in milliseconds.
|
||||
pub normal_ms: u32,
|
||||
}
|
||||
|
||||
impl Metrics {
|
||||
/// The tokens at a text size factor (1 is the default).
|
||||
pub fn new(font_scale: f32) -> Self {
|
||||
let s = font_scale;
|
||||
let control_height = 36.0 * s;
|
||||
let space_3 = 8.0;
|
||||
Self {
|
||||
font_scale,
|
||||
radius_xs: 4.0,
|
||||
radius_sm: 6.0,
|
||||
radius_md: 8.0,
|
||||
radius_lg: 12.0,
|
||||
radius_xl: 16.0,
|
||||
radius_pill: 999.0,
|
||||
space_1: 2.0,
|
||||
space_2: 4.0,
|
||||
space_3,
|
||||
space_4: 12.0,
|
||||
space_5: 16.0,
|
||||
space_6: 20.0,
|
||||
space_7: 24.0,
|
||||
space_8: 32.0,
|
||||
font_xs: 11.0 * s,
|
||||
font_sm: 12.0 * s,
|
||||
font_body: 14.0 * s,
|
||||
font_md: 15.0 * s,
|
||||
font_lg: 17.0 * s,
|
||||
font_xl: 20.0 * s,
|
||||
font_2xl: 24.0 * s,
|
||||
font_3xl: 30.0 * s,
|
||||
weight_regular: 400,
|
||||
weight_medium: 500,
|
||||
weight_semibold: 600,
|
||||
weight_bold: 700,
|
||||
row_height: 32.0 * s,
|
||||
control_height,
|
||||
control_height_sm: 28.0 * s,
|
||||
icon_sm: 16.0,
|
||||
icon_md: 20.0,
|
||||
icon_lg: 24.0,
|
||||
glow_width: 2.0,
|
||||
rail_width: 72.0,
|
||||
sidebar_width: 264.0 * s.max(1.0),
|
||||
topbar_height: 44.0_f32.max(control_height + space_3),
|
||||
right_panel_min: 220.0,
|
||||
fast_ms: 120,
|
||||
normal_ms: 200,
|
||||
}
|
||||
}
|
||||
|
||||
/// Every number token by the name it has in `theme.slint`, in its order:
|
||||
/// lengths in pixels, weights as they are, durations in milliseconds.
|
||||
pub fn entries(&self) -> Vec<(&'static str, f64)> {
|
||||
let m = self;
|
||||
[
|
||||
("radius-xs", m.radius_xs),
|
||||
("radius-sm", m.radius_sm),
|
||||
("radius-md", m.radius_md),
|
||||
("radius-lg", m.radius_lg),
|
||||
("radius-xl", m.radius_xl),
|
||||
("radius-pill", m.radius_pill),
|
||||
("space-1", m.space_1),
|
||||
("space-2", m.space_2),
|
||||
("space-3", m.space_3),
|
||||
("space-4", m.space_4),
|
||||
("space-5", m.space_5),
|
||||
("space-6", m.space_6),
|
||||
("space-7", m.space_7),
|
||||
("space-8", m.space_8),
|
||||
("font-xs", m.font_xs),
|
||||
("font-sm", m.font_sm),
|
||||
("font-body", m.font_body),
|
||||
("font-md", m.font_md),
|
||||
("font-lg", m.font_lg),
|
||||
("font-xl", m.font_xl),
|
||||
("font-2xl", m.font_2xl),
|
||||
("font-3xl", m.font_3xl),
|
||||
("row-height", m.row_height),
|
||||
("control-height", m.control_height),
|
||||
("control-height-sm", m.control_height_sm),
|
||||
("icon-sm", m.icon_sm),
|
||||
("icon-md", m.icon_md),
|
||||
("icon-lg", m.icon_lg),
|
||||
("glow-width", m.glow_width),
|
||||
("rail-width", m.rail_width),
|
||||
("sidebar-width", m.sidebar_width),
|
||||
("topbar-height", m.topbar_height),
|
||||
("right-panel-min", m.right_panel_min),
|
||||
]
|
||||
.into_iter()
|
||||
.map(|(name, value)| (name, f64::from(value)))
|
||||
.chain([
|
||||
("weight-regular", f64::from(m.weight_regular)),
|
||||
("weight-medium", f64::from(m.weight_medium)),
|
||||
("weight-semibold", f64::from(m.weight_semibold)),
|
||||
("weight-bold", f64::from(m.weight_bold)),
|
||||
("fast", f64::from(m.fast_ms)),
|
||||
("normal", f64::from(m.normal_ms)),
|
||||
])
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for Metrics {
|
||||
fn default() -> Self {
|
||||
Self::new(1.0)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
//! The window's content. The shell is not built yet (slice 1 of the
|
||||
//! migration): the window is the theme's page with the one line of the root
|
||||
//! state that proves the loops run in a status bar, or, with
|
||||
//! `VOELIN_OPEN=swatch`, the swatch page above that bar.
|
||||
|
||||
use gpui_kit::{
|
||||
Context, Entity, IntoElement, ParentElement as _, Render, Styled as _, Window, div, px,
|
||||
};
|
||||
|
||||
use crate::app::AppState;
|
||||
use crate::dev::Page;
|
||||
use crate::meter::Counters;
|
||||
use crate::swatch::swatch;
|
||||
use crate::theme::{VoelinTheme, hsla};
|
||||
|
||||
/// What the main window draws, from the root state and the theme.
|
||||
pub struct MainView {
|
||||
app: Entity<AppState>,
|
||||
page: Page,
|
||||
counters: Counters,
|
||||
}
|
||||
|
||||
impl MainView {
|
||||
/// A view of `app` that draws again whenever it changes, and that keeps
|
||||
/// the theme in `system` mode in step with the window's appearance.
|
||||
pub fn new(
|
||||
app: Entity<AppState>,
|
||||
page: Page,
|
||||
counters: Counters,
|
||||
window: &mut Window,
|
||||
cx: &mut Context<Self>,
|
||||
) -> Self {
|
||||
cx.observe(&app, |_, _, cx| cx.notify()).detach();
|
||||
cx.observe_window_appearance(window, |_, window, cx| {
|
||||
VoelinTheme::set_system_appearance(cx, window.appearance());
|
||||
})
|
||||
.detach();
|
||||
Self { app, page, counters }
|
||||
}
|
||||
}
|
||||
|
||||
impl Render for MainView {
|
||||
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
|
||||
self.counters.renders.incr();
|
||||
let line = self.app.read(cx).state_line();
|
||||
let theme = VoelinTheme::global(cx).clone();
|
||||
let (c, m) = (&theme.colors, &theme.metrics);
|
||||
let page = match self.page {
|
||||
Page::Swatch => div().flex_1().overflow_hidden().child(swatch(&theme)),
|
||||
Page::Shell => div()
|
||||
.flex_1()
|
||||
.flex()
|
||||
.flex_col()
|
||||
.items_center()
|
||||
.justify_center()
|
||||
.gap(px(m.space_3))
|
||||
.child(
|
||||
div()
|
||||
.text_size(px(m.font_3xl))
|
||||
.text_color(hsla(c.text))
|
||||
.child(voelin_platform::APP_NAME),
|
||||
)
|
||||
.child(
|
||||
div()
|
||||
.text_size(px(m.font_body))
|
||||
.text_color(hsla(c.text_muted))
|
||||
.child("The desktop shell is the next slice."),
|
||||
),
|
||||
};
|
||||
div()
|
||||
.size_full()
|
||||
.flex()
|
||||
.flex_col()
|
||||
.bg(hsla(c.bg_app))
|
||||
.text_color(hsla(c.text))
|
||||
.font_family(crate::theme::FONT_FAMILY)
|
||||
.child(page)
|
||||
.child(
|
||||
div()
|
||||
.h(px(m.control_height_sm))
|
||||
.px(px(m.space_5))
|
||||
.flex()
|
||||
.items_center()
|
||||
.bg(hsla(c.surface))
|
||||
.border_t_1()
|
||||
.border_color(hsla(c.border))
|
||||
.text_size(px(m.font_sm))
|
||||
.text_color(hsla(c.text_secondary))
|
||||
.child(line),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
//! The binary's failure path, end to end: when the main window cannot be
|
||||
//! opened (no display server, no Vulkan or GL driver), `voelin-gpui` prints
|
||||
//! why and exits with status 1 instead of staying alive with no window and no
|
||||
//! message.
|
||||
//!
|
||||
//! It has to start the real binary. GPUI's Linux platform runs the launch
|
||||
//! callback before it starts its event loop, and the loop forgets a quit asked
|
||||
//! for before it started, so a failure handled by quitting inside the
|
||||
//! callback hung the process; the test platform of the unit tests has no such
|
||||
//! loop and cannot show it.
|
||||
//!
|
||||
//! The no-driver test needs a test X server in `VOELIN_X11_TEST_DISPLAY` (an
|
||||
//! Xvfb, as CI has; never the desktop's display) and is skipped without one.
|
||||
|
||||
#![cfg(target_os = "linux")]
|
||||
|
||||
use std::fs;
|
||||
use std::os::unix::fs::PermissionsExt as _;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Command, ExitStatus, Stdio};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
/// Where the drivers are not: the Vulkan loader, EGL's vendor library
|
||||
/// directory and Mesa's driver directory all point here.
|
||||
const NOWHERE: &str = "/nonexistent-voelin-gpui-test";
|
||||
|
||||
/// Loaded machines are slow, so the wait is generous; a run that works takes a
|
||||
/// second or two.
|
||||
const WAIT: Duration = Duration::from_secs(120);
|
||||
|
||||
/// The scratch directory of one run, removed at the end.
|
||||
struct Scratch(PathBuf);
|
||||
|
||||
impl Drop for Scratch {
|
||||
fn drop(&mut self) {
|
||||
let _ = fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
/// How a run of the binary went.
|
||||
enum Outcome {
|
||||
/// It ended, with this status and this much of the log.
|
||||
Ended(ExitStatus, String),
|
||||
/// It picked a GPU: the window can open, so nothing failed.
|
||||
Opened,
|
||||
/// It was still running after [`WAIT`] with no GPU picked.
|
||||
Hung(String),
|
||||
}
|
||||
|
||||
/// Run the binary with the drivers hidden (`hide_drivers`) on `display`
|
||||
/// (none: no display server at all) and wait for it to end, to pick a GPU or
|
||||
/// to run out of time. Nothing of the user's state, display or session bus is
|
||||
/// in its environment.
|
||||
fn run_binary(name: &str, display: Option<&str>, hide_drivers: bool) -> Outcome {
|
||||
let scratch = Scratch(
|
||||
Path::new(env!("CARGO_TARGET_TMPDIR")).join(format!("{name}-{}", std::process::id())),
|
||||
);
|
||||
let home = scratch.0.join("home");
|
||||
let runtime = scratch.0.join("runtime");
|
||||
fs::create_dir_all(&runtime).unwrap();
|
||||
fs::set_permissions(&runtime, fs::Permissions::from_mode(0o700)).unwrap();
|
||||
let log = scratch.0.join("stderr.log");
|
||||
|
||||
let mut command = Command::new(env!("CARGO_BIN_EXE_voelin-gpui"));
|
||||
command
|
||||
.env_remove("DISPLAY")
|
||||
.env_remove("WAYLAND_DISPLAY")
|
||||
.env_remove("WAYLAND_SOCKET")
|
||||
.env_remove("XDG_SESSION_TYPE")
|
||||
.env_remove("DBUS_SESSION_BUS_ADDRESS")
|
||||
.env_remove("RUST_LOG")
|
||||
.env("HOME", &home)
|
||||
.env("XDG_RUNTIME_DIR", &runtime)
|
||||
.env("XDG_CONFIG_HOME", home.join("config"))
|
||||
.env("XDG_DATA_HOME", home.join("data"))
|
||||
.env("XDG_STATE_HOME", home.join("state"))
|
||||
.env("XDG_CACHE_HOME", home.join("cache"))
|
||||
.env("VOELIN_DATA_DIR", home.join("voelin"))
|
||||
// The log line that tells a GPU was picked.
|
||||
.env("VOELIN_LOG", "warn,voelin_gpui=info,gpui_wgpu=info")
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::null())
|
||||
.stderr(fs::File::create(&log).unwrap());
|
||||
if let Some(display) = display {
|
||||
command.env("DISPLAY", display);
|
||||
}
|
||||
if hide_drivers {
|
||||
command
|
||||
.env("VK_DRIVER_FILES", format!("{NOWHERE}/vulkan.json"))
|
||||
.env("VK_ICD_FILENAMES", format!("{NOWHERE}/vulkan.json"))
|
||||
.env("__EGL_VENDOR_LIBRARY_DIRS", NOWHERE)
|
||||
.env("__EGL_VENDOR_LIBRARY_FILENAMES", format!("{NOWHERE}/egl.json"))
|
||||
.env("LIBGL_DRIVERS_PATH", NOWHERE);
|
||||
}
|
||||
let mut child = command.spawn().unwrap();
|
||||
|
||||
let deadline = Instant::now() + WAIT;
|
||||
loop {
|
||||
if let Some(status) = child.try_wait().unwrap() {
|
||||
return Outcome::Ended(status, fs::read_to_string(&log).unwrap_or_default());
|
||||
}
|
||||
let seen = fs::read_to_string(&log).unwrap_or_default();
|
||||
let outcome = if seen.contains("Selected GPU adapter") {
|
||||
Outcome::Opened
|
||||
} else if Instant::now() > deadline {
|
||||
Outcome::Hung(seen)
|
||||
} else {
|
||||
std::thread::sleep(Duration::from_millis(50));
|
||||
continue;
|
||||
};
|
||||
let _ = child.kill();
|
||||
let _ = child.wait();
|
||||
return outcome;
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_window_that_cannot_open_for_want_of_a_driver_ends_the_binary_with_an_error() {
|
||||
let Some(display) = std::env::var("VOELIN_X11_TEST_DISPLAY").ok().filter(|d| !d.is_empty())
|
||||
else {
|
||||
eprintln!("skipped: VOELIN_X11_TEST_DISPLAY is not set");
|
||||
return;
|
||||
};
|
||||
match run_binary("no-driver", Some(&display), true) {
|
||||
Outcome::Ended(status, seen) => {
|
||||
assert_eq!(status.code(), Some(1), "{seen}");
|
||||
assert!(seen.contains("cannot open the main window"), "{seen}");
|
||||
}
|
||||
Outcome::Opened => eprintln!(
|
||||
"skipped: this machine's driver was found in spite of the environment, \
|
||||
so the window can open"
|
||||
),
|
||||
Outcome::Hung(seen) => panic!(
|
||||
"still running after {WAIT:?} with no window and no GPU: a quit asked for in the \
|
||||
launch callback is lost\n{seen}"
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn without_a_display_server_the_binary_ends_with_an_error() {
|
||||
match run_binary("no-display", None, false) {
|
||||
Outcome::Ended(status, seen) => {
|
||||
assert_eq!(status.code(), Some(1), "{seen}");
|
||||
assert!(seen.contains("cannot open the main window"), "{seen}");
|
||||
assert!(seen.contains("no display"), "{seen}");
|
||||
}
|
||||
Outcome::Opened => panic!("a GPU was picked without a display server"),
|
||||
Outcome::Hung(seen) => panic!(
|
||||
"still running after {WAIT:?} with no window: GPUI's headless platform keeps \
|
||||
the app alive\n{seen}"
|
||||
),
|
||||
}
|
||||
}
|
||||
@@ -40,11 +40,9 @@ wlroots = ["dep:wayland-client", "dep:wayland-protocols", "dep:wayland-protocols
|
||||
# model (PP-HumanSeg, ONNX, bundled in `models/`) run on the CPU by tract.
|
||||
# Without it the background is cut around a centred oval.
|
||||
segment = ["dep:tract-onnx"]
|
||||
# Conversion between `Codec` and `str0m::format::Codec`.
|
||||
str0m = ["dep:str0m"]
|
||||
# The studio's WHIP output: a WebRTC session (str0m) set up over HTTP. Needs
|
||||
# str0m's crypto provider, the same one voelin-stream uses.
|
||||
whip = ["str0m", "str0m/aws-lc-rs", "dep:reqwest"]
|
||||
whip = ["str0m/aws-lc-rs", "dep:reqwest"]
|
||||
|
||||
[dependencies]
|
||||
bzip2 = { version = "0.6.1", optional = true }
|
||||
@@ -61,7 +59,9 @@ serde = { version = "1", features = ["derive"] }
|
||||
ab_glyph = "0.2.32"
|
||||
image = { version = "0.25.10", default-features = false, features = ["jpeg", "png"] }
|
||||
sha2 = { version = "0.10.9", optional = true }
|
||||
str0m = { version = "0.23.1", default-features = false, optional = true }
|
||||
# Its media types (`MediaKind`, `MediaTime`) are in `stream::EncodedFrame`, and
|
||||
# `Codec` converts to and from its codec type.
|
||||
str0m = { version = "0.23.1", default-features = false }
|
||||
thiserror = "2.0.21"
|
||||
tract-onnx = { version = "0.23.8", optional = true }
|
||||
tokio = { version = "1", features = ["sync"] }
|
||||
@@ -69,7 +69,13 @@ tracing = "0.1.44"
|
||||
yuv = "0.8.19"
|
||||
|
||||
[target.'cfg(target_os = "linux")'.dependencies]
|
||||
ashpd = { version = "0.13.13", default-features = false, features = ["camera", "screencast", "tokio"], optional = true }
|
||||
# `async-io`, not `tokio`: GPUI's Linux backend enables ashpd's `async-io`, ashpd
|
||||
# refuses both at once, and a front end holds the portals and GPUI in one binary.
|
||||
# zbus then runs every connection on an I/O thread of its own, whichever thread
|
||||
# builds it: no crate of the workspace turns zbus's `tokio` feature on (with it
|
||||
# zbus would pick tokio for a connection made inside a tokio runtime, and ashpd
|
||||
# shares one connection per process with every later caller).
|
||||
ashpd = { version = "0.13.13", default-features = false, features = ["camera", "screencast", "async-io"], optional = true }
|
||||
memmap2 = { version = "0.9.11", optional = true }
|
||||
pipewire = { version = "0.10.1", optional = true }
|
||||
rustix = { version = "1.1.5", features = ["event", "fs", "stdio"], optional = true }
|
||||
@@ -97,8 +103,10 @@ criterion = "0.8"
|
||||
opus2 = "0.4"
|
||||
serde_json = "1"
|
||||
# The H.264 `profile-level-id` the signalling offers, to check it against the
|
||||
# SPS the encoders really emit (`tests/ffmpeg.rs`). No cycle: voelin-stream
|
||||
# does not depend on this crate.
|
||||
# SPS the encoders really emit (`tests/ffmpeg.rs`). A cycle through a
|
||||
# dev-dependency, which cargo allows: voelin-stream depends on this crate for
|
||||
# the frame and layer types, so this crate's unit tests see itself twice, and
|
||||
# only primitives and voelin-stream's own types cross between the copies.
|
||||
voelin-stream = { path = "../voelin-stream" }
|
||||
# Logs of integration tests (`RUST_LOG`).
|
||||
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
|
||||
|
||||
@@ -279,14 +279,14 @@ impl FrameSink for QueueSink {
|
||||
pub fn forward(mut frames: FrameReceiver<VideoFrame>, mut sink: Box<dyn FrameSink>) -> Result<()> {
|
||||
std::thread::Builder::new().name("voelin-capture-forward".into()).spawn(move || {
|
||||
loop {
|
||||
match frames.recv_timeout(Duration::from_millis(100)) {
|
||||
Some(frame) => {
|
||||
if sink.wants(frame.timestamp) && !sink.frame(frame.view()) {
|
||||
break;
|
||||
}
|
||||
let Some(frame) = frames.recv_timeout(Duration::from_millis(100)) else {
|
||||
if frames.is_closed() {
|
||||
break;
|
||||
}
|
||||
None if frames.is_closed() => break,
|
||||
None => {}
|
||||
continue;
|
||||
};
|
||||
if sink.wants(frame.timestamp) && !sink.frame(frame.view()) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
})?;
|
||||
|
||||
@@ -181,7 +181,9 @@ impl ScreenCapture for PortalCapture {
|
||||
}
|
||||
|
||||
/// Asks the user through the portal dialog (unless a restore token
|
||||
/// applies). Needs a tokio runtime (the D-Bus connection runs on it).
|
||||
/// applies). Any executor will do: ashpd runs on zbus's `async-io` in every
|
||||
/// binary of the workspace (no crate turns zbus's `tokio` feature on), whose
|
||||
/// connection has an I/O thread of its own, whichever thread builds it.
|
||||
fn start(
|
||||
&mut self,
|
||||
source: &SourceId,
|
||||
|
||||
@@ -95,7 +95,6 @@ impl FromStr for Codec {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "str0m")]
|
||||
impl From<Codec> for str0m::format::Codec {
|
||||
fn from(c: Codec) -> Self {
|
||||
match c {
|
||||
@@ -108,7 +107,6 @@ impl From<Codec> for str0m::format::Codec {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "str0m")]
|
||||
impl TryFrom<str0m::format::Codec> for Codec {
|
||||
type Error = Error;
|
||||
|
||||
@@ -226,7 +224,9 @@ pub struct EncodedChunk<'a> {
|
||||
pub pts_90khz: u64,
|
||||
}
|
||||
|
||||
/// One encoded frame, ready for `voelin_stream::Peer::write`.
|
||||
/// One frame as an encoder makes it. A stream takes it as a
|
||||
/// [`stream::EncodedFrame`](crate::stream::EncodedFrame), which adds the kind
|
||||
/// of media, the RTP time and the layer.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct EncodedFrame {
|
||||
pub data: Vec<u8>,
|
||||
@@ -1039,7 +1039,6 @@ mod tests {
|
||||
assert_eq!(Codec::Av1.to_string(), "AV1");
|
||||
}
|
||||
|
||||
#[cfg(feature = "str0m")]
|
||||
#[test]
|
||||
fn str0m_mapping() {
|
||||
for c in Codec::ALL {
|
||||
|
||||
@@ -446,7 +446,7 @@ fn files_in(dir: &Path, base: &str) -> Vec<PathBuf> {
|
||||
matches.then(|| (major_of(&name).unwrap_or(0), e.path()))
|
||||
})
|
||||
.collect();
|
||||
found.sort_by(|a, b| b.0.cmp(&a.0));
|
||||
found.sort_by_key(|entry| std::cmp::Reverse(entry.0));
|
||||
found.into_iter().map(|(_, p)| p).collect()
|
||||
}
|
||||
|
||||
@@ -466,7 +466,7 @@ fn ldconfig(base: &str) -> Vec<PathBuf> {
|
||||
name.starts_with(&prefix).then(|| (major_of(name).unwrap_or(0), PathBuf::from(path)))
|
||||
})
|
||||
.collect();
|
||||
found.sort_by(|a, b| b.0.cmp(&a.0));
|
||||
found.sort_by_key(|entry| std::cmp::Reverse(entry.0));
|
||||
found.into_iter().map(|(_, p)| p).collect()
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,210 @@
|
||||
//! Simulcast layers: several encodings of one stream, each with its own size,
|
||||
//! frame rate and bitrate.
|
||||
//!
|
||||
//! The streamer encodes every layer of its [`LayerSpec`] list and tags each
|
||||
//! [`EncodedFrame`](crate::stream::EncodedFrame) with its [`LayerId`]. Each
|
||||
//! viewer connection gets the layer that fits its bandwidth estimate; peers
|
||||
//! that negotiate RID simulcast (`a=simulcast`) get all of them. There is no
|
||||
//! limit on the number of layers.
|
||||
//!
|
||||
//! The types are the media side's vocabulary; the stream transports (the
|
||||
//! `voelin-stream` crate, and whatever else carries a stream) and the client
|
||||
//! engine use them as they are.
|
||||
|
||||
use std::fmt;
|
||||
|
||||
/// A simulcast layer. Layer 0 is the one a stream without simulcast has.
|
||||
pub type LayerId = u16;
|
||||
|
||||
/// One encoding of the stream. Compared bit for bit (`scale` by its bits),
|
||||
/// so it is `Eq`.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct LayerSpec {
|
||||
pub id: LayerId,
|
||||
/// Output size relative to the source (1.0: the source's size). Ignored
|
||||
/// when [`size`](Self::size) is set.
|
||||
pub scale: f32,
|
||||
/// Exact output size in pixels, instead of `scale`.
|
||||
pub size: Option<(u32, u32)>,
|
||||
/// Frame rate cap; `None`: the source's frame rate.
|
||||
pub max_fps: Option<u32>,
|
||||
/// Bitrate the encoder starts with, in bit/s. Bandwidth estimates move it
|
||||
/// down (and back up to this value, or [`max_bitrate`](Self::max_bitrate)).
|
||||
pub bitrate: u64,
|
||||
/// Highest bitrate bandwidth estimates may raise the layer to; `None`: no
|
||||
/// maximum.
|
||||
pub max_bitrate: Option<u64>,
|
||||
/// Estimate (bit/s) a viewer needs to receive this layer; below it the
|
||||
/// viewer moves to the next smaller layer.
|
||||
pub min_bitrate: u64,
|
||||
/// RTP stream id for peers that negotiate RID simulcast.
|
||||
pub rid: Option<String>,
|
||||
}
|
||||
|
||||
impl PartialEq for LayerSpec {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.id == other.id
|
||||
&& self.scale.to_bits() == other.scale.to_bits()
|
||||
&& self.size == other.size
|
||||
&& self.max_fps == other.max_fps
|
||||
&& self.bitrate == other.bitrate
|
||||
&& self.max_bitrate == other.max_bitrate
|
||||
&& self.min_bitrate == other.min_bitrate
|
||||
&& self.rid == other.rid
|
||||
}
|
||||
}
|
||||
|
||||
impl Eq for LayerSpec {}
|
||||
|
||||
impl LayerSpec {
|
||||
/// A stream without simulcast: layer 0 at the source's size and rate.
|
||||
pub fn single(bitrate: u64) -> Self {
|
||||
Self {
|
||||
id: 0,
|
||||
scale: 1.0,
|
||||
size: None,
|
||||
max_fps: None,
|
||||
bitrate,
|
||||
max_bitrate: None,
|
||||
min_bitrate: 0,
|
||||
rid: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Output size for a source of `width` x `height`: [`size`](Self::size),
|
||||
/// or the scaled source size rounded down to even numbers (I420), at least
|
||||
/// 2x2.
|
||||
pub fn output_size(&self, width: u32, height: u32) -> (u32, u32) {
|
||||
let (w, h) = self.size.unwrap_or_else(|| {
|
||||
let scale = if self.scale.is_finite() && self.scale > 0.0 { self.scale } else { 1.0 };
|
||||
((width as f32 * scale) as u32, (height as f32 * scale) as u32)
|
||||
});
|
||||
((w & !1).max(2), (h & !1).max(2))
|
||||
}
|
||||
}
|
||||
|
||||
/// A set of layers, e.g. those waiting for a keyframe. Grows as needed.
|
||||
#[derive(Clone, Default, PartialEq, Eq)]
|
||||
pub struct LayerSet {
|
||||
words: Vec<u64>,
|
||||
}
|
||||
|
||||
impl LayerSet {
|
||||
pub const fn new() -> Self {
|
||||
Self { words: Vec::new() }
|
||||
}
|
||||
|
||||
/// Adds `layer`; `true` if it was not in the set.
|
||||
pub fn insert(&mut self, layer: LayerId) -> bool {
|
||||
let (word, bit) = Self::position(layer);
|
||||
if self.words.len() <= word {
|
||||
self.words.resize(word + 1, 0);
|
||||
}
|
||||
let new = self.words[word] & bit == 0;
|
||||
self.words[word] |= bit;
|
||||
new
|
||||
}
|
||||
|
||||
/// Removes `layer`; `true` if it was in the set.
|
||||
pub fn remove(&mut self, layer: LayerId) -> bool {
|
||||
let (word, bit) = Self::position(layer);
|
||||
match self.words.get_mut(word) {
|
||||
Some(w) if *w & bit != 0 => {
|
||||
*w &= !bit;
|
||||
true
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn contains(&self, layer: LayerId) -> bool {
|
||||
let (word, bit) = Self::position(layer);
|
||||
self.words.get(word).is_some_and(|w| w & bit != 0)
|
||||
}
|
||||
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.words.iter().all(|w| *w == 0)
|
||||
}
|
||||
|
||||
pub fn len(&self) -> usize {
|
||||
self.words.iter().map(|w| w.count_ones() as usize).sum()
|
||||
}
|
||||
|
||||
/// Empties the set, keeping its memory.
|
||||
pub fn clear(&mut self) {
|
||||
self.words.fill(0);
|
||||
}
|
||||
|
||||
/// Adds every layer of `other`.
|
||||
pub fn union_with(&mut self, other: &LayerSet) {
|
||||
if self.words.len() < other.words.len() {
|
||||
self.words.resize(other.words.len(), 0);
|
||||
}
|
||||
for (w, o) in self.words.iter_mut().zip(&other.words) {
|
||||
*w |= o;
|
||||
}
|
||||
}
|
||||
|
||||
/// The layers in ascending order.
|
||||
pub fn iter(&self) -> impl Iterator<Item = LayerId> + '_ {
|
||||
self.words.iter().enumerate().flat_map(|(i, &word)| {
|
||||
(0..64).filter(move |b| word & (1 << b) != 0).map(move |b| (i * 64 + b) as LayerId)
|
||||
})
|
||||
}
|
||||
|
||||
fn position(layer: LayerId) -> (usize, u64) {
|
||||
(usize::from(layer) / 64, 1 << (layer % 64))
|
||||
}
|
||||
}
|
||||
|
||||
impl FromIterator<LayerId> for LayerSet {
|
||||
fn from_iter<I: IntoIterator<Item = LayerId>>(iter: I) -> Self {
|
||||
let mut set = Self::new();
|
||||
for layer in iter {
|
||||
set.insert(layer);
|
||||
}
|
||||
set
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Debug for LayerSet {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.debug_set().entries(self.iter()).finish()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn layer_set() {
|
||||
let mut set = LayerSet::new();
|
||||
assert!(set.is_empty());
|
||||
assert!(set.insert(3));
|
||||
assert!(!set.insert(3));
|
||||
assert!(set.insert(200));
|
||||
assert!(set.insert(LayerId::MAX));
|
||||
assert_eq!(set.iter().collect::<Vec<_>>(), [3, 200, LayerId::MAX]);
|
||||
assert_eq!(set.len(), 3);
|
||||
assert!(set.contains(200) && !set.contains(4));
|
||||
assert!(set.remove(200) && !set.remove(200));
|
||||
let other: LayerSet = [1, 3].into_iter().collect();
|
||||
set.union_with(&other);
|
||||
assert_eq!(format!("{set:?}"), format!("{{1, 3, {}}}", LayerId::MAX));
|
||||
set.clear();
|
||||
assert!(set.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn output_size() {
|
||||
let mut layer = LayerSpec::single(1_000_000);
|
||||
assert_eq!(layer.output_size(1921, 1081), (1920, 1080));
|
||||
layer.scale = 0.5;
|
||||
assert_eq!(layer.output_size(2560, 1440), (1280, 720));
|
||||
layer.scale = 0.0001;
|
||||
assert_eq!(layer.output_size(640, 360), (2, 2));
|
||||
layer.size = Some((853, 480));
|
||||
assert_eq!(layer.output_size(1920, 1080), (852, 480));
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,10 @@
|
||||
//! (interleaved `f32`, 48 kHz)
|
||||
//! - [`convert`]: YUV ↔ RGB conversion (BT.601 limited range, the WebRTC
|
||||
//! default), e.g. RGBA for rendering and I420 for encoding
|
||||
//! - [`layer`] and [`stream`]: the simulcast layers of a stream
|
||||
//! ([`LayerSpec`]) and its frames on the way to the viewers
|
||||
//! ([`stream::EncodedFrame`], the encoder's frame plus kind, RTP time and
|
||||
//! layer)
|
||||
//! - [`codec`]: [`VideoEncoder`] / [`VideoDecoder`] traits, codec preference
|
||||
//! and the backends: libvpx (VP8/VP9, feature `vpx`), Cisco's OpenH264
|
||||
//! loaded at runtime (H.264, feature `openh264`), dav1d (AV1 decoding,
|
||||
@@ -24,8 +28,8 @@
|
||||
//! scaling and the [`scale::Pyramid`] of simulcast sizes), and
|
||||
//! [`convert::Converter`] (borrowed capture buffers straight to I420)
|
||||
//!
|
||||
//! Encoded frames go to `voelin_stream::Peer::write` with an RTP time of
|
||||
//! [`EncodedFrame::pts_90khz`] (90 kHz clock); received `MediaFrame`s go to
|
||||
//! Encoded frames go to a stream as [`stream::EncodedFrame`]s with an RTP time
|
||||
//! of [`EncodedFrame::pts_90khz`] (90 kHz clock); received `MediaFrame`s go to
|
||||
//! [`VideoDecoder::decode`].
|
||||
|
||||
pub mod capture;
|
||||
@@ -35,10 +39,12 @@ pub mod convert;
|
||||
pub mod ffmpeg;
|
||||
pub mod frame;
|
||||
pub mod handoff;
|
||||
pub mod layer;
|
||||
pub mod mix;
|
||||
pub mod pool;
|
||||
pub mod queue;
|
||||
pub mod scale;
|
||||
pub mod stream;
|
||||
pub mod studio;
|
||||
pub mod workers;
|
||||
|
||||
@@ -51,6 +57,7 @@ pub use codec::{
|
||||
pub use frame::{
|
||||
AudioBuffer, FrameData, FrameRef, GpuFrame, PixelFormat, PixelsRef, Plane, PlaneRef, VideoFrame,
|
||||
};
|
||||
pub use layer::{LayerId, LayerSet, LayerSpec};
|
||||
pub use queue::{FrameReceiver, FrameSender, frame_channel};
|
||||
|
||||
/// Errors of this crate.
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
//! The frames of a stream on their way to its viewers.
|
||||
//!
|
||||
//! An [`EncodedFrame`] is what the streamer's encoders and the Opus encoder
|
||||
//! hand to a stream: the encoder's output ([`codec::EncodedFrame`]) plus what
|
||||
//! the transport needs, which media it is, its RTP time and its simulcast
|
||||
//! layer. The engine's stream sink, the stream sessions (`voelin-stream`) and
|
||||
//! the tools that feed a stream by hand all pass it on unchanged.
|
||||
//!
|
||||
//! [`codec::EncodedFrame`]: crate::codec::EncodedFrame
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use str0m::media::{MediaKind, MediaTime};
|
||||
|
||||
use crate::layer::LayerId;
|
||||
|
||||
/// One encoded video or audio frame of a stream, ready to be sent.
|
||||
///
|
||||
/// Not the encoder's [`codec::EncodedFrame`](crate::codec::EncodedFrame),
|
||||
/// which has neither a kind nor a layer and counts time on the 90 kHz clock
|
||||
/// only.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct EncodedFrame {
|
||||
pub kind: MediaKind,
|
||||
/// RTP time: 90 kHz for video, 48 kHz for Opus.
|
||||
pub time: MediaTime,
|
||||
pub data: Arc<[u8]>,
|
||||
/// The simulcast layer of a video frame (0 without simulcast, and for
|
||||
/// audio).
|
||||
pub layer: LayerId,
|
||||
/// A video keyframe: viewers can start decoding (or switch to this layer)
|
||||
/// here.
|
||||
pub keyframe: bool,
|
||||
}
|
||||
@@ -603,8 +603,8 @@ mod v4l2 {
|
||||
// Seconds per frame; a stepwise range starts with its smallest
|
||||
// interval, which is the highest rate.
|
||||
let (num, den) = (entry.interval[0], entry.interval[1]);
|
||||
if num > 0 {
|
||||
best = best.max(den / num);
|
||||
if let Some(rate) = den.checked_div(num) {
|
||||
best = best.max(rate);
|
||||
}
|
||||
if entry.type_ != FRMIVAL_DISCRETE {
|
||||
break;
|
||||
|
||||
@@ -1180,19 +1180,32 @@ mod tests {
|
||||
scenes
|
||||
}
|
||||
|
||||
/// The first preview frame that `wanted` takes. The preview keeps the latest
|
||||
/// frame only, so few older ones are waiting or on their way: the number of
|
||||
/// frames looked at is the bound (the work), and the wait for each, which a
|
||||
/// busy machine can stretch, only ends a hang.
|
||||
fn preview_until(
|
||||
preview: &Handoff<VideoFrame>,
|
||||
wanted: impl Fn(&VideoFrame) -> bool,
|
||||
) -> Arc<VideoFrame> {
|
||||
for _ in 0..20 {
|
||||
let frame = preview.wait_timeout(Duration::from_secs(30)).expect("a preview frame");
|
||||
if wanted(&frame) {
|
||||
return frame;
|
||||
}
|
||||
}
|
||||
panic!("the preview never showed what was asked for");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn it_composes_into_the_preview_and_follows_commands() {
|
||||
let studio = Studio::start(one_colour_scene()).await.unwrap();
|
||||
let preview = studio.preview();
|
||||
studio.apply(Command::SetPreview { width: 32, height: 24, fps: 60 }).await.unwrap();
|
||||
let started = Instant::now();
|
||||
let frame = loop {
|
||||
if let Some(frame) = preview.wait_timeout(Duration::from_millis(200)) {
|
||||
break frame;
|
||||
}
|
||||
assert!(started.elapsed() < Duration::from_secs(5), "no preview frame");
|
||||
};
|
||||
assert_eq!((frame.width, frame.height), (32, 24));
|
||||
// The studio composes from the moment it starts, at the size and rate the
|
||||
// preview has then (480x270, 15 fps): a frame of that size can be the
|
||||
// first one there is.
|
||||
let frame = preview_until(&preview, |f| (f.width, f.height) == (32, 24));
|
||||
let crate::frame::FrameData::Rgba(p) = &frame.data else { panic!("not RGBA") };
|
||||
assert_eq!(&p.data[..4], &[9, 8, 7, 255]);
|
||||
|
||||
@@ -1211,15 +1224,12 @@ mod tests {
|
||||
.unwrap();
|
||||
studio.apply(Command::SetActiveScene { scene: break_id }).await.unwrap();
|
||||
assert_eq!(studio.status().active_scene, break_id);
|
||||
// The new scene's source draws.
|
||||
let frame = loop {
|
||||
let frame = preview.wait_timeout(Duration::from_secs(2)).expect("a preview frame");
|
||||
let crate::frame::FrameData::Rgba(p) = &frame.data else { panic!() };
|
||||
if p.data[..3] == [1, 2, 3] {
|
||||
break frame;
|
||||
}
|
||||
assert!(started.elapsed() < Duration::from_secs(10), "the scene never switched");
|
||||
};
|
||||
// The new scene's source draws, from the first frame composed after the
|
||||
// command.
|
||||
let frame = preview_until(
|
||||
&preview,
|
||||
|f| matches!(&f.data, crate::frame::FrameData::Rgba(p) if p.data[..3] == [1, 2, 3]),
|
||||
);
|
||||
drop(frame);
|
||||
|
||||
studio.apply(Command::RemoveScene { scene: break_id }).await.unwrap();
|
||||
@@ -1402,9 +1412,16 @@ mod tests {
|
||||
assert_eq!((listed[0].width, listed[0].height), (64, 48));
|
||||
let frames = capture.start(&SourceId::Studio, &CaptureOptions::default()).await.unwrap();
|
||||
let mut frames = frames;
|
||||
let frame = frames.recv_timeout(Duration::from_secs(5)).expect("a composed frame");
|
||||
// (The wait only ends a hang.)
|
||||
let frame = frames.recv_timeout(Duration::from_secs(30)).expect("a composed frame");
|
||||
assert_eq!((frame.width, frame.height), (64, 48));
|
||||
assert!(studio.shared.delivered.load(Ordering::Relaxed) > 0);
|
||||
// A frame is counted once it has been handed over, so the count can still be
|
||||
// behind when the frame is in the hands of the test.
|
||||
let deadline = Instant::now() + Duration::from_secs(30);
|
||||
while studio.shared.delivered.load(Ordering::Relaxed) == 0 {
|
||||
assert!(Instant::now() < deadline, "the frame handed over was never counted");
|
||||
std::thread::sleep(Duration::from_millis(5));
|
||||
}
|
||||
capture.stop();
|
||||
std::fs::remove_dir_all(&dir).ok();
|
||||
}
|
||||
|
||||
@@ -350,7 +350,22 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn an_unwritable_path_fails_at_once() {
|
||||
assert!(Recorder::start("/nonexistent-root-dir/x/clip.webm", 0, 2).is_err());
|
||||
assert!(Recorder::start("clip.mp4", 0, 2).is_err());
|
||||
let dir = dir("unwritable");
|
||||
// A path below a regular file fails for every user, root included
|
||||
// (ENOTDIR). A directory that is merely missing would be created, and
|
||||
// a read-only one is written to by root.
|
||||
let file = dir.join("not-a-directory");
|
||||
std::fs::write(&file, b"x").unwrap();
|
||||
assert!(Recorder::start(file.join("x").join("clip.webm"), 0, 2).is_err());
|
||||
// The directory is there and the file cannot be created because the
|
||||
// path names a directory (EISDIR, again for every user).
|
||||
let named_like_a_file = dir.join("clip.webm");
|
||||
std::fs::create_dir(&named_like_a_file).unwrap();
|
||||
assert!(Recorder::start(&named_like_a_file, 0, 2).is_err());
|
||||
// A name that asks for no known container is refused before any file
|
||||
// is created.
|
||||
assert!(Recorder::start(dir.join("clip.mp4"), 0, 2).is_err());
|
||||
assert!(!dir.join("clip.mp4").exists());
|
||||
std::fs::remove_dir_all(&dir).ok();
|
||||
}
|
||||
}
|
||||
Loaded 100 of 283 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user