Compare commits
48
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
|
||||
@@ -1,3 +1,4 @@
|
||||
/target/
|
||||
/dev/.state/
|
||||
/dist/
|
||||
/.cargo/
|
||||
@@ -69,6 +69,21 @@ User-visible changes of the apps and the `tsgw` gateway. The format follows
|
||||
|
||||
### Changed
|
||||
|
||||
- The view models, the app's state and the decisions of the settings pages and
|
||||
of the Stream Studio 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. Nothing changes on screen. 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 +195,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.
|
||||
|
||||
@@ -30,10 +30,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
+80
-10
@@ -1996,7 +1996,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb"
|
||||
dependencies = [
|
||||
"const-oid 0.9.6",
|
||||
"der_derive",
|
||||
"der_derive 0.7.3",
|
||||
"flagset",
|
||||
"pem-rfc7468 0.7.0",
|
||||
"zeroize",
|
||||
@@ -2009,6 +2009,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a878c850e9e421b20262e9b41f9c860e4785fa07541c266b62ff9d1ef998a80a"
|
||||
dependencies = [
|
||||
"const-oid 0.10.2",
|
||||
"der_derive 0.8.0",
|
||||
"flagset",
|
||||
"pem-rfc7468 1.0.0",
|
||||
"zeroize",
|
||||
]
|
||||
@@ -2038,6 +2040,17 @@ dependencies = [
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "der_derive"
|
||||
version = "0.8.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "59600e2c2d636fde9b65e99cc6445ac770c63d3628195ff39932b8d6d7409903"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "deranged"
|
||||
version = "0.5.8"
|
||||
@@ -2134,7 +2147,7 @@ dependencies = [
|
||||
"spki 0.7.3",
|
||||
"subtle",
|
||||
"time",
|
||||
"x509-cert",
|
||||
"x509-cert 0.2.5",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -7136,9 +7149,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustls"
|
||||
version = "0.23.45"
|
||||
version = "0.23.46"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0d41d731c7d2f962d1ccc364cec258de3c0e93b38c2fb3ba97ac74513048d634"
|
||||
checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf"
|
||||
dependencies = [
|
||||
"aws-lc-rs",
|
||||
"once_cell",
|
||||
@@ -9449,7 +9462,6 @@ dependencies = [
|
||||
"tokio",
|
||||
"tracing",
|
||||
"tracing-subscriber",
|
||||
"tsclientlib",
|
||||
"voelin-core",
|
||||
"voelin-media",
|
||||
"voelin-model",
|
||||
@@ -9474,8 +9486,6 @@ dependencies = [
|
||||
"sonora-simd",
|
||||
"thiserror 2.0.21",
|
||||
"tracing",
|
||||
"tsclientlib",
|
||||
"tsproto-packets",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -9563,6 +9573,23 @@ dependencies = [
|
||||
"voelin-model",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "voelin-identity"
|
||||
version = "0.2.0"
|
||||
source = "git+ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git?rev=64808ccbb1e3aa10213392724f2f436bc25fd36f#64808ccbb1e3aa10213392724f2f436bc25fd36f"
|
||||
dependencies = [
|
||||
"aws-lc-rs",
|
||||
"base64 0.23.1",
|
||||
"prost",
|
||||
"rcgen",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"thiserror 2.0.21",
|
||||
"voelin-proto",
|
||||
"x509-cert 0.3.0",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "voelin-media"
|
||||
version = "0.1.0"
|
||||
@@ -9642,6 +9669,17 @@ dependencies = [
|
||||
"zbus",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "voelin-proto"
|
||||
version = "0.2.0"
|
||||
source = "git+ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git?rev=64808ccbb1e3aa10213392724f2f436bc25fd36f#64808ccbb1e3aa10213392724f2f436bc25fd36f"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"prost",
|
||||
"thiserror 2.0.21",
|
||||
"tokio",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "voelin-query"
|
||||
version = "0.1.0"
|
||||
@@ -9665,7 +9703,9 @@ dependencies = [
|
||||
"serde",
|
||||
"serde_json",
|
||||
"thiserror 2.0.21",
|
||||
"tracing",
|
||||
"tsclientlib",
|
||||
"voelin-identity",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -9685,6 +9725,7 @@ dependencies = [
|
||||
"tracing-subscriber",
|
||||
"tsclientlib",
|
||||
"tsproto-packets",
|
||||
"voelin-media",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -9695,7 +9736,6 @@ dependencies = [
|
||||
"chrono",
|
||||
"dirs",
|
||||
"image",
|
||||
"miniz_oxide 0.8.9",
|
||||
"png",
|
||||
"serde",
|
||||
"serde_json",
|
||||
@@ -9713,6 +9753,25 @@ dependencies = [
|
||||
"voelin-platform",
|
||||
"voelin-query",
|
||||
"voelin-store",
|
||||
"voelin-ui-vm",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "voelin-ui-vm"
|
||||
version = "0.0.1-alpha"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"image",
|
||||
"miniz_oxide 0.8.9",
|
||||
"png",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"unicode-segmentation",
|
||||
"voelin-audio",
|
||||
"voelin-core",
|
||||
"voelin-gateway-proto",
|
||||
"voelin-model",
|
||||
"voelin-store",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -10852,6 +10911,17 @@ dependencies = [
|
||||
"spki 0.7.3",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "x509-cert"
|
||||
version = "0.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "105ef4642d9cb137ef83d623d0e4bf08b8adf69e9918ca904a174adb6d3d038b"
|
||||
dependencies = [
|
||||
"const-oid 0.10.2",
|
||||
"der 0.8.2",
|
||||
"spki 0.8.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "x509-parser"
|
||||
version = "0.18.1"
|
||||
@@ -10968,9 +11038,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "yoke-derive"
|
||||
version = "0.8.3"
|
||||
version = "0.8.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "33811428bee40dbceb6d545e95754741d17a6aef9a4849f0fd62e2ba4f412a78"
|
||||
checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
|
||||
+10
@@ -23,6 +23,7 @@ members = [
|
||||
"crates/voelin-store",
|
||||
"crates/voelin-stream",
|
||||
"crates/voelin-ui",
|
||||
"crates/voelin-ui-vm",
|
||||
"tools/voelinctl",
|
||||
]
|
||||
default-members = [
|
||||
@@ -43,6 +44,7 @@ default-members = [
|
||||
"crates/voelin-store",
|
||||
"crates/voelin-stream",
|
||||
"crates/voelin-ui",
|
||||
"crates/voelin-ui-vm",
|
||||
"tools/voelinctl",
|
||||
]
|
||||
|
||||
@@ -53,6 +55,14 @@ 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
|
||||
# that has the account-bound KeyStore (its Phase 2 task 28).
|
||||
voelin-identity = { git = "ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git", rev = "64808ccbb1e3aa10213392724f2f436bc25fd36f" }
|
||||
|
||||
[workspace.lints.rust]
|
||||
# deny, not forbid: generated code (Slint) needs a local allow.
|
||||
unsafe_code = "deny"
|
||||
|
||||
@@ -45,6 +45,9 @@ 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-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
|
||||
|
||||
@@ -175,7 +175,7 @@ the crate's authors are listed as its copyright holders.
|
||||
|
||||
| License | Crates |
|
||||
|---|---|
|
||||
| MIT License | 658 |
|
||||
| MIT License | 660 |
|
||||
| Apache License 2.0 | 31 |
|
||||
| Unicode License v3 | 26 |
|
||||
| BSD 3-Clause "New" or "Revised" License | 22 |
|
||||
@@ -4150,7 +4150,7 @@ DEALINGS IN THE SOFTWARE.
|
||||
|
||||
````
|
||||
|
||||
Used by: hyper-rustls 0.27.10, rustls-native-certs 0.8.4, rustls 0.23.45
|
||||
Used by: hyper-rustls 0.27.10, rustls-native-certs 0.8.4, rustls 0.23.46
|
||||
|
||||
````text
|
||||
Copyright (c) 2016 Joseph Birr-Pixton <jpixton@gmail.com>
|
||||
@@ -6994,7 +6994,7 @@ DEALINGS IN THE SOFTWARE.
|
||||
|
||||
````
|
||||
|
||||
Used by: cpufeatures 0.2.17
|
||||
Used by: cpufeatures 0.2.17, der_derive 0.8.0
|
||||
|
||||
````text
|
||||
Copyright (c) 2020-2025 The RustCrypto Project Developers
|
||||
@@ -7246,7 +7246,7 @@ DEALINGS IN THE SOFTWARE.
|
||||
|
||||
````
|
||||
|
||||
Used by: pem-rfc7468 1.0.0, pkcs1 0.8.0-rc.4
|
||||
Used by: pem-rfc7468 1.0.0, pkcs1 0.8.0-rc.4, x509-cert 0.3.0
|
||||
|
||||
````text
|
||||
Copyright (c) 2021-2025 The RustCrypto Project Developers
|
||||
@@ -11796,7 +11796,7 @@ authorization of the copyright holder.
|
||||
|
||||
````
|
||||
|
||||
Used by: fixed_decimal 0.7.2, icu_collections 2.3.0, icu_decimal 2.3.0, icu_decimal_data 2.3.0, icu_locale_core 2.3.0, icu_locale_fallback 2.3.0, icu_locale_fallback_data 2.3.0, icu_normalizer 2.3.0, icu_normalizer_data 2.3.0, icu_properties 2.3.0, icu_properties_data 2.3.0, icu_provider 2.3.1, icu_segmenter 2.3.0, icu_segmenter_data 2.3.0, litemap 0.8.3, potential_utf 0.1.6, tinystr 0.8.4, writeable 0.6.4, yoke-derive 0.8.3, yoke 0.8.3, zerofrom-derive 0.1.8, zerofrom 0.1.8, zerotrie 0.2.5, zerovec-derive 0.11.6, zerovec 0.11.8
|
||||
Used by: fixed_decimal 0.7.2, icu_collections 2.3.0, icu_decimal 2.3.0, icu_decimal_data 2.3.0, icu_locale_core 2.3.0, icu_locale_fallback 2.3.0, icu_locale_fallback_data 2.3.0, icu_normalizer 2.3.0, icu_normalizer_data 2.3.0, icu_properties 2.3.0, icu_properties_data 2.3.0, icu_provider 2.3.1, icu_segmenter 2.3.0, icu_segmenter_data 2.3.0, litemap 0.8.3, potential_utf 0.1.6, tinystr 0.8.4, writeable 0.6.4, yoke-derive 0.8.4, yoke 0.8.3, zerofrom-derive 0.1.8, zerofrom 0.1.8, zerotrie 0.2.5, zerovec-derive 0.11.6, zerovec 0.11.8
|
||||
|
||||
````text
|
||||
UNICODE LICENSE V3
|
||||
@@ -11991,7 +11991,8 @@ bzip2/libbzip2 version 1.1.0 of 6 September 2010
|
||||
|
||||
<!-- 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).
|
||||
|
||||
+2
-1
@@ -3,7 +3,8 @@
|
||||
|
||||
<!-- 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).
|
||||
|
||||
@@ -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).
|
||||
@@ -49,7 +50,7 @@ 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-media = { path = "../voelin-media", default-features = false }
|
||||
voelin-model = { path = "../voelin-model" }
|
||||
voelin-observer = { path = "../voelin-observer" }
|
||||
# Paths only (the cache directory).
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -3,7 +3,8 @@
|
||||
//! 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), made by a
|
||||
//! [`link::ServerLink`] ([`TsLink`] for TeamSpeak servers; see [`link`])
|
||||
//! - **gateway**: a `tsgw` gateway (invisible presence, relayed chat)
|
||||
//! - **query**: the user's own ServerQuery credentials (same, without a gateway)
|
||||
//!
|
||||
@@ -53,6 +54,7 @@ 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,8 +63,10 @@ mod route;
|
||||
mod session;
|
||||
pub mod settings;
|
||||
pub mod stream;
|
||||
mod stream_types;
|
||||
#[cfg(feature = "media")]
|
||||
pub mod studio;
|
||||
mod ts_link;
|
||||
pub mod versions;
|
||||
mod voice;
|
||||
mod web;
|
||||
@@ -76,7 +80,6 @@ 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 +91,15 @@ 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::ConnectOptions;
|
||||
pub use link::ConnectOptions as VoiceOptions;
|
||||
pub use link::ServerLink;
|
||||
pub use offline::{OfflineMessage, OfflineMessageInfo};
|
||||
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 ts_link::TsLink;
|
||||
/// 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).
|
||||
@@ -248,11 +252,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 {
|
||||
@@ -507,6 +513,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 +544,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 +792,19 @@ impl Engine {
|
||||
}
|
||||
|
||||
/// Start the engine on the current tokio runtime with `settings` and
|
||||
/// chat `history`.
|
||||
/// chat `history`, connecting voice with [`TsLink`].
|
||||
pub fn start_with(settings: Settings, history: History) -> Self {
|
||||
Self::start_with_link(settings, history, Arc::new(TsLink))
|
||||
}
|
||||
|
||||
/// Start the engine on the current tokio runtime with `settings` and
|
||||
/// chat `history`, connecting voice with `link` (every session's voice
|
||||
/// source is one of its connections, see [`link`]).
|
||||
pub fn start_with_link(
|
||||
settings: Settings,
|
||||
history: History,
|
||||
link: Arc<dyn ServerLink>,
|
||||
) -> Self {
|
||||
let (commands, rx) = mpsc::unbounded_channel();
|
||||
let (events, _) = broadcast::channel(4096);
|
||||
// About a minute of one watched stream.
|
||||
@@ -773,7 +816,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,6 +900,7 @@ async fn run(
|
||||
events: broadcast::Sender<Event>,
|
||||
frames: broadcast::Sender<StreamFrame>,
|
||||
engine: Shared,
|
||||
link: Arc<dyn ServerLink>,
|
||||
) {
|
||||
let Shared { settings: shared, history, cache, contacts } = engine.clone();
|
||||
// Before any command: a contact set meanwhile would be lost.
|
||||
@@ -869,7 +913,7 @@ async fn run(
|
||||
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! {
|
||||
@@ -1006,6 +1050,7 @@ async fn run(
|
||||
frames.clone(),
|
||||
settings.clone(),
|
||||
engine.clone(),
|
||||
link.clone(),
|
||||
myts_identity.subscribe(),
|
||||
myts_data.subscribe(),
|
||||
);
|
||||
@@ -1111,3 +1156,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,330 @@
|
||||
//! The seam between a session and the server it talks to as a client.
|
||||
//!
|
||||
//! 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. Everything the
|
||||
//! session needs from it goes through [`ServerLink`]: the session hands the
|
||||
//! link the connection's options and a [`LinkCtx`], and talks to it with two
|
||||
//! channels, [`LinkCmd`]s in and [`LinkEvent`]s out. Nothing else of the
|
||||
//! backend shows: the session merges, deduplicates, stores and routes what a
|
||||
//! link reports, whichever server software is behind it.
|
||||
//!
|
||||
//! # Contract for a link
|
||||
//!
|
||||
//! - [`ServerLink::spawn`] returns at once; the connection runs on its own
|
||||
//! task and reports through `events`. Connecting is not an event: the
|
||||
//! session shows `Connecting` from the moment it spawned the link, until
|
||||
//! [`LinkEvent::Connected`] (or [`LinkEvent::Disconnected`] if it failed).
|
||||
//! - The first thing a connected link reports is [`LinkEvent::Connected`]
|
||||
//! (name, backend, what it can do, our client id, the server's unique id),
|
||||
//! then [`LinkEvent::Presence`] whenever anything in the server's tree or
|
||||
//! client list changed (a full snapshot each time) and
|
||||
//! [`LinkEvent::OwnChannel`] when we moved.
|
||||
//! - [`LinkEvent::Disconnected`], with the reason if it was not asked for,
|
||||
//! reports that the connection ended, whichever way it did; a link sends it
|
||||
//! once, and nothing from the connection itself follows it. A link that
|
||||
//! gets [`LinkCmd::Disconnect`] (or whose command channel closes) leaves.
|
||||
//! It is not promised to be the last event of the link: the stream task of
|
||||
//! a connection with streams is a task of its own, which winds down after
|
||||
//! the connection, so [`LinkEvent::OwnStream`] (`Ended`) and
|
||||
//! [`LinkEvent::StreamAudioEnded`] from it, and the bus events of its
|
||||
//! streams, may follow `Disconnected` (`TsLink` ends the stream task as the
|
||||
//! connection's loop ends, which usually, not always, puts them before it).
|
||||
//! The session does not depend on the order: it ends our own stream and
|
||||
//! the audio of watched streams itself when it hears `Disconnected`, and
|
||||
//! ignores what a link says after that, like the events of a replaced one.
|
||||
//! - Streams (screen sharing) are the link's business from the capabilities
|
||||
//! on: when [`Capabilities::streams`] is set in `Connected`, it runs the
|
||||
//! stream task, takes [`LinkCmd::Stream`] and reports through the event
|
||||
//! bus ([`LinkCtx::emit`]) like the other answers that need not pass the
|
||||
//! session first (file lists, transfers, offline messages, stream state).
|
||||
//! What the session must place itself comes as events: our own stream's
|
||||
//! life ([`LinkEvent::OwnStream`], for the gateway directory) and the audio
|
||||
//! of watched streams ([`LinkEvent::StreamAudio`], for the audio thread,
|
||||
//! and [`LinkEvent::StreamAudioEnded`] when a stream's audio is over).
|
||||
//! When the session replaces a connection it gives the old link
|
||||
//! `StreamCmd::Shutdown` before [`LinkCmd::Disconnect`] (the streams hear
|
||||
//! of their end before the link stops reading commands).
|
||||
//! - What the session must see first (chat, pokes, who is talking, audio)
|
||||
//! comes as [`LinkEvent`]s; the answers to requests the UI made (a file
|
||||
//! list, a request's `Done`) go straight to the event bus with
|
||||
//! [`LinkCtx::emit`].
|
||||
//! - Events of a link the session replaced are ignored (each link has a
|
||||
//! generation), so a link need not stop emitting at once.
|
||||
//!
|
||||
//! # Implementations
|
||||
//!
|
||||
//! [`TsLink`](crate::TsLink) (`ts_link.rs`, with `voice.rs`) is the
|
||||
//! TeamSpeak 3 and 6 connection of `tsclientlib`; it is the only one for now,
|
||||
//! and [`Engine::start_with_link`](crate::Engine::start_with_link) takes
|
||||
//! another (the tests drive the session with an in-memory one,
|
||||
//! `tests/link_fake.rs`). The decoupling plan moves `TsLink` out of this
|
||||
//! crate into the TeamSpeak gateway (VoelinGateWay, `voelin-gateway-ts`), and
|
||||
//! the Voelin protocol's QUIC transport becomes the other implementation,
|
||||
//! both behind the backend-neutral `voelin_proto::link::Session` of
|
||||
//! VoelinProtocol; `ServerLink` is this crate's side of that seam until then.
|
||||
//!
|
||||
//! # What is still TeamSpeak's
|
||||
//!
|
||||
//! The seam is not backend-neutral yet. What still has TeamSpeak types or
|
||||
//! TeamSpeak's shape, and changes when `TsLink` leaves:
|
||||
//!
|
||||
//! - Types of the TeamSpeak crates: [`ConnectOptions::identity`] and
|
||||
//! [`ConnectOptions::client_version`] (`tsclientlib`), and the account
|
||||
//! proof in [`LinkCtx`] (`myts_identity` of `tsproto`, `myts_data` of
|
||||
//! `tsclientlib`).
|
||||
//! - Client ids are TeamSpeak's `u16`: `own_client` of
|
||||
//! [`LinkEvent::Connected`], `from` of [`LinkEvent::Poke`], `client` of
|
||||
//! [`LinkEvent::Talking`] and of [`LinkCmd::Poke`], the `author_id` of a
|
||||
//! [`ChatMessage`], and the viewer and streamer ids of the stream API.
|
||||
//! - [`LinkEvent::Presence`] snapshots have TeamSpeak's shape: `u16` client
|
||||
//! ids, `u64` channel and group ids, server and channel groups, talk
|
||||
//! power, icons, badges and the myTeamSpeak avatar.
|
||||
//! - The stream vocabulary is that of `voelin-stream`, the TeamSpeak 6 stream
|
||||
//! protocol: `PeerConfig` in [`ConnectOptions::stream_peer`], `MediaFrame`
|
||||
//! in the frames of watched streams ([`LinkCtx`]), `VideoFormat` in
|
||||
//! `StreamCmd::VideoFrame`, and `VideoCodec` and `FrameSource` of the same
|
||||
//! API (re-exported from [`crate::stream`]).
|
||||
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
|
||||
use tokio::sync::{broadcast, mpsc, watch};
|
||||
use voelin_audio::{EncodedVoice, VoicePacket};
|
||||
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};
|
||||
|
||||
/// Starts the voice connection of a session.
|
||||
///
|
||||
/// One link serves every session of an engine; [`spawn`](Self::spawn) starts
|
||||
/// one connection.
|
||||
pub 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 connection needs to know: the server, who to be, where to join.
|
||||
/// ([`VoiceOptions`](crate::VoiceOptions) is the name the app uses for it.)
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct ConnectOptions {
|
||||
pub address: String,
|
||||
pub nickname: String,
|
||||
/// The identity to connect with (TeamSpeak's, for now).
|
||||
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 (TeamSpeak 6).
|
||||
pub stream_peer: PeerConfig,
|
||||
}
|
||||
|
||||
impl ConnectOptions {
|
||||
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 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,
|
||||
/// The main account's proof, for every connection ([`crate::Command::SetMytsIdentity`]).
|
||||
pub(crate) myts_identity: watch::Receiver<Option<Arc<tsproto::myts::Identity>>>,
|
||||
/// What the server is shown of the account ([`crate::Command::SetMytsData`]).
|
||||
pub(crate) myts_data: watch::Receiver<Option<Arc<tsclientlib::MytsData>>>,
|
||||
}
|
||||
|
||||
impl LinkCtx {
|
||||
/// The session this connection belongs to.
|
||||
pub fn session(&self) -> SessionId {
|
||||
self.session
|
||||
}
|
||||
|
||||
/// Tell the engine's event bus something (a request's answer, a
|
||||
/// transfer's progress).
|
||||
pub 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 struct Remote {
|
||||
pub channel: ChannelId,
|
||||
pub password: Option<String>,
|
||||
pub path: String,
|
||||
}
|
||||
|
||||
/// What the session asks of a connection.
|
||||
pub 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),
|
||||
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 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,
|
||||
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>),
|
||||
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).
|
||||
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
|
||||
/// ([`ConnectOptions::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>),
|
||||
}
|
||||
@@ -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
|
||||
|
||||
+155
-165
@@ -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, ServerLink};
|
||||
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};
|
||||
|
||||
@@ -80,19 +78,30 @@ pub(crate) struct SessionHandle {
|
||||
}
|
||||
|
||||
impl SessionHandle {
|
||||
#[allow(clippy::too_many_arguments)] // what the engine hands each session
|
||||
pub fn spawn(
|
||||
id: SessionId,
|
||||
events: broadcast::Sender<Event>,
|
||||
frames: broadcast::Sender<StreamFrame>,
|
||||
audio_settings: AudioSettings,
|
||||
shared: Shared,
|
||||
link: Arc<dyn ServerLink>,
|
||||
myts_identity: watch::Receiver<Option<Arc<tsproto::myts::Identity>>>,
|
||||
myts_data: watch::Receiver<Option<Arc<tsclientlib::MytsData>>>,
|
||||
) -> Self {
|
||||
let (tx, rx) = mpsc::unbounded_channel();
|
||||
tokio::spawn(
|
||||
Session::new(id, events, frames, audio_settings, shared, myts_identity, myts_data)
|
||||
.run(rx),
|
||||
Session::new(
|
||||
id,
|
||||
events,
|
||||
frames,
|
||||
audio_settings,
|
||||
shared,
|
||||
link,
|
||||
myts_identity,
|
||||
myts_data,
|
||||
)
|
||||
.run(rx),
|
||||
);
|
||||
Self { tx }
|
||||
}
|
||||
@@ -105,13 +114,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 +297,15 @@ struct OwnStream {
|
||||
}
|
||||
|
||||
struct Session {
|
||||
/// Starts the voice connections.
|
||||
link: Arc<dyn ServerLink>,
|
||||
myts_identity: watch::Receiver<Option<Arc<tsproto::myts::Identity>>>,
|
||||
myts_data: watch::Receiver<Option<Arc<tsclientlib::MytsData>>>,
|
||||
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 +327,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>,
|
||||
@@ -380,12 +386,14 @@ struct Session {
|
||||
}
|
||||
|
||||
impl Session {
|
||||
#[allow(clippy::too_many_arguments)] // what the engine hands each session
|
||||
fn new(
|
||||
id: SessionId,
|
||||
events: broadcast::Sender<Event>,
|
||||
frames: broadcast::Sender<StreamFrame>,
|
||||
audio_settings: AudioSettings,
|
||||
shared: Shared,
|
||||
link: Arc<dyn ServerLink>,
|
||||
myts_identity: watch::Receiver<Option<Arc<tsproto::myts::Identity>>>,
|
||||
myts_data: watch::Receiver<Option<Arc<tsclientlib::MytsData>>>,
|
||||
) -> Self {
|
||||
@@ -393,6 +401,7 @@ impl Session {
|
||||
let Shared { settings, history, cache, contacts } = shared;
|
||||
let contacts_rx = Some(contacts.watch());
|
||||
Self {
|
||||
link,
|
||||
myts_identity,
|
||||
myts_data,
|
||||
cache,
|
||||
@@ -434,12 +443,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 +516,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 +541,15 @@ 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(),
|
||||
myts_identity: self.myts_identity.clone(),
|
||||
myts_data: self.myts_data.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 +558,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, .. } => {
|
||||
@@ -626,7 +636,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 +667,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 +679,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 +702,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 +716,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 +762,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 +800,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 +852,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,17 +860,17 @@ 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(_)
|
||||
@@ -894,7 +890,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 +921,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 +934,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 +943,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 +979,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 +1399,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 +1432,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 +1458,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 +1496,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 +1714,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 +1735,7 @@ impl Session {
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
streams.send(StreamInput::Directory(entries));
|
||||
self.stream_cmd(StreamCmd::Directory(entries));
|
||||
}
|
||||
|
||||
fn register_own_stream(&mut self) {
|
||||
@@ -1834,7 +1840,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 +1864,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 +1873,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 +1898,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 +1926,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 +1950,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 +1979,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 +1992,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();
|
||||
@@ -2298,6 +2286,7 @@ mod banner_tests {
|
||||
frames,
|
||||
AudioSettings::default(),
|
||||
shared,
|
||||
Arc::new(crate::TsLink),
|
||||
myts_identity,
|
||||
myts_data,
|
||||
);
|
||||
@@ -2386,7 +2375,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 +2422,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 +2964,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>;
|
||||
|
||||
+500
-155
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),
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
//! [`TsLink`]: the TeamSpeak implementation of [`ServerLink`].
|
||||
//!
|
||||
//! It connects as a normal TeamSpeak 3 or 6 client with `tsclientlib` and
|
||||
//! runs the connection ([`crate::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 tokio::sync::mpsc;
|
||||
|
||||
use crate::link::{ConnectOptions, LinkCmd, LinkCtx, LinkEvent, ServerLink};
|
||||
use crate::voice;
|
||||
|
||||
/// Connects to TeamSpeak 3 and 6 servers. The engine's default link.
|
||||
#[derive(Clone, Copy, Debug, Default)]
|
||||
pub struct TsLink;
|
||||
|
||||
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, cmds, events));
|
||||
}
|
||||
}
|
||||
+391
-260
@@ -1,19 +1,26 @@
|
||||
//! The voice source: a normal client connection.
|
||||
//! The TeamSpeak link: a normal client connection ([`crate::TsLink`] runs
|
||||
//! [`run`]).
|
||||
//!
|
||||
//! Besides presence, chat, voice and stream signalling it carries what only
|
||||
//! a client connection can do: pokes, file transfer (channel files,
|
||||
//! avatars, icons) and offline messages. Their answers go straight to the
|
||||
//! engine's event bus ([`VoiceLink`]); what the session must see first
|
||||
//! (chat, pokes: blocking) comes as [`VoiceEvent`]s.
|
||||
//! engine's event bus ([`LinkCtx`]); what the session must see first
|
||||
//! (chat, pokes: blocking) comes as [`LinkEvent`]s.
|
||||
//!
|
||||
//! On TeamSpeak 6 servers the connection also runs the stream task
|
||||
//! ([`crate::stream`]): it hands the task the server's stream notifications
|
||||
//! and the clients' channels, and sends the requests the task makes. The
|
||||
//! session only sees the commands it gave ([`LinkCmd::Stream`]) and, for the
|
||||
//! gateway directory, our own stream's life ([`LinkEvent::OwnStream`]).
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::collections::{BTreeMap, HashMap};
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use base64::Engine as _;
|
||||
use futures::prelude::*;
|
||||
use tokio::sync::{broadcast, mpsc, watch};
|
||||
use tokio::sync::{mpsc, watch};
|
||||
use tokio::task::AbortHandle;
|
||||
use tokio::time::{Instant, timeout};
|
||||
use tracing::{debug, info, warn};
|
||||
@@ -21,85 +28,22 @@ use tsclientlib::events::Event as BookEvent;
|
||||
use tsclientlib::messages::c2s;
|
||||
use tsclientlib::prelude::*;
|
||||
use tsclientlib::{
|
||||
Connection, DisconnectOptions, FiletransferHandle, Identity, InMessage, MessageHandle,
|
||||
MessageTarget, StreamItem, TsError, Version,
|
||||
Connection, DisconnectOptions, FiletransferHandle, InMessage, MessageHandle, MessageTarget,
|
||||
StreamItem, TsError,
|
||||
};
|
||||
use tsproto_packets::packets::{AudioData, InAudioBuf, OutCommand, OutPacket};
|
||||
use voelin_model::{ChannelId, ChatMessage, ChatTarget, Presence, ServerFlavor};
|
||||
use voelin_stream::{PeerConfig, Request, StreamNotification};
|
||||
use tsproto_packets::packets::{AudioData, CodecType, InAudioBuf, OutAudio, OutCommand, OutPacket};
|
||||
use voelin_audio::{EncodedVoice, TalkerId, VoiceCodec, VoicePacket};
|
||||
use voelin_model::{Capabilities, ChannelId, ChatMessage, ChatTarget, ServerFlavor};
|
||||
use voelin_stream::{ClientState, Request, StreamNotification};
|
||||
|
||||
use crate::book::presence_from_book;
|
||||
use crate::cache;
|
||||
use crate::files::{self, FileEntry, Report, RequestId, Sink, TransferId, TransferState};
|
||||
use crate::link::{ConnectOptions, LinkCmd, LinkCtx, LinkEvent, Remote};
|
||||
use crate::offline::{OfflineMessage, OfflineMessageInfo};
|
||||
use crate::settings::{FILES_PROGRESS_MS, SharedSettings};
|
||||
use crate::{Event, JoinFailure, POKE_MESSAGE_MAX, SessionId};
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct VoiceOptions {
|
||||
pub address: String,
|
||||
pub nickname: String,
|
||||
pub identity: Option<Identity>,
|
||||
/// Signed compatibility version; `None` selects the native platform's tuple.
|
||||
pub client_version: Option<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 (TeamSpeak 6).
|
||||
pub stream_peer: PeerConfig,
|
||||
}
|
||||
|
||||
impl VoiceOptions {
|
||||
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(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Where a voice connection reports answers the session does not need to see.
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct VoiceLink {
|
||||
pub myts_identity: watch::Receiver<Option<Arc<tsproto::myts::Identity>>>,
|
||||
/// What the server is shown of the account ([`crate::Command::SetMytsData`]).
|
||||
pub myts_data: watch::Receiver<Option<Arc<tsclientlib::MytsData>>>,
|
||||
pub session: SessionId,
|
||||
pub events: broadcast::Sender<Event>,
|
||||
pub settings: SharedSettings,
|
||||
}
|
||||
|
||||
impl VoiceLink {
|
||||
fn emit(&self, event: Event) {
|
||||
let _ = self.events.send(event);
|
||||
}
|
||||
|
||||
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,
|
||||
}
|
||||
use crate::settings::FILES_PROGRESS_MS;
|
||||
use crate::stream::{StreamCmd, StreamHandle, StreamInput};
|
||||
use crate::{BackendInfo, Event, JoinFailure, POKE_MESSAGE_MAX};
|
||||
|
||||
impl Remote {
|
||||
fn cpw(&self) -> String {
|
||||
@@ -114,116 +58,19 @@ fn encode_password(password: Option<&str>) -> String {
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
pub(crate) enum VoiceCmd {
|
||||
SendChat(ChatTarget, String),
|
||||
Move(ChannelId, Option<String>),
|
||||
SetInputMuted(bool),
|
||||
SetOutputMuted(bool),
|
||||
/// An encoded voice packet from the audio thread.
|
||||
Audio(OutPacket),
|
||||
/// A stream command; failures come back as [`VoiceEvent::StreamRequestFailed`].
|
||||
Stream(Request),
|
||||
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),
|
||||
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,
|
||||
},
|
||||
/// `clientupdate client_flag_avatar` (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,
|
||||
}
|
||||
|
||||
pub(crate) enum VoiceEvent {
|
||||
Connected {
|
||||
name: String,
|
||||
flavor: ServerFlavor,
|
||||
own_client: u16,
|
||||
/// The server's unique id (from its public key, as the server
|
||||
/// generation computes it).
|
||||
server_uid: String,
|
||||
/// Our unique id as the server knows it.
|
||||
own_uid: Option<String>,
|
||||
},
|
||||
Presence(Box<Presence>),
|
||||
OwnChannel(ChannelId),
|
||||
Chat(ChatMessage),
|
||||
Poke {
|
||||
from: u16,
|
||||
from_uid: Option<String>,
|
||||
from_name: String,
|
||||
message: String,
|
||||
},
|
||||
/// Incoming voice for the audio thread, and who is talking.
|
||||
Audio(InAudioBuf),
|
||||
Talking {
|
||||
client: u16,
|
||||
talking: bool,
|
||||
},
|
||||
Stream(StreamNotification),
|
||||
StreamRequestFailed(Request, String),
|
||||
/// A command failed (the connection stays).
|
||||
Error(String),
|
||||
Disconnected(Option<String>),
|
||||
/// What the engine is told of the server this connection reached: the
|
||||
/// product and version to show, and what the product can do. The flavor
|
||||
/// (TeamSpeak 3 or 6) is decided here, from the version the server sent, and
|
||||
/// goes no further.
|
||||
fn backend_of(flavor: &ServerFlavor) -> (BackendInfo, Capabilities) {
|
||||
let (product, version) = match flavor {
|
||||
ServerFlavor::Ts3(version) => ("TeamSpeak 3", version.to_string()),
|
||||
ServerFlavor::Ts6(version) => ("TeamSpeak 6", version.to_string()),
|
||||
// Not recognised: the version string as it came, for the status
|
||||
// line and the log.
|
||||
ServerFlavor::Unknown(raw) => ("", raw.clone()),
|
||||
};
|
||||
(BackendInfo { product: product.into(), version }, flavor.capabilities())
|
||||
}
|
||||
|
||||
fn now_ms() -> i64 {
|
||||
@@ -264,7 +111,9 @@ enum Input {
|
||||
MytsDataChanged,
|
||||
AccountSourceClosed,
|
||||
Item(Option<Result<StreamItem, tsclientlib::Error>>),
|
||||
Cmd(Option<VoiceCmd>),
|
||||
Cmd(Option<LinkCmd>),
|
||||
/// A request of the stream task, for the server.
|
||||
Request(Request),
|
||||
Tick,
|
||||
}
|
||||
|
||||
@@ -302,7 +151,7 @@ enum Pending {
|
||||
Move {
|
||||
channel: ChannelId,
|
||||
},
|
||||
/// Failures are reported as [`VoiceEvent::Error`] with this label.
|
||||
/// Failures are reported as [`LinkEvent::Error`] with this label.
|
||||
Report(&'static str),
|
||||
/// Best effort: the answer does not matter.
|
||||
Quiet,
|
||||
@@ -370,23 +219,42 @@ enum Slot {
|
||||
|
||||
/// Run a voice connection until it ends or is told to disconnect.
|
||||
pub(crate) async fn run(
|
||||
options: VoiceOptions,
|
||||
link: VoiceLink,
|
||||
mut commands: mpsc::UnboundedReceiver<VoiceCmd>,
|
||||
events: mpsc::UnboundedSender<VoiceEvent>,
|
||||
options: ConnectOptions,
|
||||
ctx: LinkCtx,
|
||||
mut commands: mpsc::UnboundedReceiver<LinkCmd>,
|
||||
events: mpsc::UnboundedSender<LinkEvent>,
|
||||
) {
|
||||
let reason = match run_inner(&options, link, &mut commands, &events).await {
|
||||
let reason = match run_inner(&options, ctx, &mut commands, &events).await {
|
||||
Ok(()) => None,
|
||||
Err(e) => Some(e.to_string()),
|
||||
};
|
||||
let _ = events.send(VoiceEvent::Disconnected(reason));
|
||||
let _ = events.send(LinkEvent::Disconnected(reason));
|
||||
}
|
||||
|
||||
/// The stream task of a connection. When the connection ends, in whatever
|
||||
/// way, its streams end with it.
|
||||
struct ConnectionStreams(StreamHandle);
|
||||
|
||||
impl ConnectionStreams {
|
||||
fn send(&self, input: impl Into<StreamInput>) {
|
||||
self.0.send(input);
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for ConnectionStreams {
|
||||
fn drop(&mut self) {
|
||||
// After a `StreamCmd::Shutdown` of the session this reaches a task
|
||||
// that has ended, which is fine; the task keeps a sender of its own,
|
||||
// so it never ends by itself.
|
||||
self.0.send(StreamCmd::Shutdown("voice disconnected".into()));
|
||||
}
|
||||
}
|
||||
|
||||
/// The state of a connected voice source.
|
||||
struct Voice {
|
||||
con: Connection,
|
||||
link: VoiceLink,
|
||||
events: mpsc::UnboundedSender<VoiceEvent>,
|
||||
link: LinkCtx,
|
||||
events: mpsc::UnboundedSender<LinkEvent>,
|
||||
server_uid: String,
|
||||
/// Who is talking: last voice packet per client.
|
||||
talking: HashMap<u16, Instant>,
|
||||
@@ -399,13 +267,17 @@ struct Voice {
|
||||
/// What this connection has shown the server of the account (avatar,
|
||||
/// badges, User Tag): what changes, and what a sign-out clears.
|
||||
myts_shown: tsclientlib::MytsData,
|
||||
/// The streams of the connection (TeamSpeak 6 servers).
|
||||
streams: Option<ConnectionStreams>,
|
||||
/// The clients as last told to the streams: channel and `client_is_streaming`.
|
||||
streaming_clients: BTreeMap<u16, ClientState>,
|
||||
}
|
||||
|
||||
async fn run_inner(
|
||||
options: &VoiceOptions,
|
||||
link: VoiceLink,
|
||||
commands: &mut mpsc::UnboundedReceiver<VoiceCmd>,
|
||||
events: &mpsc::UnboundedSender<VoiceEvent>,
|
||||
options: &ConnectOptions,
|
||||
link: LinkCtx,
|
||||
commands: &mut mpsc::UnboundedReceiver<LinkCmd>,
|
||||
events: &mpsc::UnboundedSender<LinkEvent>,
|
||||
) -> anyhow::Result<()> {
|
||||
let version = match &options.client_version {
|
||||
Some(version) => version.clone(),
|
||||
@@ -467,7 +339,10 @@ async fn run_inner(
|
||||
})
|
||||
.await
|
||||
.map_err(|_| anyhow::anyhow!("timed out while connecting"))??;
|
||||
let server_uid = {
|
||||
// The requests the stream task makes; `requests_tx` stays here, so the
|
||||
// channel is open (and empty) also where there is no stream task.
|
||||
let (requests_tx, mut requests) = mpsc::unbounded_channel();
|
||||
let (server_uid, streams) = {
|
||||
let state = con.get_state()?;
|
||||
let flavor = ServerFlavor::from_version_string(&state.server.version);
|
||||
let ids = voelin_gateway_proto::UniqueIds::from_omega(&state.server.public_key.to_ts());
|
||||
@@ -478,14 +353,31 @@ async fn run_inner(
|
||||
.get(&state.own_client)
|
||||
.and_then(|c| c.uid.as_ref())
|
||||
.map(|u| u.as_ref().to_string());
|
||||
let _ = events.send(VoiceEvent::Connected {
|
||||
let (backend, capabilities) = backend_of(&flavor);
|
||||
// Before the session hears of the connection, so that the commands it
|
||||
// then gives find the task.
|
||||
let streams = capabilities.streams.then(|| {
|
||||
ConnectionStreams(StreamHandle::spawn(
|
||||
link.session,
|
||||
state.own_client.0,
|
||||
options.stream_peer.clone(),
|
||||
requests_tx.clone(),
|
||||
link.events.clone(),
|
||||
link.frames.clone(),
|
||||
options.audio,
|
||||
link.settings.clone(),
|
||||
events.clone(),
|
||||
))
|
||||
});
|
||||
let _ = events.send(LinkEvent::Connected {
|
||||
name: state.server.name.clone(),
|
||||
flavor,
|
||||
backend,
|
||||
capabilities,
|
||||
own_client: state.own_client.0,
|
||||
server_uid: server_uid.clone(),
|
||||
own_uid,
|
||||
});
|
||||
server_uid
|
||||
(server_uid, streams)
|
||||
};
|
||||
// Subscribe to all channels to see everyone.
|
||||
let cmd = con.get_state()?.server.set_subscribed(true);
|
||||
@@ -501,6 +393,8 @@ async fn run_inner(
|
||||
transfers: HashMap::new(),
|
||||
myts_data_due: false,
|
||||
myts_shown: tsclientlib::MytsData::default(),
|
||||
streams,
|
||||
streaming_clients: BTreeMap::new(),
|
||||
};
|
||||
voice.publish_state()?;
|
||||
// The account's avatar, badges and User Tag, for everyone on the
|
||||
@@ -517,9 +411,15 @@ async fn run_inner(
|
||||
}) {
|
||||
break Err(anyhow::anyhow!("myTeamSpeak account update timed out"));
|
||||
}
|
||||
let input =
|
||||
next_input(&mut voice.con.events(), commands, &mut tick, &mut identity, &mut data)
|
||||
.await;
|
||||
let input = next_input(
|
||||
&mut voice.con.events(),
|
||||
commands,
|
||||
&mut requests,
|
||||
&mut tick,
|
||||
&mut identity,
|
||||
&mut data,
|
||||
)
|
||||
.await;
|
||||
match input {
|
||||
Input::AccountSourceClosed => break Err(anyhow::anyhow!("account source closed")),
|
||||
Input::MytsIdentityChanged => {
|
||||
@@ -547,15 +447,25 @@ async fn run_inner(
|
||||
break Err(e);
|
||||
}
|
||||
}
|
||||
Input::Cmd(None) | Input::Cmd(Some(VoiceCmd::Disconnect)) => break Ok(()),
|
||||
Input::Cmd(None) | Input::Cmd(Some(LinkCmd::Disconnect)) => break Ok(()),
|
||||
Input::Cmd(Some(cmd)) => {
|
||||
if let Err(e) = voice.command(cmd) {
|
||||
let _ = voice.events.send(VoiceEvent::Error(e.to_string()));
|
||||
let _ = voice.events.send(LinkEvent::Error(e.to_string()));
|
||||
}
|
||||
}
|
||||
Input::Request(request) => {
|
||||
if let Err(e) = voice.stream_request(request) {
|
||||
let _ = voice.events.send(LinkEvent::Error(e.to_string()));
|
||||
}
|
||||
}
|
||||
Input::Tick => voice.tick(),
|
||||
}
|
||||
};
|
||||
// The streams end now, not after the shutdown below (up to three seconds):
|
||||
// the commands are not read any more, so a `StreamCmd::Shutdown` the
|
||||
// session sends from here on would never reach the stream task. Its end
|
||||
// needs nothing of the connection: it reports to the session's channels.
|
||||
drop(voice.streams.take());
|
||||
// Transfers the server never opened fail; running ones go on.
|
||||
for (_, job) in voice.jobs.drain() {
|
||||
job.report()(TransferState::Failed("disconnected".into()));
|
||||
@@ -568,7 +478,8 @@ async fn run_inner(
|
||||
|
||||
async fn next_input(
|
||||
stream: &mut (impl Stream<Item = Result<StreamItem, tsclientlib::Error>> + Unpin),
|
||||
commands: &mut mpsc::UnboundedReceiver<VoiceCmd>,
|
||||
commands: &mut mpsc::UnboundedReceiver<LinkCmd>,
|
||||
requests: &mut mpsc::UnboundedReceiver<Request>,
|
||||
tick: &mut tokio::time::Interval,
|
||||
identity: &mut watch::Receiver<Option<Arc<tsproto::myts::Identity>>>,
|
||||
data: &mut watch::Receiver<Option<Arc<tsclientlib::MytsData>>>,
|
||||
@@ -590,6 +501,7 @@ async fn next_input(
|
||||
// the audio command queue remains ready.
|
||||
tokio::select! {
|
||||
cmd = commands.recv() => Input::Cmd(cmd),
|
||||
Some(request) = requests.recv() => Input::Request(request),
|
||||
_ = tick.tick() => Input::Tick,
|
||||
item = stream.next() => Input::Item(item),
|
||||
}
|
||||
@@ -616,13 +528,25 @@ async fn shutdown_connection(mut con: Connection) -> Result<(), tsclientlib::Err
|
||||
}
|
||||
|
||||
impl Voice {
|
||||
fn publish_state(&self) -> anyhow::Result<()> {
|
||||
fn publish_state(&mut self) -> anyhow::Result<()> {
|
||||
let state = self.con.get_state()?;
|
||||
let talking = |id| self.talking.contains_key(&id);
|
||||
let presence = presence_from_book(state, Some(&self.server_uid), talking);
|
||||
let _ = self.events.send(VoiceEvent::Presence(Box::new(presence)));
|
||||
// The streams follow the clients' channels and streaming flags.
|
||||
if let Some(streams) = &self.streams {
|
||||
let clients: BTreeMap<_, _> = presence
|
||||
.clients
|
||||
.values()
|
||||
.map(|c| (c.id, ClientState { channel: c.channel, streaming: c.streaming }))
|
||||
.collect();
|
||||
if clients != self.streaming_clients {
|
||||
self.streaming_clients = clients.clone();
|
||||
streams.send(StreamInput::Clients(clients));
|
||||
}
|
||||
}
|
||||
let _ = self.events.send(LinkEvent::Presence(Box::new(presence)));
|
||||
if let Some(own) = state.clients.get(&state.own_client) {
|
||||
let _ = self.events.send(VoiceEvent::OwnChannel(own.channel.0));
|
||||
let _ = self.events.send(LinkEvent::OwnChannel(own.channel.0));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -633,7 +557,7 @@ impl Voice {
|
||||
self.talking.retain(|client, last| {
|
||||
let active = last.elapsed() < Duration::from_millis(400);
|
||||
if !active {
|
||||
let _ = events.send(VoiceEvent::Talking { client: *client, talking: false });
|
||||
let _ = events.send(LinkEvent::Talking { client: *client, talking: false });
|
||||
}
|
||||
active
|
||||
});
|
||||
@@ -663,9 +587,11 @@ impl Voice {
|
||||
_ => return Ok(()),
|
||||
};
|
||||
if self.talking.insert(from, Instant::now()).is_none() {
|
||||
let _ = self.events.send(VoiceEvent::Talking { client: from, talking: true });
|
||||
let _ = self.events.send(LinkEvent::Talking { client: from, talking: true });
|
||||
}
|
||||
if let Some(packet) = voice_packet(&packet) {
|
||||
let _ = self.events.send(LinkEvent::Audio(packet));
|
||||
}
|
||||
let _ = self.events.send(VoiceEvent::Audio(packet));
|
||||
}
|
||||
StreamItem::MessageEvent(msg) => self.message_event(&msg),
|
||||
StreamItem::MessageResult(handle, result) => {
|
||||
@@ -767,7 +693,7 @@ impl Voice {
|
||||
let uid = invoker.uid.as_ref().map(|u| u.as_ref().to_string());
|
||||
let target = match target {
|
||||
MessageTarget::Poke(_) => {
|
||||
let _ = self.events.send(VoiceEvent::Poke {
|
||||
let _ = self.events.send(LinkEvent::Poke {
|
||||
from: invoker.id.0,
|
||||
from_uid: uid,
|
||||
from_name: invoker.name.to_string(),
|
||||
@@ -784,7 +710,7 @@ impl Voice {
|
||||
}
|
||||
MessageTarget::Client(_) => ChatTarget::Private(uid.clone().unwrap_or_default()),
|
||||
};
|
||||
let _ = self.events.send(VoiceEvent::Chat(ChatMessage {
|
||||
let _ = self.events.send(LinkEvent::Chat(ChatMessage {
|
||||
target,
|
||||
author_name: invoker.name.to_string(),
|
||||
author_uid: uid,
|
||||
@@ -852,8 +778,10 @@ impl Voice {
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
for n in StreamNotification::from_message(msg) {
|
||||
let _ = self.events.send(VoiceEvent::Stream(n));
|
||||
if let Some(streams) = &self.streams {
|
||||
for n in StreamNotification::from_message(msg) {
|
||||
streams.send(StreamInput::Notification(n));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -875,9 +803,8 @@ impl Voice {
|
||||
};
|
||||
match pending {
|
||||
Pending::Stream(request) => {
|
||||
if let Err(e) = result {
|
||||
let _ =
|
||||
self.events.send(VoiceEvent::StreamRequestFailed(request, e.to_string()));
|
||||
if let (Err(e), Some(streams)) = (result, &self.streams) {
|
||||
streams.send(StreamInput::RequestFailed(request, e.to_string()));
|
||||
}
|
||||
}
|
||||
Pending::FileList { request, channel, path, entries } => {
|
||||
@@ -931,7 +858,7 @@ impl Voice {
|
||||
},
|
||||
Pending::Report(what) => {
|
||||
if let Err(e) = result {
|
||||
let _ = self.events.send(VoiceEvent::Error(format!("{what}: {e}")));
|
||||
let _ = self.events.send(LinkEvent::Error(format!("{what}: {e}")));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1066,9 +993,15 @@ impl Voice {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn command(&mut self, cmd: VoiceCmd) -> anyhow::Result<()> {
|
||||
/// Send a request of the stream task to the server.
|
||||
fn stream_request(&mut self, request: Request) -> anyhow::Result<()> {
|
||||
let cmd = request.to_command();
|
||||
self.send(cmd, Pending::Stream(request))
|
||||
}
|
||||
|
||||
fn command(&mut self, cmd: LinkCmd) -> anyhow::Result<()> {
|
||||
match cmd {
|
||||
VoiceCmd::SendChat(target, text) => {
|
||||
LinkCmd::SendChat(target, text) => {
|
||||
let state = self.con.get_state()?;
|
||||
let out = match target {
|
||||
ChatTarget::Server => state.server.send_textmessage(&text),
|
||||
@@ -1089,7 +1022,7 @@ impl Voice {
|
||||
};
|
||||
self.send(out, Pending::Report("message"))?;
|
||||
}
|
||||
VoiceCmd::Move(channel, password) => {
|
||||
LinkCmd::Move(channel, password) => {
|
||||
let own = self.con.get_state()?.own_client;
|
||||
let cpw = encode_password(password.as_deref());
|
||||
let cmd =
|
||||
@@ -1100,19 +1033,20 @@ impl Voice {
|
||||
}));
|
||||
self.send(cmd, Pending::Move { channel })?;
|
||||
}
|
||||
VoiceCmd::SetInputMuted(muted) => {
|
||||
LinkCmd::SetInputMuted(muted) => {
|
||||
self.con.get_state()?.client_update().set_input_muted(muted).send(&mut self.con)?;
|
||||
}
|
||||
VoiceCmd::SetOutputMuted(muted) => {
|
||||
LinkCmd::SetOutputMuted(muted) => {
|
||||
let update = self.con.get_state()?.client_update().set_output_muted(muted);
|
||||
update.send(&mut self.con)?;
|
||||
}
|
||||
VoiceCmd::Audio(packet) => self.con.send_audio(packet)?,
|
||||
VoiceCmd::Stream(request) => {
|
||||
let cmd = request.to_command();
|
||||
self.send(cmd, Pending::Stream(request))?;
|
||||
LinkCmd::Audio(voice) => self.con.send_audio(out_audio(&voice))?,
|
||||
LinkCmd::Stream(cmd) => {
|
||||
if let Some(streams) = &self.streams {
|
||||
streams.send(cmd);
|
||||
}
|
||||
}
|
||||
VoiceCmd::Poke { client, message } => {
|
||||
LinkCmd::Poke { client, message } => {
|
||||
let cmd = c2s::OutClientPokeRequestMessage::new(&mut std::iter::once(
|
||||
c2s::OutClientPokeRequestPart {
|
||||
client_id: tsclientlib::ClientId(client),
|
||||
@@ -1121,7 +1055,7 @@ impl Voice {
|
||||
));
|
||||
self.send(cmd, Pending::Report("poke"))?;
|
||||
}
|
||||
VoiceCmd::ListFiles { request, dir } => {
|
||||
LinkCmd::ListFiles { request, dir } => {
|
||||
let path = files::normalize_dir(&dir.path);
|
||||
let cpw = dir.cpw();
|
||||
let cmd = c2s::OutFileListRequestMessage::new(&mut std::iter::once(
|
||||
@@ -1135,7 +1069,7 @@ impl Voice {
|
||||
Pending::FileList { request, channel: dir.channel, path, entries: Vec::new() };
|
||||
self.send(cmd, pending)?;
|
||||
}
|
||||
VoiceCmd::Download { transfer, file, sink, report } => {
|
||||
LinkCmd::Download { transfer, file, sink, report } => {
|
||||
let offset = sink.offset();
|
||||
let seek = (offset > 0).then_some(offset);
|
||||
let password = file.password.as_deref().filter(|p| !p.is_empty());
|
||||
@@ -1156,7 +1090,7 @@ impl Voice {
|
||||
self.transfers.insert(id, Slot::Waiting(handle));
|
||||
}
|
||||
}
|
||||
VoiceCmd::Upload { transfer, file, from, overwrite, resume, report } => {
|
||||
LinkCmd::Upload { transfer, file, from, overwrite, resume, report } => {
|
||||
let size = match std::fs::metadata(&from) {
|
||||
Ok(m) if m.is_file() => m.len(),
|
||||
Ok(_) => {
|
||||
@@ -1186,7 +1120,7 @@ impl Voice {
|
||||
self.transfers.insert(id, Slot::Waiting(handle));
|
||||
}
|
||||
}
|
||||
VoiceCmd::CancelTransfer(id) => match self.transfers.remove(&id) {
|
||||
LinkCmd::CancelTransfer(id) => match self.transfers.remove(&id) {
|
||||
Some(Slot::Waiting(handle)) => {
|
||||
if let Some(job) = self.jobs.remove(&handle) {
|
||||
job.report()(TransferState::Cancelled);
|
||||
@@ -1201,7 +1135,7 @@ impl Voice {
|
||||
}
|
||||
_ => debug!(id, "cancel: no such transfer (finished?)"),
|
||||
},
|
||||
VoiceCmd::DeleteFiles { request, channel, password, paths } => {
|
||||
LinkCmd::DeleteFiles { request, channel, password, paths } => {
|
||||
let cpw = encode_password(password.as_deref());
|
||||
let mut parts = paths.iter().map(|p| c2s::OutDeleteFilePart {
|
||||
channel_id: tsclientlib::ChannelId(channel),
|
||||
@@ -1211,7 +1145,7 @@ impl Voice {
|
||||
let cmd = c2s::OutDeleteFileMessage::new(&mut parts);
|
||||
self.send(cmd, request.map_or(Pending::Quiet, Pending::Done))?;
|
||||
}
|
||||
VoiceCmd::RenameFile { request, from, to } => {
|
||||
LinkCmd::RenameFile { request, from, to } => {
|
||||
let (cpw, tcpw) = (from.cpw(), to.cpw());
|
||||
let other = to.channel != from.channel;
|
||||
let cmd =
|
||||
@@ -1225,7 +1159,7 @@ impl Voice {
|
||||
}));
|
||||
self.send(cmd, Pending::Done(request))?;
|
||||
}
|
||||
VoiceCmd::CreateDirectory { request, dir } => {
|
||||
LinkCmd::CreateDirectory { request, dir } => {
|
||||
let cpw = dir.cpw();
|
||||
let cmd = c2s::OutCreateDirectoryMessage::new(&mut std::iter::once(
|
||||
c2s::OutCreateDirectoryPart {
|
||||
@@ -1236,23 +1170,23 @@ impl Voice {
|
||||
));
|
||||
self.send(cmd, Pending::Done(request))?;
|
||||
}
|
||||
VoiceCmd::SetAvatarHash { request, hash } => {
|
||||
LinkCmd::SetAvatarHash { request, hash } => {
|
||||
let update = self.con.get_state()?.client_update().set_avatar_hash(&hash);
|
||||
let cmd = c2s::OutClientUpdateMessage::new(&mut std::iter::once(update));
|
||||
let pending = request.map_or(Pending::Report("avatar"), Pending::Done);
|
||||
self.send(cmd, pending)?;
|
||||
}
|
||||
VoiceCmd::OfflineList { request } => {
|
||||
LinkCmd::OfflineList { request } => {
|
||||
let cmd = c2s::OutOfflineMessageListRequestMessage::new();
|
||||
self.send(cmd, Pending::OfflineList { request, messages: Vec::new() })?;
|
||||
}
|
||||
VoiceCmd::OfflineGet { request, id } => {
|
||||
LinkCmd::OfflineGet { request, id } => {
|
||||
let cmd = c2s::OutOfflineMessageGetMessage::new(&mut std::iter::once(
|
||||
c2s::OutOfflineMessageGetPart { message_id: id },
|
||||
));
|
||||
self.send(cmd, Pending::OfflineGet { request, id, message: None })?;
|
||||
}
|
||||
VoiceCmd::OfflineAdd { request, to_uid, subject, text } => {
|
||||
LinkCmd::OfflineAdd { request, to_uid, subject, text } => {
|
||||
// The command carries the unique id's bytes (base64 on the wire).
|
||||
let bytes = base64::engine::general_purpose::STANDARD
|
||||
.decode(to_uid.trim())
|
||||
@@ -1273,19 +1207,19 @@ impl Voice {
|
||||
));
|
||||
self.send(cmd, Pending::Done(request))?;
|
||||
}
|
||||
VoiceCmd::OfflineDelete { request, id } => {
|
||||
LinkCmd::OfflineDelete { request, id } => {
|
||||
let cmd = c2s::OutOfflineMessageDelMessage::new(&mut std::iter::once(
|
||||
c2s::OutOfflineMessageDelPart { message_id: id },
|
||||
));
|
||||
self.send(cmd, Pending::Done(request))?;
|
||||
}
|
||||
VoiceCmd::OfflineFlag { request, id, read } => {
|
||||
LinkCmd::OfflineFlag { request, id, read } => {
|
||||
let cmd = c2s::OutOfflineMessageUpdateFlagMessage::new(&mut std::iter::once(
|
||||
c2s::OutOfflineMessageUpdateFlagPart { message_id: id, is_read: read },
|
||||
));
|
||||
self.send(cmd, Pending::Done(request))?;
|
||||
}
|
||||
VoiceCmd::Disconnect => {}
|
||||
LinkCmd::Disconnect => {}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -1357,6 +1291,173 @@ fn transfer_error(error: &tsclientlib::Error) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
/// Our voice frame as a TeamSpeak audio packet; the connection assigns its
|
||||
/// packet id. This and [`voice_packet`] are the only places that convert
|
||||
/// between the audio pipeline's packets and TeamSpeak's.
|
||||
fn out_audio(voice: &EncodedVoice) -> OutPacket {
|
||||
let codec = match voice.codec {
|
||||
VoiceCodec::Voice => CodecType::OpusVoice,
|
||||
VoiceCodec::Music => CodecType::OpusMusic,
|
||||
};
|
||||
OutAudio::new(&AudioData::C2S { id: 0, codec, data: &voice.payload })
|
||||
}
|
||||
|
||||
/// A received TeamSpeak audio packet for the audio thread. `None` for
|
||||
/// anything but Opus voice: the jitter buffer cannot play the other codecs
|
||||
/// (Speex, CELT), and only server-to-client packets are received.
|
||||
fn voice_packet(packet: &InAudioBuf) -> Option<VoicePacket> {
|
||||
let (seq, from, codec, data, whisper) = match packet.data().data() {
|
||||
AudioData::S2C { id, from, codec, data } => (*id, *from, *codec, *data, false),
|
||||
AudioData::S2CWhisper { id, from, codec, data } => (*id, *from, *codec, *data, true),
|
||||
_ => return None,
|
||||
};
|
||||
let codec = match codec {
|
||||
CodecType::OpusVoice => VoiceCodec::Voice,
|
||||
CodecType::OpusMusic => VoiceCodec::Music,
|
||||
other => {
|
||||
debug!(codec = ?other, "dropped voice packet: only Opus is supported");
|
||||
return None;
|
||||
}
|
||||
};
|
||||
Some(VoicePacket { talker: TalkerId(from), seq, codec, whisper, payload: data.to_vec() })
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod audio_packet_tests {
|
||||
use tsproto_packets::packets::Direction;
|
||||
|
||||
use super::*;
|
||||
|
||||
fn received(data: AudioData) -> InAudioBuf {
|
||||
InAudioBuf::try_new(Direction::S2C, OutAudio::new(&data).into_vec()).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn received_voice_reaches_the_audio_thread_as_a_voice_packet() {
|
||||
let packet = received(AudioData::S2C {
|
||||
id: 513,
|
||||
from: 7,
|
||||
codec: CodecType::OpusVoice,
|
||||
data: &[1, 2, 3],
|
||||
});
|
||||
assert_eq!(
|
||||
voice_packet(&packet),
|
||||
Some(VoicePacket {
|
||||
talker: TalkerId(7),
|
||||
seq: 513,
|
||||
codec: VoiceCodec::Voice,
|
||||
whisper: false,
|
||||
payload: vec![1, 2, 3],
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn whispers_and_music_are_marked() {
|
||||
let packet = received(AudioData::S2CWhisper {
|
||||
id: 65_535,
|
||||
from: 300,
|
||||
codec: CodecType::OpusMusic,
|
||||
data: &[9],
|
||||
});
|
||||
let voice = voice_packet(&packet).unwrap();
|
||||
assert_eq!((voice.talker, voice.seq), (TalkerId(300), 65_535));
|
||||
assert_eq!(voice.codec, VoiceCodec::Music);
|
||||
assert!(voice.whisper);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_end_of_a_talk_arrives_empty() {
|
||||
let packet =
|
||||
received(AudioData::S2C { id: 4, from: 7, codec: CodecType::OpusVoice, data: &[] });
|
||||
let voice = voice_packet(&packet).unwrap();
|
||||
assert!(voice.payload.is_empty() && voice.is_end());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn codecs_other_than_opus_are_dropped() {
|
||||
for codec in [CodecType::SpeexWideband, CodecType::CeltMono] {
|
||||
let packet = received(AudioData::S2C { id: 1, from: 7, codec, data: &[1, 2, 3] });
|
||||
assert_eq!(voice_packet(&packet), None);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sent_voice_is_a_client_audio_packet() {
|
||||
for (codec, wire) in
|
||||
[(VoiceCodec::Voice, CodecType::OpusVoice), (VoiceCodec::Music, CodecType::OpusMusic)]
|
||||
{
|
||||
let voice = EncodedVoice { codec, payload: vec![5, 6, 7] };
|
||||
let packet = InAudioBuf::try_new(Direction::C2S, out_audio(&voice).into_vec()).unwrap();
|
||||
match packet.data().data() {
|
||||
AudioData::C2S { id, codec, data } => {
|
||||
// The connection numbers the packets.
|
||||
assert_eq!((*id, *codec, *data), (0, wire, &[5u8, 6, 7][..]));
|
||||
}
|
||||
other => panic!("not a client audio packet: {other:?}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_end_of_our_transmission_is_an_empty_packet() {
|
||||
let end = EncodedVoice { codec: VoiceCodec::Voice, payload: Vec::new() };
|
||||
// Two bytes of packet id and one of codec, no audio.
|
||||
assert_eq!(out_audio(&end).content().len(), 3);
|
||||
let voice = EncodedVoice { codec: VoiceCodec::Voice, payload: vec![0] };
|
||||
assert_eq!(out_audio(&voice).content().len(), 4);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod backend_tests {
|
||||
use super::*;
|
||||
|
||||
/// What a connection tells the engine about the server it reached: the
|
||||
/// product and version the UI shows, and the capabilities the old flavor
|
||||
/// carried through the event.
|
||||
fn told(version: &str) -> (BackendInfo, Capabilities) {
|
||||
backend_of(&ServerFlavor::from_version_string(version))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_teamspeak_3_server_is_named_with_its_capabilities() {
|
||||
let (backend, capabilities) = told("3.13.8 [Build: 1779874471]");
|
||||
assert_eq!(
|
||||
backend,
|
||||
BackendInfo { product: "TeamSpeak 3".into(), version: "3.13.8".into() }
|
||||
);
|
||||
assert_eq!(backend.label(), "TeamSpeak 3 3.13.8");
|
||||
assert!(!capabilities.streams && capabilities.raw_query && capabilities.file_transfer);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_teamspeak_6_server_is_named_with_its_capabilities() {
|
||||
let (backend, capabilities) = told("6.0.0-beta13.1 [Build: 1790080330]");
|
||||
assert_eq!(
|
||||
backend,
|
||||
BackendInfo { product: "TeamSpeak 6".into(), version: "6.0.0-beta13.1".into() }
|
||||
);
|
||||
assert_eq!(backend.label(), "TeamSpeak 6 6.0.0-beta13.1");
|
||||
assert!(capabilities.streams && !capabilities.raw_query && capabilities.http_query);
|
||||
// The capabilities are the flavor's own.
|
||||
assert_eq!(
|
||||
capabilities,
|
||||
ServerFlavor::from_version_string("6.0.0-beta13.1 [Build: 1790080330]").capabilities()
|
||||
);
|
||||
}
|
||||
|
||||
/// A version nobody recognises names no product: the status line shows
|
||||
/// the string as the server sent it, and nothing is switched on.
|
||||
#[test]
|
||||
fn an_unrecognised_server_keeps_its_version_string_and_no_capabilities() {
|
||||
let (backend, capabilities) = told("custom 9");
|
||||
assert_eq!(backend, BackendInfo { product: String::new(), version: "custom 9".into() });
|
||||
assert_eq!(backend.label(), "custom 9");
|
||||
assert_eq!(capabilities, Capabilities::default());
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod join_tests {
|
||||
use super::*;
|
||||
@@ -1447,14 +1548,16 @@ mod image_download_tests {
|
||||
#[cfg(test)]
|
||||
mod account_tests {
|
||||
use super::*;
|
||||
use tokio::sync::broadcast;
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn account_priority_preserves_ready_network_and_timer_progress() {
|
||||
let (account, mut identity) = watch::channel(None);
|
||||
let (account_data, mut data) = watch::channel(None);
|
||||
let (commands, mut receiver) = mpsc::unbounded_channel();
|
||||
let (_requests, mut requests) = mpsc::unbounded_channel();
|
||||
for _ in 0..512 {
|
||||
commands.send(VoiceCmd::SetInputMuted(false)).unwrap();
|
||||
commands.send(LinkCmd::SetInputMuted(false)).unwrap();
|
||||
}
|
||||
let mut stream = futures::stream::poll_fn(|_| {
|
||||
std::task::Poll::Ready(Some(Err(tsclientlib::Error::NotConnected)))
|
||||
@@ -1462,21 +1565,45 @@ mod account_tests {
|
||||
let mut tick = tokio::time::interval(Duration::from_millis(1));
|
||||
account.send_replace(None);
|
||||
assert!(matches!(
|
||||
next_input(&mut stream, &mut receiver, &mut tick, &mut identity, &mut data).await,
|
||||
next_input(
|
||||
&mut stream,
|
||||
&mut receiver,
|
||||
&mut requests,
|
||||
&mut tick,
|
||||
&mut identity,
|
||||
&mut data
|
||||
)
|
||||
.await,
|
||||
Input::MytsIdentityChanged
|
||||
));
|
||||
identity.borrow_and_update();
|
||||
// What is shown of the account changes too, ahead of the rest.
|
||||
account_data.send_replace(Some(Arc::new(tsclientlib::MytsData::default())));
|
||||
assert!(matches!(
|
||||
next_input(&mut stream, &mut receiver, &mut tick, &mut identity, &mut data).await,
|
||||
next_input(
|
||||
&mut stream,
|
||||
&mut receiver,
|
||||
&mut requests,
|
||||
&mut tick,
|
||||
&mut identity,
|
||||
&mut data
|
||||
)
|
||||
.await,
|
||||
Input::MytsDataChanged
|
||||
));
|
||||
data.borrow_and_update();
|
||||
let (mut network, mut timers, mut audio) = (0, 0, 0);
|
||||
for _ in 0..512 {
|
||||
tokio::time::advance(Duration::from_millis(1)).await;
|
||||
match next_input(&mut stream, &mut receiver, &mut tick, &mut identity, &mut data).await
|
||||
match next_input(
|
||||
&mut stream,
|
||||
&mut receiver,
|
||||
&mut requests,
|
||||
&mut tick,
|
||||
&mut identity,
|
||||
&mut data,
|
||||
)
|
||||
.await
|
||||
{
|
||||
Input::Item(_) => network += 1,
|
||||
Input::Tick => timers += 1,
|
||||
@@ -1546,10 +1673,11 @@ mod account_tests {
|
||||
let identity =
|
||||
tsproto::myts::Identity::new(vec![1; 33], 42, public, private, vec![2; 65]).unwrap();
|
||||
let (events, _) = broadcast::channel(8);
|
||||
let link = VoiceLink {
|
||||
let link = LinkCtx {
|
||||
session: 1,
|
||||
events,
|
||||
settings: SharedSettings::new(crate::settings::Settings::default()),
|
||||
frames: broadcast::channel(1).0,
|
||||
settings: crate::settings::SharedSettings::new(crate::settings::Settings::default()),
|
||||
myts_identity: watch::channel(Some(Arc::new(identity))).1,
|
||||
myts_data: watch::channel(Some(Arc::new(data))).1,
|
||||
};
|
||||
@@ -1564,6 +1692,8 @@ mod account_tests {
|
||||
transfers: HashMap::new(),
|
||||
myts_data_due: false,
|
||||
myts_shown: tsclientlib::MytsData::default(),
|
||||
streams: None,
|
||||
streaming_clients: BTreeMap::new(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1631,17 +1761,18 @@ mod account_tests {
|
||||
let server = tokio::net::UdpSocket::bind("127.0.0.1:0").await.unwrap();
|
||||
let (account, identity) = watch::channel(None);
|
||||
let (events, _) = broadcast::channel(8);
|
||||
let link = VoiceLink {
|
||||
let link = LinkCtx {
|
||||
session: 1,
|
||||
events,
|
||||
settings: SharedSettings::new(crate::settings::Settings::default()),
|
||||
frames: broadcast::channel(1).0,
|
||||
settings: crate::settings::SharedSettings::new(crate::settings::Settings::default()),
|
||||
myts_identity: identity,
|
||||
myts_data: watch::channel(None).1,
|
||||
};
|
||||
let (_commands, commands) = mpsc::unbounded_channel();
|
||||
let (events, mut received) = mpsc::unbounded_channel();
|
||||
let task = tokio::spawn(run(
|
||||
VoiceOptions::new(server.local_addr().unwrap().to_string(), "account-test"),
|
||||
ConnectOptions::new(server.local_addr().unwrap().to_string(), "account-test"),
|
||||
link,
|
||||
commands,
|
||||
events,
|
||||
@@ -1666,7 +1797,7 @@ mod account_tests {
|
||||
drop(account);
|
||||
timeout(Duration::from_secs(2), task).await.unwrap().unwrap();
|
||||
assert!(
|
||||
matches!(received.recv().await, Some(VoiceEvent::Disconnected(Some(reason))) if reason == "account source closed")
|
||||
matches!(received.recv().await, Some(LinkEvent::Disconnected(Some(reason))) if reason == "account source closed")
|
||||
);
|
||||
assert!(received.try_recv().is_err());
|
||||
}
|
||||
|
||||
@@ -0,0 +1,570 @@
|
||||
//! 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. Presence, chat, the dedup of a message that comes twice, history
|
||||
//! and the end of a connection are the session's own behaviour; 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 voelin_core::history::MessageSource;
|
||||
use voelin_core::link::{ConnectOptions, LinkCmd, LinkCtx, LinkEvent, ServerLink};
|
||||
use voelin_core::settings::Settings;
|
||||
use voelin_core::stream::{StreamCmd, StreamSetup};
|
||||
use voelin_core::{
|
||||
BackendInfo, Command, Engine, Event, History, HistoryMessage, HistorySource, SessionId,
|
||||
SessionState, Source, VoiceOptions, VoiceState,
|
||||
};
|
||||
use voelin_model::{
|
||||
Capabilities, ChannelId, ChannelInfo, ChatMessage, ChatTarget, ClientInfo, Presence,
|
||||
};
|
||||
|
||||
/// A connection the session asked the link for.
|
||||
struct Conn {
|
||||
options: ConnectOptions,
|
||||
session: SessionId,
|
||||
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 conn = Conn { options, session: ctx.session(), cmds, events };
|
||||
let _ = self.conns.send(conn);
|
||||
}
|
||||
}
|
||||
|
||||
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 engine =
|
||||
Engine::start_with_link(Settings::in_memory(), History::in_memory(), Arc::new(link));
|
||||
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
|
||||
}
|
||||
|
||||
/// The messages stored for `target`, oldest first.
|
||||
async fn stored(&self, target: ChatTarget) -> Vec<HistoryMessage> {
|
||||
self.engine
|
||||
.history()
|
||||
.page(SERVER_UID, &target, Default::default(), false)
|
||||
.await
|
||||
.expect("the history")
|
||||
}
|
||||
}
|
||||
|
||||
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()),
|
||||
}
|
||||
}
|
||||
|
||||
fn client(id: u16, nickname: &str, channel: ChannelId) -> ClientInfo {
|
||||
ClientInfo {
|
||||
id,
|
||||
uid: Some(format!("{nickname}=")),
|
||||
nickname: nickname.into(),
|
||||
channel,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// Two channels, three clients; we are in the second channel.
|
||||
fn presence() -> Presence {
|
||||
let channel = |id, name: &str| ChannelInfo { id, name: name.into(), ..Default::default() };
|
||||
let mut presence = Presence { server_name: "Fake Server".into(), ..Default::default() };
|
||||
presence.channels.insert(LOBBY, channel(LOBBY, "Lobby"));
|
||||
presence.channels.insert(GAMES, channel(GAMES, "Games"));
|
||||
for c in [client(ME, "tester", GAMES), 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,
|
||||
}
|
||||
}
|
||||
|
||||
/// Connecting, the server's presence, moving, talking, a failing command
|
||||
/// and the end of the connection, as the session reports them.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn presence_follows_the_link_until_it_disconnects() {
|
||||
let mut h = Harness::start();
|
||||
let conn = h.connect().await;
|
||||
// What the link was given.
|
||||
assert_eq!(
|
||||
(conn.options.address.as_str(), conn.options.nickname.as_str()),
|
||||
("fake.test:9987", "tester")
|
||||
);
|
||||
assert_eq!(conn.session, SESSION);
|
||||
h.state(|s| s.voice == VoiceState::Connecting).await;
|
||||
|
||||
conn.play([
|
||||
connected(false),
|
||||
LinkEvent::Presence(Box::new(presence())),
|
||||
LinkEvent::OwnChannel(GAMES),
|
||||
]);
|
||||
// In the order the session tells them: the server, its presence, our channel.
|
||||
let (name, info, caps) = h
|
||||
.next(|e| match e {
|
||||
Event::ServerInfo { name, backend, capabilities, .. } => {
|
||||
Some((name, backend, capabilities))
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.await;
|
||||
assert_eq!((name.as_str(), info.label().as_str()), ("Fake Server", "Fake 1.2"));
|
||||
assert_eq!(caps, capabilities(false));
|
||||
let shown = h
|
||||
.next(|e| match e {
|
||||
Event::Presence { presence, .. } if !presence.clients.is_empty() => Some(presence),
|
||||
_ => None,
|
||||
})
|
||||
.await;
|
||||
assert_eq!(*shown, presence());
|
||||
let state = h.state(|s| s.own_channel == Some(GAMES)).await;
|
||||
assert_eq!(state.voice, VoiceState::Connected);
|
||||
assert_eq!(state.own_client, Some(ME));
|
||||
assert_eq!(state.server_uid.as_deref(), Some(SERVER_UID));
|
||||
assert_eq!(state.presence_source, Some(Source::Voice));
|
||||
|
||||
conn.play([
|
||||
LinkEvent::Talking { client: 8, talking: true },
|
||||
LinkEvent::Poke {
|
||||
from: 8,
|
||||
from_uid: Some("alice=".into()),
|
||||
from_name: "alice".into(),
|
||||
message: "wake up".into(),
|
||||
},
|
||||
LinkEvent::Error("move refused".into()),
|
||||
]);
|
||||
h.next(|e| matches!(e, Event::Talking { client: 8, talking: true, .. }).then_some(())).await;
|
||||
let poke = h
|
||||
.next(|e| match e {
|
||||
Event::Poke { from_name, message, blocked, .. } => Some((from_name, message, blocked)),
|
||||
_ => None,
|
||||
})
|
||||
.await;
|
||||
assert_eq!(poke, ("alice".into(), "wake up".into(), false));
|
||||
let error = h
|
||||
.next(|e| match e {
|
||||
Event::Error { message, .. } => Some(message),
|
||||
_ => None,
|
||||
})
|
||||
.await;
|
||||
assert_eq!(error, "move refused");
|
||||
|
||||
// The link ends the connection: the session forgets what it showed.
|
||||
conn.play([LinkEvent::Disconnected(Some("server shut down".into()))]);
|
||||
let state = h.state(|s| s.voice == VoiceState::Disconnected).await;
|
||||
assert_eq!((state.own_channel, state.own_client), (None, None));
|
||||
let error = h
|
||||
.next(|e| match e {
|
||||
Event::Error { message, .. } => Some(message),
|
||||
_ => None,
|
||||
})
|
||||
.await;
|
||||
assert_eq!(error, "voice: server shut down");
|
||||
let state = h.state(|s| s.presence_source.is_none()).await;
|
||||
assert_eq!(state.voice, VoiceState::Disconnected);
|
||||
let shown = h
|
||||
.next(|e| match e {
|
||||
Event::Presence { presence, .. } => Some(presence),
|
||||
_ => None,
|
||||
})
|
||||
.await;
|
||||
assert!(shown.clients.is_empty() && shown.channels.is_empty());
|
||||
}
|
||||
|
||||
/// What the user asks for reaches the link; streams only where the link's
|
||||
/// capabilities say it has them.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn commands_reach_the_link() {
|
||||
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;
|
||||
|
||||
let engine = h.engine.clone();
|
||||
engine.send(Command::SendChat {
|
||||
session: SESSION,
|
||||
target: ChatTarget::Channel(GAMES),
|
||||
text: "hello".into(),
|
||||
});
|
||||
let LinkCmd::SendChat(target, text) = conn.cmd().await else { panic!("a chat message") };
|
||||
assert_eq!((target, text.as_str()), (ChatTarget::Channel(GAMES), "hello"));
|
||||
engine.send(Command::MoveToChannel {
|
||||
session: SESSION,
|
||||
channel: LOBBY,
|
||||
password: Some("pw".into()),
|
||||
});
|
||||
let LinkCmd::Move(channel, password) = conn.cmd().await else { panic!("a move") };
|
||||
assert_eq!((channel, password.as_deref()), (LOBBY, Some("pw")));
|
||||
engine.send(Command::SetInputMuted { session: SESSION, muted: true });
|
||||
assert!(matches!(conn.cmd().await, LinkCmd::SetInputMuted(true)));
|
||||
assert!(h.state(|s| s.input_muted).await.input_muted);
|
||||
engine.send(Command::Poke { session: SESSION, client: 8, message: "hi".into() });
|
||||
assert!(matches!(conn.cmd().await, LinkCmd::Poke { client: 8, .. }));
|
||||
engine.send(Command::ListFiles {
|
||||
session: SESSION,
|
||||
request: 5,
|
||||
channel: GAMES,
|
||||
password: None,
|
||||
path: "/docs/".into(),
|
||||
});
|
||||
let LinkCmd::ListFiles { request, dir } = conn.cmd().await else { panic!("a file list") };
|
||||
assert_eq!((request, dir.channel, dir.path.as_str()), (5, GAMES, "/docs/"));
|
||||
|
||||
// No streams in the capabilities: the session refuses them itself.
|
||||
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));
|
||||
}
|
||||
|
||||
/// A message we send is stored at once; the server's copy of it merges
|
||||
/// into the same row, and is shown (once).
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_sent_message_and_its_echo_are_one_message() {
|
||||
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;
|
||||
|
||||
h.engine.send(Command::SendChat {
|
||||
session: SESSION,
|
||||
target: ChatTarget::Channel(GAMES),
|
||||
text: "hello".into(),
|
||||
});
|
||||
assert!(matches!(conn.cmd().await, LinkCmd::SendChat(..)));
|
||||
// The server sends it back to everyone in the channel, to us too.
|
||||
let mut echo = message("tester", "hello", now_ms());
|
||||
echo.author_uid = Some(ME_UID.into());
|
||||
echo.author_id = Some(ME);
|
||||
conn.play([LinkEvent::Chat(echo.clone())]);
|
||||
let shown = h.chat().await;
|
||||
assert_eq!((shown.author_name.as_str(), shown.text.as_str()), ("tester", "hello"));
|
||||
|
||||
// A marker: what comes next is the next message, not a second "hello".
|
||||
conn.play([LinkEvent::Chat(message("alice", "marker", now_ms()))]);
|
||||
assert_eq!(h.chat().await.text, "marker");
|
||||
let rows = h.stored(ChatTarget::Channel(GAMES)).await;
|
||||
let texts: Vec<_> = rows.iter().map(|m| m.message.text.as_str()).collect();
|
||||
assert_eq!(texts, ["hello", "marker"]);
|
||||
assert_eq!(rows[0].source, MessageSource::Local);
|
||||
}
|
||||
|
||||
/// A message that comes twice (the server's and a relay's copy, with the
|
||||
/// relay's `[nick] ` prefix) is shown once.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_message_that_comes_twice_is_shown_once() {
|
||||
let mut h = Harness::start();
|
||||
let conn = h.connect().await;
|
||||
h.engine.send(Command::OpenChat { session: SESSION, target: ChatTarget::Channel(GAMES) });
|
||||
conn.play([
|
||||
connected(false),
|
||||
LinkEvent::Presence(Box::new(presence())),
|
||||
LinkEvent::OwnChannel(GAMES),
|
||||
]);
|
||||
h.state(|s| s.own_channel == Some(GAMES)).await;
|
||||
|
||||
let t = now_ms();
|
||||
let mut relayed = message("alice", "[alice] gg everyone", t + 300);
|
||||
relayed.via_relay = true;
|
||||
conn.play([
|
||||
LinkEvent::Chat(message("alice", "gg everyone", t)),
|
||||
LinkEvent::Chat(relayed),
|
||||
// The same words much later are another message.
|
||||
LinkEvent::Chat(message("alice", "gg everyone", t + 10_000)),
|
||||
LinkEvent::Chat(message("bob", "gg everyone", t + 10_100)),
|
||||
]);
|
||||
let shown: Vec<_> = {
|
||||
let mut shown = Vec::new();
|
||||
while shown.len() < 3 {
|
||||
shown.push(h.chat().await);
|
||||
}
|
||||
shown
|
||||
};
|
||||
let who: Vec<_> = shown.iter().map(|m| (m.author_name.as_str(), m.ts_ms)).collect();
|
||||
assert_eq!(who, [("alice", t), ("alice", t + 10_000), ("bob", t + 10_100)]);
|
||||
}
|
||||
|
||||
/// Stored messages come back when a chat opens, also after the connection
|
||||
/// is gone; the server's id keys them.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn history_is_kept_across_the_connection() {
|
||||
let mut h = Harness::start();
|
||||
let 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;
|
||||
let t = now_ms();
|
||||
conn.play([
|
||||
LinkEvent::Chat(message("alice", "first", t)),
|
||||
LinkEvent::Chat(message("bob", "second", t + 1_000)),
|
||||
// A private message to us is stored under its peer, not the channel.
|
||||
LinkEvent::Chat(ChatMessage {
|
||||
target: ChatTarget::Private("alice=".into()),
|
||||
..message("alice", "psst", t + 2_000)
|
||||
}),
|
||||
]);
|
||||
for _ in 0..3 {
|
||||
h.chat().await;
|
||||
}
|
||||
conn.play([LinkEvent::Disconnected(None)]);
|
||||
h.state(|s| s.voice == VoiceState::Disconnected).await;
|
||||
|
||||
h.engine.send(Command::OpenChat { session: SESSION, target: ChatTarget::Channel(GAMES) });
|
||||
// The stored page (the live batches of the messages came before).
|
||||
let messages = h
|
||||
.next(|e| match e {
|
||||
Event::ChatHistory { messages, source: HistorySource::Local, .. } => Some(messages),
|
||||
_ => None,
|
||||
})
|
||||
.await;
|
||||
let texts: Vec<_> = messages.iter().map(|m| m.message.text.as_str()).collect();
|
||||
assert_eq!(texts, ["first", "second"]);
|
||||
let private = h.stored(ChatTarget::Private("alice=".into())).await;
|
||||
assert_eq!(private.len(), 1);
|
||||
assert_eq!(private[0].message.text, "psst");
|
||||
}
|
||||
|
||||
/// 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);
|
||||
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");
|
||||
new.play([LinkEvent::Chat(message("alice", "hello", now_ms()))]);
|
||||
assert_eq!(h.chat().await.text, "hello", "the old connection's chat never showed");
|
||||
}
|
||||
@@ -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(())
|
||||
}
|
||||
|
||||
@@ -1,4 +1,9 @@
|
||||
# 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
|
||||
@@ -6,9 +11,19 @@
|
||||
# the volume: -e TSGW_LOG_FILE=logs/tsgw.log). See docs/gateway-admin.md.
|
||||
FROM rust:1.94-bookworm AS build
|
||||
WORKDIR /src
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends cmake libasound2-dev && rm -rf /var/lib/apt/lists/*
|
||||
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
|
||||
|
||||
@@ -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"] }
|
||||
@@ -97,8 +97,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"] }
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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,
|
||||
}
|
||||
@@ -19,7 +19,9 @@ rusqlite = { version = "0.40.2", features = ["bundled"] }
|
||||
serde = { version = "1.0.229", features = ["derive"] }
|
||||
serde_json = "1.0.151"
|
||||
thiserror = "2.0.21"
|
||||
tracing = "0.1.44"
|
||||
tsclientlib = { path = "../proto/tsclientlib" }
|
||||
voelin-identity = { workspace = true }
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -0,0 +1,587 @@
|
||||
//! The `identities` table as a [`voelin_identity::KeyStore`].
|
||||
//!
|
||||
//! The table holds identities of more than one kind: the TeamSpeak identities
|
||||
//! the client has always had (`kind` `teamspeak`, `data` the JSON of a
|
||||
//! `tsproto::Identity`), a Voelin key (`voelin`), the record of the account the
|
||||
//! installation is signed in to (`account`) and whatever kind a later version
|
||||
//! adds, which passes through untouched. A row is addressed by its
|
||||
//! `(kind, uid)`, and `uid` stays `UNIQUE` across kinds: the uid forms of the
|
||||
//! kinds do not overlap (a TeamSpeak uid is base64, a Voelin uid 52 characters
|
||||
//! of `a-z2-7`, an account uid is written `account:<uid>`).
|
||||
//!
|
||||
//! Besides the blob a row carries the columns of the TeamSpeak-only world,
|
||||
//! which a [`KeyStore`] does not see and keeps when it replaces a row: `name`,
|
||||
//! `origin`, `is_default` and `created`. A blob of a new `(kind, uid)` becomes a
|
||||
//! row named after its uid, of origin `user` and not the default.
|
||||
//!
|
||||
//! The TeamSpeak security level is not stored: it is computed from the key and
|
||||
//! counter in `data`, as [`Store::identities`] always did, and the level of a
|
||||
//! blob a caller puts is ignored. A TeamSpeak row whose JSON cannot be read
|
||||
//! (it could only have been damaged outside this crate) lists and reads with
|
||||
//! level 0 instead of failing the whole list, and a [`KeyStore::put`] that only
|
||||
//! changes the binding of a row (the row of that `(kind, uid)` already holds
|
||||
//! that `data`, as [`KeyStore::get`] reads it) writes the four binding columns,
|
||||
//! does not look at `data` again and does not rewrite it. That is how
|
||||
//! [`KeyStore::sign_out`] unbinds a device-only secret: a row whose `data` was
|
||||
//! damaged outside this crate (JSON that is no identity, a BLOB, bytes that are
|
||||
//! no UTF-8) does not keep the sign-out from unbinding it, and its `data` is
|
||||
//! kept byte for byte.
|
||||
//!
|
||||
//! A row that is damaged elsewhere never fails a call that is not about it. A
|
||||
//! row whose binding columns cannot be read (`synced = 2`, an `account` that is
|
||||
//! no uid, a revision that is no integer; only something outside this crate
|
||||
//! writes them) is listed and read as unbound, and a warning names the row and
|
||||
//! the reason. [`KeyStore::list`] fails only when the database does, because
|
||||
//! the trait's [`KeyStore::sign_out`] starts with it and then reads the account
|
||||
//! record and the device key with [`KeyStore::get`]: one damaged row, the
|
||||
//! record's own included, would otherwise keep a sign-out from ever finishing,
|
||||
//! and with it the deletion of the key the user asked to forget. Unbound is the
|
||||
//! reading that never deletes on a guess: a sign-out neither deletes such a row
|
||||
//! as a synced copy nor writes it, it stays as it is until a `put` of it writes
|
||||
//! four good binding columns. A `data` column that is not text (a BLOB, or text
|
||||
//! of bytes that are no UTF-8) is read as text with the odd bytes replaced, so
|
||||
//! that a record that cannot be read is deleted by the sign-out, as the trait
|
||||
//! says, instead of its read failing. A [`KeyStore::put`] of the text that
|
||||
//! [`KeyStore::get`] returned for such a row is taken for the data that is
|
||||
//! there: it changes the binding and keeps the stored bytes, where any other
|
||||
//! text replaces them (a TeamSpeak blob still has to be an identity). A row
|
||||
//! whose `kind` or `uid` is not text cannot be addressed, and the list leaves it
|
||||
//! out with a warning.
|
||||
//!
|
||||
//! The rows are private keys, so a removed row is not left behind in the file:
|
||||
//! every connection sets `secure_delete`, which makes SQLite overwrite what it
|
||||
//! deletes, and [`KeyStore::remove`] truncates the write-ahead log after it, as
|
||||
//! [`Store::delete_identity`] does, so that the frame of the log that held the
|
||||
//! page with the key is gone too. [`KeyStore::sign_out`], which deletes with
|
||||
//! `remove`, truncates the log once, after its last step, not after each
|
||||
//! removal. The checkpoint waits for another connection for a moment at most
|
||||
//! (`Store::truncate_wal`): one that keeps reading an old snapshot blocks it,
|
||||
//! and then the removal still succeeds and a warning says that the deleted
|
||||
//! bytes may stay in the log file, until a later checkpoint truncates the log,
|
||||
//! later writes overwrite those frames, or the last connection to the database
|
||||
//! closes and the log is deleted.
|
||||
//!
|
||||
//! The device key is never a synced copy. The account record names the Voelin key
|
||||
//! that is the installation's device key, and [`KeyStore::sign_out`] deletes
|
||||
//! every identity bound with `synced = true` in its first step, before it reads
|
||||
//! the record, so a key stored that way would be deleted whatever the record
|
||||
//! says (a key that predates the account is to be kept). The store therefore
|
||||
//! refuses, with an error that says why, a [`KeyStore::put`] of a `voelin` blob
|
||||
//! with `synced = true` while an account record names its uid as the device, or
|
||||
//! while a record cannot be read, because then it cannot tell; and a put of an
|
||||
//! account record that names a key which is stored as a synced copy. A binding
|
||||
//! with `synced = false` is accepted: a sign-out unbinds such a key and then
|
||||
//! follows the record. The check and the write are done under the store's lock;
|
||||
//! a second process writing the same file at the same moment is not covered.
|
||||
//!
|
||||
//! A TeamSpeak blob that is refused says why in words that carry none of its
|
||||
//! input: its `data` is the identity's private key, and an error reaches log
|
||||
//! lines.
|
||||
|
||||
use std::path::Path;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::{Mutex, MutexGuard, PoisonError};
|
||||
|
||||
use rusqlite::types::ValueRef;
|
||||
use rusqlite::{OptionalExtension, params};
|
||||
use tsclientlib::Identity;
|
||||
use voelin_identity::migrate::SELECT_ACCOUNT_COLUMNS;
|
||||
use voelin_identity::{
|
||||
AccountBinding, BindingColumns, BlobError, DeviceKeyChoice, IdentityBlob, IdentityInfo,
|
||||
KIND_ACCOUNT, KIND_TEAMSPEAK, KIND_VOELIN, KeyStore, KeyStoreError, SignOut, Uid,
|
||||
};
|
||||
|
||||
use crate::{Error, Result, Store};
|
||||
|
||||
/// A result of the key store seam.
|
||||
type KsResult<T> = std::result::Result<T, KeyStoreError>;
|
||||
|
||||
/// The rows of [`KeyStore::list`]. The secret of a kind this crate does not
|
||||
/// interpret is never read; a TeamSpeak row's `data` is, for its level.
|
||||
const LIST: &str = "SELECT kind, uid, CASE WHEN kind = 'teamspeak' THEN data END,
|
||||
account, integration, integration_rev, synced, id
|
||||
FROM identities ORDER BY kind, uid";
|
||||
|
||||
/// Replace the binding of the row of this `(kind, uid)` if its `data` is
|
||||
/// exactly the blob's: nothing else of the row is written.
|
||||
const REBIND: &str = "UPDATE identities
|
||||
SET account = ?4, integration = ?5, integration_rev = ?6, synced = ?7
|
||||
WHERE kind = ?1 AND uid = ?2 AND data = ?3";
|
||||
|
||||
/// [`REBIND`] for a row whose `data` is not text and reads, as [`lossy_text`]
|
||||
/// reads it, as the blob's: the same four columns, and the stored bytes stay.
|
||||
const REBIND_BYTES: &str = "UPDATE identities
|
||||
SET account = ?3, integration = ?4, integration_rev = ?5, synced = ?6
|
||||
WHERE kind = ?1 AND uid = ?2";
|
||||
|
||||
/// Insert the blob, or replace the row of the same uid if it is of the same
|
||||
/// kind. A row of another kind is left alone: the statement then changes
|
||||
/// nothing, which `put` reports.
|
||||
const PUT: &str = "INSERT INTO identities
|
||||
(name, uid, data, kind, account, integration, integration_rev, synced)
|
||||
VALUES (?1, ?1, ?2, ?3, ?4, ?5, ?6, ?7)
|
||||
ON CONFLICT (uid) DO UPDATE SET
|
||||
data = excluded.data, account = excluded.account,
|
||||
integration = excluded.integration, integration_rev = excluded.integration_rev,
|
||||
synced = excluded.synced
|
||||
WHERE identities.kind = excluded.kind";
|
||||
|
||||
/// The identities of a client database as a [`KeyStore`]: every kind, with its
|
||||
/// account binding.
|
||||
///
|
||||
/// It owns a [`Store`] behind a mutex, because a [`KeyStore`] is `Sync` and a
|
||||
/// SQLite connection is not. Open it on the database file next to the
|
||||
/// other connections of the app (the settings writer and the chat history do
|
||||
/// the same): SQLite lets them share the file. [`Self::with_store`] gives
|
||||
/// access to the TeamSpeak methods of the same connection.
|
||||
///
|
||||
/// [`KeyStore::sign_out`] and the rest of the trait's provided methods work as
|
||||
/// `voelin-identity` defines them, on top of the five methods here; the
|
||||
/// sign-out only truncates the write-ahead log once, at its end.
|
||||
pub struct SqliteKeyStore {
|
||||
store: Mutex<Store>,
|
||||
}
|
||||
|
||||
impl SqliteKeyStore {
|
||||
/// The identities of an open [`Store`].
|
||||
pub fn new(store: Store) -> Self {
|
||||
Self { store: Mutex::new(store) }
|
||||
}
|
||||
|
||||
/// Open or create the database at `path`, migrating it.
|
||||
pub fn open(path: &Path) -> Result<Self> {
|
||||
Ok(Self::new(Store::open(path)?))
|
||||
}
|
||||
|
||||
/// A key store in memory: for tests.
|
||||
pub fn open_in_memory() -> Result<Self> {
|
||||
Ok(Self::new(Store::open_in_memory()?))
|
||||
}
|
||||
|
||||
/// Run `f` on the [`Store`] behind this key store, holding its lock: the
|
||||
/// TeamSpeak identity methods (`identities`, `default_identity`, ...) see
|
||||
/// the same rows on the same connection.
|
||||
pub fn with_store<R>(&self, f: impl FnOnce(&Store) -> R) -> R {
|
||||
f(&self.lock())
|
||||
}
|
||||
|
||||
fn lock(&self) -> MutexGuard<'_, Store> {
|
||||
// A panic in another thread cannot leave the table half-updated: every
|
||||
// write here is one statement, and `put` tries a second one only when
|
||||
// the first changed nothing.
|
||||
self.store.lock().unwrap_or_else(PoisonError::into_inner)
|
||||
}
|
||||
}
|
||||
|
||||
impl KeyStore for SqliteKeyStore {
|
||||
fn list(&self) -> KsResult<Vec<IdentityInfo>> {
|
||||
let store = self.lock();
|
||||
let mut statement = store.db.prepare_cached(LIST).map_err(backend)?;
|
||||
let rows = statement.query_map([], Columns::read).map_err(backend)?;
|
||||
let mut infos = Vec::new();
|
||||
for row in rows {
|
||||
infos.extend(row.map_err(backend)?.map(Columns::into_info));
|
||||
}
|
||||
Ok(infos)
|
||||
}
|
||||
|
||||
fn get(&self, kind: &str, uid: &str) -> KsResult<Option<IdentityBlob>> {
|
||||
let store = self.lock();
|
||||
let sql = format!(
|
||||
"SELECT {SELECT_ACCOUNT_COLUMNS}, id FROM identities WHERE kind = ?1 AND uid = ?2"
|
||||
);
|
||||
let mut statement = store.db.prepare_cached(&sql).map_err(backend)?;
|
||||
let mut rows = statement.query_map(params![kind, uid], Columns::read).map_err(backend)?;
|
||||
Ok(rows.next().transpose().map_err(backend)?.flatten().map(Columns::into_blob))
|
||||
}
|
||||
|
||||
fn put(&self, blob: &IdentityBlob) -> KsResult<()> {
|
||||
let columns = blob.binding_columns()?;
|
||||
let store = self.lock();
|
||||
match blob.kind.as_str() {
|
||||
KIND_VOELIN if blob.binding.is_some_and(|binding| binding.synced) => {
|
||||
refuse_synced_device_key(&store, &blob.uid)?;
|
||||
}
|
||||
KIND_ACCOUNT => refuse_record_of_synced_key(&store, blob)?,
|
||||
_ => {}
|
||||
}
|
||||
// A row that already holds this data changes its binding and nothing
|
||||
// else, and is not checked again: it may have been damaged outside this
|
||||
// crate, and a sign-out still has to unbind it. "Holds this data" is
|
||||
// meant as `get` reads it: for a `data` that is not text, `get` hands out
|
||||
// the text with the odd bytes replaced, `REBIND` cannot match that, and
|
||||
// the second statement takes the blob for the data that is there.
|
||||
let rebound = store
|
||||
.db
|
||||
.prepare_cached(REBIND)
|
||||
.map_err(backend)?
|
||||
.execute(params![
|
||||
blob.kind,
|
||||
blob.uid,
|
||||
blob.json,
|
||||
columns.account,
|
||||
columns.integration,
|
||||
columns.rev,
|
||||
columns.synced,
|
||||
])
|
||||
.map_err(backend)?;
|
||||
if rebound > 0 || rebind_stored_bytes(&store, blob, &columns)? {
|
||||
return Ok(());
|
||||
}
|
||||
if blob.kind == KIND_TEAMSPEAK {
|
||||
check_teamspeak(blob)?;
|
||||
}
|
||||
let changed = store
|
||||
.db
|
||||
.prepare_cached(PUT)
|
||||
.map_err(backend)?
|
||||
.execute(params![
|
||||
blob.uid,
|
||||
blob.json,
|
||||
blob.kind,
|
||||
columns.account,
|
||||
columns.integration,
|
||||
columns.rev,
|
||||
columns.synced,
|
||||
])
|
||||
.map_err(backend)?;
|
||||
if changed == 0 {
|
||||
let held_by: String = store
|
||||
.db
|
||||
.query_row("SELECT kind FROM identities WHERE uid = ?1", [&blob.uid], |r| r.get(0))
|
||||
.map_err(backend)?;
|
||||
return Err(KeyStoreError::backend(Refused::UidHeld {
|
||||
uid: blob.uid.clone(),
|
||||
kind: held_by,
|
||||
}));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn remove(&self, kind: &str, uid: &str) -> KsResult<bool> {
|
||||
let store = self.lock();
|
||||
let removed = delete_row(&store, kind, uid)?;
|
||||
if removed {
|
||||
// The row may be a key: leave nothing of it in the log either.
|
||||
store.truncate_wal();
|
||||
}
|
||||
Ok(removed)
|
||||
}
|
||||
|
||||
/// The trait's sign-out, with the log truncated once after its last step
|
||||
/// instead of after each of its removals: it removes up to a handful of
|
||||
/// rows, and a checkpoint that another connection blocks costs a moment
|
||||
/// (`Store::truncate_wal`) each time. The steps are the trait's own; they
|
||||
/// run on a `SignOutPass`, which deletes like [`Self::remove`] and leaves
|
||||
/// the checkpoint to this method.
|
||||
fn sign_out(&self, account: &Uid, device_key: DeviceKeyChoice) -> KsResult<SignOut> {
|
||||
let pass = SignOutPass { store: self, deleted: AtomicBool::new(false) };
|
||||
let outcome = KeyStore::sign_out(&pass, account, device_key);
|
||||
// Also after a failure: the removals before it have happened.
|
||||
if pass.deleted.load(Ordering::Relaxed) {
|
||||
self.lock().truncate_wal();
|
||||
}
|
||||
outcome
|
||||
}
|
||||
}
|
||||
|
||||
/// Delete the row of this `(kind, uid)`: whether there was one. The rows are
|
||||
/// overwritten (`secure_delete`); the log is the caller's to truncate.
|
||||
fn delete_row(store: &Store, kind: &str, uid: &str) -> KsResult<bool> {
|
||||
let removed = store
|
||||
.db
|
||||
.prepare_cached("DELETE FROM identities WHERE kind = ?1 AND uid = ?2")
|
||||
.map_err(backend)?
|
||||
.execute(params![kind, uid])
|
||||
.map_err(backend)?;
|
||||
Ok(removed > 0)
|
||||
}
|
||||
|
||||
/// A [`SqliteKeyStore`] for the length of one [`KeyStore::sign_out`]: the same
|
||||
/// rows, but `remove` only notes that it deleted something, so that the sign-out
|
||||
/// truncates the log once at its end.
|
||||
struct SignOutPass<'a> {
|
||||
store: &'a SqliteKeyStore,
|
||||
/// Whether a row was deleted.
|
||||
deleted: AtomicBool,
|
||||
}
|
||||
|
||||
impl KeyStore for SignOutPass<'_> {
|
||||
fn list(&self) -> KsResult<Vec<IdentityInfo>> {
|
||||
self.store.list()
|
||||
}
|
||||
|
||||
fn get(&self, kind: &str, uid: &str) -> KsResult<Option<IdentityBlob>> {
|
||||
self.store.get(kind, uid)
|
||||
}
|
||||
|
||||
fn put(&self, blob: &IdentityBlob) -> KsResult<()> {
|
||||
self.store.put(blob)
|
||||
}
|
||||
|
||||
fn remove(&self, kind: &str, uid: &str) -> KsResult<bool> {
|
||||
let removed = delete_row(&self.store.lock(), kind, uid)?;
|
||||
if removed {
|
||||
self.deleted.store(true, Ordering::Relaxed);
|
||||
}
|
||||
Ok(removed)
|
||||
}
|
||||
}
|
||||
|
||||
/// Change only the binding of the row of the blob's `(kind, uid)` if its `data`
|
||||
/// is not text but reads as exactly the blob's JSON, and say whether it did.
|
||||
///
|
||||
/// [`KeyStore::get`] reads a `data` that is a BLOB, or TEXT of bytes that are no
|
||||
/// UTF-8, as text with the odd bytes replaced ([`lossy_text`]). The blob that a
|
||||
/// sign-out puts back to unbind such a row carries that text, so `REBIND` finds
|
||||
/// nothing, and writing the blob would replace the stored bytes with the
|
||||
/// replaced text (and refuse a TeamSpeak row, whose replaced text is no
|
||||
/// identity, for ever). The text `get` handed out is taken for the data that is
|
||||
/// there, and the bytes are kept.
|
||||
///
|
||||
/// It is called after `REBIND` changed nothing, which is why the stored value is
|
||||
/// known not to be exactly the blob's text. Any other JSON does not match, and
|
||||
/// is a new identity for the uid as ever.
|
||||
fn rebind_stored_bytes(
|
||||
store: &Store,
|
||||
blob: &IdentityBlob,
|
||||
columns: &BindingColumns,
|
||||
) -> KsResult<bool> {
|
||||
let reads_as_blob = store
|
||||
.db
|
||||
.prepare_cached("SELECT data FROM identities WHERE kind = ?1 AND uid = ?2")
|
||||
.map_err(backend)?
|
||||
.query_row(params![blob.kind, blob.uid], |row| {
|
||||
Ok(lossy_text(row.get_ref(0)?).is_some_and(|text| text == blob.json))
|
||||
})
|
||||
.optional()
|
||||
.map_err(backend)?;
|
||||
if reads_as_blob != Some(true) {
|
||||
return Ok(false);
|
||||
}
|
||||
store
|
||||
.db
|
||||
.prepare_cached(REBIND_BYTES)
|
||||
.map_err(backend)?
|
||||
.execute(params![
|
||||
blob.kind,
|
||||
blob.uid,
|
||||
columns.account,
|
||||
columns.integration,
|
||||
columns.rev,
|
||||
columns.synced,
|
||||
])
|
||||
.map_err(backend)?;
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// A TeamSpeak blob is stored only if it is what its kind says: the JSON of a
|
||||
/// `tsproto::Identity` whose key has the uid the blob names.
|
||||
///
|
||||
/// The first keeps one bad row, which a service or a damaged file could hand
|
||||
/// over, from failing the list of TeamSpeak identities for everyone. The
|
||||
/// second keeps a blob from overwriting, by its uid, the key of a different
|
||||
/// identity that is stored under that uid.
|
||||
///
|
||||
/// The parse error of serde is dropped, not forwarded: it can quote the text
|
||||
/// it choked on, which is a private key, into a log line.
|
||||
fn check_teamspeak(blob: &IdentityBlob) -> KsResult<()> {
|
||||
let Ok(identity) = serde_json::from_str::<Identity>(&blob.json) else {
|
||||
return Err(KeyStoreError::backend(Refused::NotATeamSpeakIdentity));
|
||||
};
|
||||
if identity.key().to_pub().get_uid() != blob.uid {
|
||||
return Err(KeyStoreError::Blob(BlobError::UidMismatch));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Refuse to store the Voelin key `uid` as a synced copy while the device key
|
||||
/// of the installation, as an account record names it, is this key.
|
||||
///
|
||||
/// A record that cannot be read could name it: it is refused then too, because
|
||||
/// the sign-out that follows would delete the key on that guess.
|
||||
fn refuse_synced_device_key(store: &Store, uid: &str) -> KsResult<()> {
|
||||
let mut statement = store
|
||||
.db
|
||||
.prepare_cached("SELECT uid, data FROM identities WHERE kind = 'account'")
|
||||
.map_err(backend)?;
|
||||
let mut rows = statement.query([]).map_err(backend)?;
|
||||
while let Some(row) = rows.next().map_err(backend)? {
|
||||
// A record whose uid is not text cannot be addressed; it is not read.
|
||||
let Ok(record_uid) = row.get_ref(0).map_err(backend)?.as_str() else { continue };
|
||||
let data = lossy_text(row.get_ref(1).map_err(backend)?).unwrap_or_default();
|
||||
match IdentityBlob::new(KIND_ACCOUNT, record_uid, 0, data).account_record() {
|
||||
Ok(record) if record.device.to_base32() == uid => {
|
||||
return Err(KeyStoreError::backend(Refused::SyncedDeviceKey {
|
||||
uid: uid.to_owned(),
|
||||
record: record_uid.to_owned(),
|
||||
}));
|
||||
}
|
||||
Ok(_) => {}
|
||||
Err(_) => {
|
||||
return Err(KeyStoreError::backend(Refused::UnreadableRecord {
|
||||
uid: uid.to_owned(),
|
||||
record: record_uid.to_owned(),
|
||||
}));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Refuse to store an account record whose device key is stored as a synced
|
||||
/// copy: the same state as [`refuse_synced_device_key`] guards, reached from
|
||||
/// the other side. A blob that is no readable record is not checked here; the
|
||||
/// store has always kept what it is given for that kind, and a sign-out
|
||||
/// deletes it.
|
||||
fn refuse_record_of_synced_key(store: &Store, blob: &IdentityBlob) -> KsResult<()> {
|
||||
let Ok(record) = blob.account_record() else { return Ok(()) };
|
||||
let device = record.device.to_base32();
|
||||
let synced: bool = store
|
||||
.db
|
||||
.prepare_cached(
|
||||
"SELECT EXISTS (SELECT 1 FROM identities
|
||||
WHERE kind = 'voelin' AND uid = ?1 AND synced = 1)",
|
||||
)
|
||||
.map_err(backend)?
|
||||
.query_row([&device], |row| row.get(0))
|
||||
.map_err(backend)?;
|
||||
if synced {
|
||||
return Err(KeyStoreError::backend(Refused::RecordNamesSyncedKey {
|
||||
record: blob.uid.clone(),
|
||||
device,
|
||||
}));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A database error as the store's backend error.
|
||||
fn backend(error: impl Into<Error>) -> KeyStoreError {
|
||||
KeyStoreError::backend(error.into())
|
||||
}
|
||||
|
||||
/// A [`KeyStore::put`] this store refuses.
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
enum Refused {
|
||||
/// The JSON is not that of a `tsproto::Identity`. The text is a private
|
||||
/// key, so the error does not repeat it, nor serde's account of it.
|
||||
#[error("the TeamSpeak identity JSON is not that of an identity")]
|
||||
NotATeamSpeakIdentity,
|
||||
/// `uid` is unique across kinds in this table.
|
||||
#[error("the uid {uid:?} is already stored as an identity of kind {kind:?}")]
|
||||
UidHeld { uid: String, kind: String },
|
||||
/// The Voelin key is the device key of an account record. A sign-out
|
||||
/// deletes a synced copy without reading the record, so the key the record
|
||||
/// says to keep would be deleted.
|
||||
#[error(
|
||||
"the Voelin key {uid:?} is the device key of the account record {record:?} and cannot be \
|
||||
stored as a synced copy (synced = true): a sign-out would delete it whatever the record says"
|
||||
)]
|
||||
SyncedDeviceKey { uid: String, record: String },
|
||||
/// An account record cannot be read, so the store cannot tell whether the
|
||||
/// Voelin key is its device key.
|
||||
#[error(
|
||||
"the Voelin key {uid:?} cannot be stored as a synced copy (synced = true): the account \
|
||||
record {record:?} cannot be read, so it may name this key as the device key"
|
||||
)]
|
||||
UnreadableRecord { uid: String, record: String },
|
||||
/// The device key of the record is stored as a synced copy already.
|
||||
#[error(
|
||||
"the account record {record:?} names the Voelin key {device:?} as the device key, which is \
|
||||
stored as a synced copy (synced = true): a sign-out would delete it whatever the record \
|
||||
says"
|
||||
)]
|
||||
RecordNamesSyncedKey { record: String, device: String },
|
||||
}
|
||||
|
||||
/// One row of the table as `LIST` and `SELECT_ACCOUNT_COLUMNS` select it (with
|
||||
/// the row id last), its binding already read.
|
||||
struct Columns {
|
||||
kind: String,
|
||||
uid: String,
|
||||
/// The identity itself. `LIST` leaves it out for kinds with no level.
|
||||
data: Option<String>,
|
||||
/// `None` for an unbound row and for one whose binding columns are damaged.
|
||||
binding: Option<AccountBinding>,
|
||||
}
|
||||
|
||||
/// Why binding columns cannot be read.
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
enum Damage {
|
||||
#[error(transparent)]
|
||||
Binding(#[from] BlobError),
|
||||
#[error("a binding column holds a value of the wrong type")]
|
||||
WrongType,
|
||||
}
|
||||
|
||||
impl Columns {
|
||||
/// The row, or `None` for a row that cannot be addressed (its `kind` or
|
||||
/// `uid` is not text) and is left out with a warning.
|
||||
fn read(row: &rusqlite::Row<'_>) -> rusqlite::Result<Option<Self>> {
|
||||
let id: i64 = row.get(7)?;
|
||||
let (Ok(kind), Ok(uid)) = (row.get_ref(0)?.as_str(), row.get_ref(1)?.as_str()) else {
|
||||
tracing::warn!(id, "an identities row whose kind or uid is not text is left out");
|
||||
return Ok(None);
|
||||
};
|
||||
let binding = read_binding(row).unwrap_or_else(|damage| {
|
||||
tracing::warn!(
|
||||
id, kind, uid, %damage,
|
||||
"the binding columns of an identity cannot be read: it is treated as unbound",
|
||||
);
|
||||
None
|
||||
});
|
||||
Ok(Some(Self {
|
||||
kind: kind.to_owned(),
|
||||
uid: uid.to_owned(),
|
||||
data: lossy_text(row.get_ref(2)?),
|
||||
binding,
|
||||
}))
|
||||
}
|
||||
|
||||
/// The security level of a TeamSpeak row, 0 for any other kind and for JSON
|
||||
/// that is no identity.
|
||||
fn level(&self) -> u8 {
|
||||
match &self.data {
|
||||
Some(json) if self.kind == KIND_TEAMSPEAK => {
|
||||
serde_json::from_str::<Identity>(json).map_or(0, |identity| identity.level())
|
||||
}
|
||||
_ => 0,
|
||||
}
|
||||
}
|
||||
|
||||
fn into_info(self) -> IdentityInfo {
|
||||
let level = self.level();
|
||||
IdentityInfo { kind: self.kind, uid: self.uid, level, binding: self.binding }
|
||||
}
|
||||
|
||||
fn into_blob(self) -> IdentityBlob {
|
||||
let level = self.level();
|
||||
let data = self.data.unwrap_or_default();
|
||||
IdentityBlob::from_row(&self.kind, self.uid, level, data).with_binding(self.binding)
|
||||
}
|
||||
}
|
||||
|
||||
/// The binding of a row from its four columns (3 to 6 of both selects).
|
||||
fn read_binding(row: &rusqlite::Row<'_>) -> std::result::Result<Option<AccountBinding>, Damage> {
|
||||
let column = |index| row.get_ref(index).map_err(|_| Damage::WrongType);
|
||||
let account = column(3)?.as_str_or_null().map_err(|_| Damage::WrongType)?;
|
||||
let integration = column(4)?.as_str_or_null().map_err(|_| Damage::WrongType)?;
|
||||
let rev = column(5)?.as_i64().map_err(|_| Damage::WrongType)?;
|
||||
let synced = column(6)?.as_i64().map_err(|_| Damage::WrongType)?;
|
||||
Ok(AccountBinding::from_columns(account, integration, rev, synced)?)
|
||||
}
|
||||
|
||||
/// A `data` column as text, whatever it holds. Bytes that are no UTF-8 and
|
||||
/// values of another type are damage; read as text they fail where the
|
||||
/// blob's kind is checked, with that kind's own error, instead of failing the
|
||||
/// read of the row.
|
||||
fn lossy_text(value: ValueRef<'_>) -> Option<String> {
|
||||
match value {
|
||||
ValueRef::Null => None,
|
||||
ValueRef::Integer(n) => Some(n.to_string()),
|
||||
ValueRef::Real(x) => Some(x.to_string()),
|
||||
ValueRef::Text(bytes) | ValueRef::Blob(bytes) => {
|
||||
Some(String::from_utf8_lossy(bytes).into_owned())
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -7,9 +7,16 @@
|
||||
//!
|
||||
//! The schema is versioned (`PRAGMA user_version`): opening a database runs
|
||||
//! the migrations it has not seen, each in one transaction, keeping the data.
|
||||
//!
|
||||
//! The `identities` table keeps identities of more than one kind. [`Store`]
|
||||
//! has the TeamSpeak identities the client has always had; [`SqliteKeyStore`]
|
||||
//! is the table as a `voelin_identity::KeyStore`: every kind (TeamSpeak, a
|
||||
//! Voelin key, the record of the signed-in account), each with the binding that
|
||||
//! says whether it belongs to an account, and the sign-out of that account.
|
||||
|
||||
pub mod chat;
|
||||
pub mod contacts;
|
||||
mod keystore;
|
||||
mod secrets;
|
||||
mod store;
|
||||
|
||||
@@ -18,6 +25,7 @@ pub use chat::{
|
||||
StoredMessage, SyncState, WriteOutcome, Written,
|
||||
};
|
||||
pub use contacts::{Contact, ContactSeen, Relation};
|
||||
pub use keystore::SqliteKeyStore;
|
||||
#[cfg(feature = "keyring")]
|
||||
pub use secrets::KeyringSecrets;
|
||||
pub use secrets::{MemorySecrets, Secrets};
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
//! The SQLite database.
|
||||
|
||||
use std::path::Path;
|
||||
use std::time::Duration;
|
||||
|
||||
use rusqlite::{Connection, OptionalExtension, TransactionBehavior, params};
|
||||
use serde::de::DeserializeOwned;
|
||||
@@ -18,12 +19,21 @@ enum Migration {
|
||||
/// Schema migrations; entry `i` upgrades from version `i` to `i + 1`
|
||||
/// (`PRAGMA user_version`). Add new ones at the end; never change one that
|
||||
/// shipped.
|
||||
///
|
||||
/// Versions 6 and 7 are the identity migrations of `voelin-identity` (the
|
||||
/// protocol's Phase 2 tasks 7 and 28), run in this order: a `kind` column
|
||||
/// (every row that exists is a `teamspeak` identity) and then the four
|
||||
/// account-binding columns (every row that exists is unbound). Their SQL is
|
||||
/// the protocol's; `the_identity_migrations_are_pinned` keeps it from changing
|
||||
/// under a shipped version.
|
||||
const MIGRATIONS: &[Migration] = &[
|
||||
Migration::Sql(SCHEMA_1),
|
||||
Migration::Code(crate::chat::migrate_2),
|
||||
Migration::Sql(crate::contacts::SCHEMA_3),
|
||||
Migration::Sql(SCHEMA_4),
|
||||
Migration::Sql(crate::chat::SCHEMA_5),
|
||||
Migration::Sql(voelin_identity::migrate::ADD_KIND_COLUMN),
|
||||
Migration::Sql(voelin_identity::migrate::ADD_ACCOUNT_COLUMNS),
|
||||
];
|
||||
|
||||
/// Version 4: where each identity came from ([`IdentityOrigin`]) and which
|
||||
@@ -228,6 +238,12 @@ impl Bookmark {
|
||||
}
|
||||
}
|
||||
|
||||
/// How long the checkpoint that follows the deletion of a key waits for another
|
||||
/// connection ([`Store::truncate_wal`]). Short on purpose: the connection's own
|
||||
/// busy timeout is seconds, and the checkpoint holds the writer lock while it
|
||||
/// waits.
|
||||
const CHECKPOINT_WAIT: Duration = Duration::from_millis(150);
|
||||
|
||||
pub struct Store {
|
||||
pub(crate) db: Connection,
|
||||
}
|
||||
@@ -261,6 +277,13 @@ impl Store {
|
||||
// Statements run through `prepare_cached` are parsed once per connection.
|
||||
db.set_prepared_statement_cache_capacity(64);
|
||||
db.pragma_update(None, "foreign_keys", true)?;
|
||||
// Identities hold private keys. By default a delete only unlinks the
|
||||
// row: its bytes stay in the free space of the page, and in earlier
|
||||
// frames of the write-ahead log. With this SQLite overwrites what it
|
||||
// deletes with zeros, and `truncate_wal` then folds the log into the
|
||||
// file after a key is removed. It is a setting of the connection, so
|
||||
// every connection that opens the file sets it here.
|
||||
db.pragma_update(None, "secure_delete", true)?;
|
||||
// Each migration with its version bump in one write transaction: a
|
||||
// second connection that opens the file at the same time (the
|
||||
// settings writer, the chat history) waits, then sees the new version.
|
||||
@@ -287,6 +310,10 @@ impl Store {
|
||||
pub const SCHEMA_VERSION: i64 = MIGRATIONS.len() as i64;
|
||||
|
||||
// Identities
|
||||
//
|
||||
// These methods are the TeamSpeak identities (kind `teamspeak`) the client
|
||||
// has always had, and act on those rows only: the other kinds of the
|
||||
// `identities` table (a Voelin key, the signed-in account) are not theirs.
|
||||
|
||||
/// Store an identity; it is the default when no other one is.
|
||||
pub fn add_identity(
|
||||
@@ -306,7 +333,8 @@ impl Store {
|
||||
|
||||
pub fn identities(&self) -> Result<Vec<IdentityEntry>> {
|
||||
let mut stmt = self.db.prepare(
|
||||
"SELECT id, name, uid, data, origin, is_default FROM identities ORDER BY id",
|
||||
"SELECT id, name, uid, data, origin, is_default FROM identities
|
||||
WHERE kind = 'teamspeak' ORDER BY id",
|
||||
)?;
|
||||
let rows = stmt.query_map([], |r| {
|
||||
Ok((
|
||||
@@ -339,7 +367,11 @@ impl Store {
|
||||
/// and is never replaced by an import again.
|
||||
pub fn set_default_identity(&self, id: i64, by_user: bool) -> Result<()> {
|
||||
let tx = self.db.unchecked_transaction()?;
|
||||
if tx.execute("UPDATE identities SET is_default = 1 WHERE id = ?1", [id])? == 0 {
|
||||
if tx.execute(
|
||||
"UPDATE identities SET is_default = 1 WHERE id = ?1 AND kind = 'teamspeak'",
|
||||
[id],
|
||||
)? == 0
|
||||
{
|
||||
return Err(Error::NotFound("identity", id));
|
||||
}
|
||||
tx.execute("UPDATE identities SET is_default = 0 WHERE id <> ?1", [id])?;
|
||||
@@ -356,7 +388,11 @@ impl Store {
|
||||
pub fn identity(&self, id: i64) -> Result<Identity> {
|
||||
let data: Option<String> = self
|
||||
.db
|
||||
.query_row("SELECT data FROM identities WHERE id = ?1", [id], |r| r.get(0))
|
||||
.query_row(
|
||||
"SELECT data FROM identities WHERE id = ?1 AND kind = 'teamspeak'",
|
||||
[id],
|
||||
|r| r.get(0),
|
||||
)
|
||||
.optional()?;
|
||||
let data = data.ok_or(Error::NotFound("identity", id))?;
|
||||
Ok(serde_json::from_str(&data)?)
|
||||
@@ -365,23 +401,82 @@ impl Store {
|
||||
/// Store an identity again, e.g. after its security level was improved.
|
||||
pub fn update_identity(&self, id: i64, identity: &Identity) -> Result<()> {
|
||||
let n = self.db.execute(
|
||||
"UPDATE identities SET data = ?2 WHERE id = ?1",
|
||||
"UPDATE identities SET data = ?2 WHERE id = ?1 AND kind = 'teamspeak'",
|
||||
params![id, serde_json::to_string(identity)?],
|
||||
)?;
|
||||
if n == 0 { Err(Error::NotFound("identity", id)) } else { Ok(()) }
|
||||
}
|
||||
|
||||
pub fn rename_identity(&self, id: i64, name: &str) -> Result<()> {
|
||||
let n =
|
||||
self.db.execute("UPDATE identities SET name = ?2 WHERE id = ?1", params![id, name])?;
|
||||
let n = self.db.execute(
|
||||
"UPDATE identities SET name = ?2 WHERE id = ?1 AND kind = 'teamspeak'",
|
||||
params![id, name],
|
||||
)?;
|
||||
if n == 0 { Err(Error::NotFound("identity", id)) } else { Ok(()) }
|
||||
}
|
||||
|
||||
/// Delete the identity, key included: SQLite overwrites the row
|
||||
/// (`secure_delete`) and the write-ahead log is truncated, so the key is
|
||||
/// in neither the database file nor its log afterwards
|
||||
/// (`truncate_wal` says when it cannot be).
|
||||
pub fn delete_identity(&self, id: i64) -> Result<()> {
|
||||
self.db.execute("DELETE FROM identities WHERE id = ?1", [id])?;
|
||||
let deleted =
|
||||
self.db.execute("DELETE FROM identities WHERE id = ?1 AND kind = 'teamspeak'", [id])?;
|
||||
if deleted > 0 {
|
||||
self.truncate_wal();
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Fold the write-ahead log into the database file and truncate it to
|
||||
/// nothing. The delete of a key has overwritten its bytes in the page
|
||||
/// (`secure_delete`), but the frame of the log that held the page when the
|
||||
/// key was stored still has them until the log is reset, and a plain
|
||||
/// checkpoint only copies the frames. Call it after the rows of a key were
|
||||
/// deleted.
|
||||
///
|
||||
/// It is best effort, because the delete it follows has happened and a
|
||||
/// sign-out must still finish. A checkpoint that cannot complete (another
|
||||
/// connection keeps reading an old snapshot) or fails leaves the bytes in
|
||||
/// the log file, and a warning says so; they go when a later checkpoint
|
||||
/// truncates the log, when later writes overwrite those frames, or when the
|
||||
/// last connection to the database closes and the log is deleted. It does
|
||||
/// nothing to a database that is not in WAL mode and does not overwrite what
|
||||
/// was deleted before `secure_delete` was on (`VACUUM` does).
|
||||
///
|
||||
/// It waits for another connection for [`CHECKPOINT_WAIT`] at most, not for
|
||||
/// the busy timeout of the connection: while a checkpoint that truncates
|
||||
/// waits for readers it holds the writer lock of the log, so every other
|
||||
/// writer would wait with it, and fail with "database is locked" when its
|
||||
/// own timeout is shorter than the wait. The timeout the connection had is
|
||||
/// restored before this returns.
|
||||
pub(crate) fn truncate_wal(&self) {
|
||||
match self.checkpoint_truncate() {
|
||||
Ok(0) => {}
|
||||
Ok(_) => tracing::warn!(
|
||||
"a deleted key may stay in the write-ahead log: another connection blocked the checkpoint"
|
||||
),
|
||||
Err(error) => tracing::warn!(
|
||||
%error,
|
||||
"a deleted key may stay in the write-ahead log: the checkpoint failed"
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
/// `PRAGMA wal_checkpoint(TRUNCATE)` under [`CHECKPOINT_WAIT`]: whether
|
||||
/// another connection blocked it (`1`) or not (`0`).
|
||||
fn checkpoint_truncate(&self) -> rusqlite::Result<i64> {
|
||||
let previous: i64 = self.db.pragma_query_value(None, "busy_timeout", |r| r.get(0))?;
|
||||
let previous = Duration::from_millis(u64::try_from(previous).unwrap_or_default());
|
||||
self.db.busy_timeout(CHECKPOINT_WAIT)?;
|
||||
let blocked =
|
||||
self.db.query_row("PRAGMA wal_checkpoint(TRUNCATE)", [], |r| r.get::<_, i64>(0));
|
||||
if let Err(error) = self.db.busy_timeout(previous) {
|
||||
tracing::warn!(%error, "the busy timeout of the connection could not be restored");
|
||||
}
|
||||
blocked
|
||||
}
|
||||
|
||||
// Bookmarks
|
||||
|
||||
pub fn add_bookmark(&self, bookmark: &Bookmark) -> Result<i64> {
|
||||
@@ -506,6 +601,57 @@ mod tests {
|
||||
assert!(matches!(store.identity(id), Err(Error::NotFound(..))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_connection_overwrites_what_it_deletes() {
|
||||
let secure_delete = |store: &Store| -> i64 {
|
||||
store.db.pragma_query_value(None, "secure_delete", |r| r.get(0)).unwrap()
|
||||
};
|
||||
assert_eq!(secure_delete(&Store::open_in_memory().unwrap()), 1);
|
||||
let dir = scratch_dir("secure-delete");
|
||||
let path = dir.join("client.db");
|
||||
assert_eq!(secure_delete(&Store::open(&path).unwrap()), 1);
|
||||
// A second connection to the same file sets it for itself.
|
||||
assert_eq!(secure_delete(&Store::open(&path).unwrap()), 1);
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_blocked_checkpoint_waits_briefly_and_leaves_the_busy_timeout_as_it_was() {
|
||||
let dir = scratch_dir("blocked-checkpoint");
|
||||
let path = dir.join("client.db");
|
||||
let wal = dir.join("client.db-wal");
|
||||
let store = Store::open(&path).unwrap();
|
||||
store.add_identity("first", &Identity::create(), IdentityOrigin::User).unwrap();
|
||||
|
||||
// A reader whose snapshot is older than the last write keeps the log
|
||||
// from being reset.
|
||||
let reader = Connection::open(&path).unwrap();
|
||||
reader.execute_batch("BEGIN").unwrap();
|
||||
reader.query_row("SELECT count(*) FROM identities", [], |r| r.get::<_, i64>(0)).unwrap();
|
||||
store.add_identity("second", &Identity::create(), IdentityOrigin::User).unwrap();
|
||||
|
||||
// A value that is not the default, so that restoring a constant would show.
|
||||
let timeout = |store: &Store| -> i64 {
|
||||
store.db.pragma_query_value(None, "busy_timeout", |r| r.get(0)).unwrap()
|
||||
};
|
||||
store.db.busy_timeout(Duration::from_millis(2345)).unwrap();
|
||||
let started = std::time::Instant::now();
|
||||
store.truncate_wal();
|
||||
let elapsed = started.elapsed();
|
||||
assert!(elapsed < Duration::from_secs(1), "the checkpoint waited {elapsed:?}");
|
||||
assert!(std::fs::metadata(&wal).unwrap().len() > 0, "the reader should block the reset");
|
||||
assert_eq!(timeout(&store), 2345);
|
||||
|
||||
// Without the reader the same call resets the log.
|
||||
reader.execute_batch("COMMIT").unwrap();
|
||||
store.truncate_wal();
|
||||
assert_eq!(std::fs::metadata(&wal).unwrap().len(), 0);
|
||||
assert_eq!(timeout(&store), 2345);
|
||||
drop(reader);
|
||||
drop(store);
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_default_identity() {
|
||||
let store = Store::open_in_memory().unwrap();
|
||||
@@ -595,7 +741,7 @@ mod tests {
|
||||
.unwrap();
|
||||
}
|
||||
let store = Store::open(&path).unwrap();
|
||||
assert_eq!(Store::SCHEMA_VERSION, 5);
|
||||
assert_eq!(Store::SCHEMA_VERSION, 7);
|
||||
assert_eq!(store.schema_version().unwrap(), Store::SCHEMA_VERSION);
|
||||
let channel = ChatTarget::Channel(1);
|
||||
let rows = store.messages("srv", &channel, PageQuery::default()).unwrap();
|
||||
@@ -611,6 +757,350 @@ mod tests {
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
/// What `serde_json::to_string(&tsproto::Identity)` writes for the test
|
||||
/// identity of tsproto's own `identity_tests` (the fixture row of
|
||||
/// `voelin-identity`'s `tests/storage.rs`): its unique id and security
|
||||
/// level are checked against the real tsproto below.
|
||||
const TEAMSPEAK_JSON: &str = r#"{"key":"YTyJofmztcTBjq3KZcDdxu+G4RPVwE5vg8VaN2jbQao=","counter":2792354,"max_counter":2792354}"#;
|
||||
const TEAMSPEAK_UID: &str = "test/9PZ9vww/Bpf5vJxtJhpz80=";
|
||||
const TEAMSPEAK_LEVEL: u8 = 21;
|
||||
|
||||
/// A `client.db` as it was at schema `version`: the migrations below
|
||||
/// `version` applied by the code that runs them, nothing else.
|
||||
fn database_at(path: &Path, version: usize) {
|
||||
let mut db = rusqlite::Connection::open(path).unwrap();
|
||||
for migration in &MIGRATIONS[..version] {
|
||||
match migration {
|
||||
Migration::Sql(sql) => db.execute_batch(sql).unwrap(),
|
||||
Migration::Code(migrate) => {
|
||||
let tx = db.transaction().unwrap();
|
||||
migrate(&tx).unwrap();
|
||||
tx.commit().unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
db.pragma_update(None, "user_version", version as i64).unwrap();
|
||||
}
|
||||
|
||||
fn scratch_dir(name: &str) -> std::path::PathBuf {
|
||||
let dir = std::env::temp_dir().join(format!("voelin-store-{name}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
dir
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_teamspeak_fixture_is_what_tsproto_writes() {
|
||||
let identity: Identity = serde_json::from_str(TEAMSPEAK_JSON).unwrap();
|
||||
assert_eq!(identity.key().to_pub().get_uid(), TEAMSPEAK_UID);
|
||||
assert_eq!(identity.level(), TEAMSPEAK_LEVEL);
|
||||
assert_eq!(serde_json::to_string(&identity).unwrap(), TEAMSPEAK_JSON);
|
||||
}
|
||||
|
||||
/// The identity migrations are `voelin-identity`'s SQL, and a shipped
|
||||
/// version never changes: a newer revision of the protocol repository
|
||||
/// that touched either string would fail here instead of changing what
|
||||
/// version 6 or 7 does to an installed database.
|
||||
#[test]
|
||||
fn the_identity_migrations_are_pinned() {
|
||||
let sql = |index: usize| match &MIGRATIONS[index] {
|
||||
Migration::Sql(sql) => *sql,
|
||||
Migration::Code(_) => panic!("migration {index} is code"),
|
||||
};
|
||||
assert_eq!(MIGRATIONS.len(), 7);
|
||||
assert_eq!(
|
||||
sql(5),
|
||||
"ALTER TABLE identities ADD COLUMN kind TEXT NOT NULL DEFAULT 'teamspeak';"
|
||||
);
|
||||
assert_eq!(
|
||||
sql(6),
|
||||
"ALTER TABLE identities ADD COLUMN account TEXT;\n\
|
||||
ALTER TABLE identities ADD COLUMN integration TEXT;\n\
|
||||
ALTER TABLE identities ADD COLUMN integration_rev INTEGER NOT NULL DEFAULT 0;\n\
|
||||
ALTER TABLE identities ADD COLUMN synced INTEGER NOT NULL DEFAULT 0;"
|
||||
);
|
||||
}
|
||||
|
||||
/// A database of version 5 (what 0.1 ships) gets the `kind` column and
|
||||
/// then the account columns in one open; every identity stays as it was:
|
||||
/// kind `teamspeak`, unbound, its JSON byte for byte, its origin and
|
||||
/// default flag, and the level computed from the key as before.
|
||||
#[test]
|
||||
fn migrates_version_5_identities_through_both_steps() {
|
||||
use voelin_identity::migrate::SELECT_ACCOUNT_COLUMNS;
|
||||
use voelin_identity::{AccountBinding, IdentityBlob, KIND_TEAMSPEAK};
|
||||
|
||||
let dir = scratch_dir("v5");
|
||||
let path = dir.join("client.db");
|
||||
let other = Identity::create();
|
||||
let other_json = serde_json::to_string(&other).unwrap();
|
||||
let other_uid = other.key().to_pub().get_uid();
|
||||
database_at(&path, 5);
|
||||
{
|
||||
let db = rusqlite::Connection::open(&path).unwrap();
|
||||
assert_eq!(
|
||||
db.pragma_query_value(None, "user_version", |r| r.get::<_, i64>(0)).unwrap(),
|
||||
5
|
||||
);
|
||||
for (name, uid, json, origin, default) in [
|
||||
("Main", TEAMSPEAK_UID, TEAMSPEAK_JSON, "imported", 1),
|
||||
("Other", other_uid.as_str(), other_json.as_str(), "user", 0),
|
||||
] {
|
||||
db.execute(
|
||||
"INSERT INTO identities (name, uid, data, origin, is_default)
|
||||
VALUES (?1, ?2, ?3, ?4, ?5)",
|
||||
params![name, uid, json, origin, default],
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
let store = Store::open(&path).unwrap();
|
||||
assert_eq!(Store::SCHEMA_VERSION, 7);
|
||||
assert_eq!(store.schema_version().unwrap(), 7);
|
||||
|
||||
// Read as the key store reads a row of the migrated table.
|
||||
let rows: Vec<_> = store
|
||||
.db
|
||||
.prepare(&format!("SELECT {SELECT_ACCOUNT_COLUMNS} FROM identities ORDER BY id"))
|
||||
.unwrap()
|
||||
.query_map([], |r| {
|
||||
Ok((
|
||||
r.get::<_, String>(0)?,
|
||||
r.get::<_, String>(1)?,
|
||||
r.get::<_, String>(2)?,
|
||||
r.get::<_, Option<String>>(3)?,
|
||||
r.get::<_, Option<String>>(4)?,
|
||||
r.get::<_, i64>(5)?,
|
||||
r.get::<_, i64>(6)?,
|
||||
))
|
||||
})
|
||||
.unwrap()
|
||||
.collect::<rusqlite::Result<_>>()
|
||||
.unwrap();
|
||||
assert_eq!(rows.len(), 2);
|
||||
for ((kind, uid, data, account, integration, rev, synced), (want_uid, want_json)) in
|
||||
rows.into_iter().zip([(TEAMSPEAK_UID, TEAMSPEAK_JSON), (&*other_uid, &*other_json)])
|
||||
{
|
||||
assert_eq!(kind, KIND_TEAMSPEAK);
|
||||
let binding = AccountBinding::from_columns(
|
||||
account.as_deref(),
|
||||
integration.as_deref(),
|
||||
rev,
|
||||
synced,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(binding, None, "an old row is unbound");
|
||||
assert_eq!((uid.as_str(), data.as_str()), (want_uid, want_json), "byte for byte");
|
||||
let blob = IdentityBlob::from_row(&kind, uid, 0, data);
|
||||
assert!(blob.is_teamspeak());
|
||||
}
|
||||
|
||||
// The old API sees what it saw before, origin and default included.
|
||||
let list = store.identities().unwrap();
|
||||
assert_eq!(list.len(), 2);
|
||||
assert_eq!((list[0].name.as_str(), list[0].uid.as_str()), ("Main", TEAMSPEAK_UID));
|
||||
assert_eq!(
|
||||
(list[0].level, list[0].origin, list[0].is_default),
|
||||
(21, IdentityOrigin::Imported, true)
|
||||
);
|
||||
assert_eq!((list[1].name.as_str(), list[1].uid.as_str()), ("Other", &*other_uid));
|
||||
assert_eq!(
|
||||
(list[1].level, list[1].origin, list[1].is_default),
|
||||
(other.level(), IdentityOrigin::User, false)
|
||||
);
|
||||
assert_eq!(store.default_identity().unwrap().unwrap().id, list[0].id);
|
||||
assert_eq!(store.identity(list[1].id).unwrap().counter(), other.counter());
|
||||
drop(store);
|
||||
|
||||
// Opened again, nothing runs twice.
|
||||
let store = Store::open(&path).unwrap();
|
||||
assert_eq!(store.schema_version().unwrap(), 7);
|
||||
assert_eq!(store.identities().unwrap(), list);
|
||||
drop(store);
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
/// The acceptance of the migration for the key store: a `client.db` at the
|
||||
/// version before the identity migrations (5), and at the one between them
|
||||
/// (6), opens, and every identity loads through the key store unchanged:
|
||||
/// kind `teamspeak`, no binding, its JSON byte for byte, the level computed
|
||||
/// as before, and the origin and default flag the old API reports kept.
|
||||
#[test]
|
||||
fn a_migrated_database_loads_every_identity_unchanged_through_the_key_store() {
|
||||
use crate::SqliteKeyStore;
|
||||
use voelin_identity::{IdentityBlob, IdentityInfo, KIND_TEAMSPEAK, KeyStore};
|
||||
|
||||
for version in [5, 6] {
|
||||
let dir = scratch_dir(&format!("keys-v{version}"));
|
||||
let path = dir.join("client.db");
|
||||
let other = Identity::create();
|
||||
let other_json = serde_json::to_string(&other).unwrap();
|
||||
let other_uid = other.key().to_pub().get_uid();
|
||||
database_at(&path, version);
|
||||
{
|
||||
let db = rusqlite::Connection::open(&path).unwrap();
|
||||
for (name, uid, json, origin, default) in [
|
||||
("Main", TEAMSPEAK_UID, TEAMSPEAK_JSON, "imported", 1),
|
||||
("Other", other_uid.as_str(), other_json.as_str(), "created", 0),
|
||||
] {
|
||||
db.execute(
|
||||
"INSERT INTO identities (name, uid, data, origin, is_default)
|
||||
VALUES (?1, ?2, ?3, ?4, ?5)",
|
||||
params![name, uid, json, origin, default],
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
let keys = SqliteKeyStore::open(&path).unwrap();
|
||||
assert_eq!(keys.with_store(|s| s.schema_version().unwrap()), 7);
|
||||
let want = [
|
||||
(TEAMSPEAK_UID.to_owned(), TEAMSPEAK_JSON.to_owned(), TEAMSPEAK_LEVEL),
|
||||
(other_uid.clone(), other_json.clone(), other.level()),
|
||||
];
|
||||
let mut infos: Vec<_> = want
|
||||
.iter()
|
||||
.map(|(uid, _, level)| IdentityInfo {
|
||||
kind: KIND_TEAMSPEAK.into(),
|
||||
uid: uid.clone(),
|
||||
level: *level,
|
||||
binding: None,
|
||||
})
|
||||
.collect();
|
||||
infos.sort_by(|a, b| a.uid.cmp(&b.uid));
|
||||
assert_eq!(keys.list().unwrap(), infos, "version {version}");
|
||||
for (uid, json, level) in want {
|
||||
let blob = keys.get(KIND_TEAMSPEAK, &uid).unwrap().unwrap();
|
||||
assert_eq!(blob, IdentityBlob::teamspeak(&uid, level, &json), "version {version}");
|
||||
assert_eq!(blob.json, json, "byte for byte");
|
||||
assert_eq!(blob.binding, None);
|
||||
}
|
||||
|
||||
// What the TeamSpeak methods report is kept as well.
|
||||
let entries = keys.with_store(|s| s.identities().unwrap());
|
||||
let origin = |uid: &str| entries.iter().find(|e| e.uid == uid).unwrap();
|
||||
assert_eq!(
|
||||
(origin(TEAMSPEAK_UID).origin, origin(TEAMSPEAK_UID).is_default),
|
||||
(IdentityOrigin::Imported, true)
|
||||
);
|
||||
assert_eq!(
|
||||
(origin(&other_uid).origin, origin(&other_uid).is_default),
|
||||
(IdentityOrigin::Created, false)
|
||||
);
|
||||
drop(keys);
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
/// A database of version 6 (the `kind` column, no account columns yet) takes
|
||||
/// the second step alone, and its rows of other kinds stay what they are.
|
||||
#[test]
|
||||
fn migrates_version_6_identities_to_accounts() {
|
||||
let dir = scratch_dir("v6");
|
||||
let path = dir.join("client.db");
|
||||
database_at(&path, 6);
|
||||
{
|
||||
let db = rusqlite::Connection::open(&path).unwrap();
|
||||
db.execute(
|
||||
"INSERT INTO identities (name, uid, data, origin, is_default)
|
||||
VALUES ('Main', ?1, ?2, 'created', 1)",
|
||||
params![TEAMSPEAK_UID, TEAMSPEAK_JSON],
|
||||
)
|
||||
.unwrap();
|
||||
db.execute(
|
||||
"INSERT INTO identities (name, uid, data, kind)
|
||||
VALUES ('key', 'abc', '{\"v\":1}', 'voelin')",
|
||||
[],
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
let store = Store::open(&path).unwrap();
|
||||
assert_eq!(store.schema_version().unwrap(), 7);
|
||||
let (kind, account, integration, rev, synced): (
|
||||
String,
|
||||
Option<String>,
|
||||
Option<String>,
|
||||
i64,
|
||||
i64,
|
||||
) = store
|
||||
.db
|
||||
.query_row(
|
||||
"SELECT kind, account, integration, integration_rev, synced FROM identities
|
||||
WHERE uid = 'abc'",
|
||||
[],
|
||||
|r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?, r.get(4)?)),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
(kind.as_str(), account, integration, rev, synced),
|
||||
("voelin", None, None, 0, 0)
|
||||
);
|
||||
let list = store.identities().unwrap();
|
||||
assert_eq!(list.len(), 1, "the Voelin row is not a TeamSpeak identity");
|
||||
assert_eq!(
|
||||
(list[0].origin, list[0].is_default, list[0].level),
|
||||
(IdentityOrigin::Created, true, 21)
|
||||
);
|
||||
drop(store);
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
/// Rows of other kinds share the table with the TeamSpeak identities and
|
||||
/// are none of the TeamSpeak methods' business: they are not listed, not
|
||||
/// read as an identity, not renamed, changed, made the default or deleted
|
||||
/// (the JSON of a Voelin key is not a `tsproto::Identity`, and listing
|
||||
/// would fail on it).
|
||||
#[test]
|
||||
fn the_teamspeak_methods_leave_other_kinds_alone() {
|
||||
let store = Store::open_in_memory().unwrap();
|
||||
let mine = Identity::create();
|
||||
let id = store.add_identity("mine", &mine, IdentityOrigin::User).unwrap();
|
||||
let other_id = |kind: &str, uid: &str| {
|
||||
store
|
||||
.db
|
||||
.execute(
|
||||
"INSERT INTO identities (name, uid, data, kind) VALUES (?1, ?2, '{\"v\":1}', ?1)",
|
||||
params![kind, uid],
|
||||
)
|
||||
.unwrap();
|
||||
store.db.last_insert_rowid()
|
||||
};
|
||||
let voelin = other_id("voelin", "v1");
|
||||
let account = other_id("account", "account:a1");
|
||||
|
||||
let list = store.identities().unwrap();
|
||||
assert_eq!(list.iter().map(|e| e.id).collect::<Vec<_>>(), [id]);
|
||||
assert_eq!(store.default_identity().unwrap().unwrap().id, id);
|
||||
for other in [voelin, account] {
|
||||
assert!(matches!(store.identity(other), Err(Error::NotFound(..))));
|
||||
assert!(matches!(store.rename_identity(other, "x"), Err(Error::NotFound(..))));
|
||||
assert!(matches!(store.update_identity(other, &mine), Err(Error::NotFound(..))));
|
||||
assert!(matches!(store.set_default_identity(other, true), Err(Error::NotFound(..))));
|
||||
store.delete_identity(other).unwrap();
|
||||
}
|
||||
let rows: i64 =
|
||||
store.db.query_row("SELECT count(*) FROM identities", [], |r| r.get(0)).unwrap();
|
||||
assert_eq!(rows, 3, "nothing of another kind was deleted");
|
||||
let names: Vec<String> = store
|
||||
.db
|
||||
.prepare("SELECT name FROM identities ORDER BY id")
|
||||
.unwrap()
|
||||
.query_map([], |r| r.get(0))
|
||||
.unwrap()
|
||||
.collect::<rusqlite::Result<_>>()
|
||||
.unwrap();
|
||||
assert_eq!(names, ["mine", "voelin", "account"]);
|
||||
let defaults: i64 = store
|
||||
.db
|
||||
.query_row("SELECT count(*) FROM identities WHERE is_default", [], |r| r.get(0))
|
||||
.unwrap();
|
||||
assert_eq!(defaults, 1);
|
||||
// A TeamSpeak identity is deleted as before.
|
||||
store.delete_identity(id).unwrap();
|
||||
assert!(store.identities().unwrap().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bookmarks_keep_order_and_fields() {
|
||||
let store = Store::open_in_memory().unwrap();
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -22,6 +22,9 @@ tokio = { version = "1", features = ["macros", "net", "rt", "sync", "time"] }
|
||||
tracing = "0.1"
|
||||
tsclientlib = { path = "../proto/tsclientlib" }
|
||||
tsproto-packets = { path = "../proto/tsproto-packets" }
|
||||
# The frame and simulcast layer types (`EncodedFrame`, `LayerSpec`), which the
|
||||
# media side owns; re-exported here.
|
||||
voelin-media = { path = "../voelin-media", default-features = false }
|
||||
|
||||
[dev-dependencies]
|
||||
anyhow = "1"
|
||||
|
||||
@@ -1,83 +1,13 @@
|
||||
//! Simulcast layers: several encodings of one stream, each with its own size,
|
||||
//! frame rate and bitrate.
|
||||
//! Simulcast layers of a stream. The types ([`LayerSpec`], [`LayerId`],
|
||||
//! [`LayerSet`]) are `voelin-media`'s; this module keeps how a streamer's
|
||||
//! offer lists its layers in the SDP, so that a Voelin viewer can pick one.
|
||||
//!
|
||||
//! The streamer encodes every layer of its [`LayerSpec`] list and tags each
|
||||
//! [`EncodedFrame`](crate::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.
|
||||
//! negotiate RID simulcast (`a=simulcast`) get all of them.
|
||||
|
||||
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))
|
||||
}
|
||||
}
|
||||
pub use voelin_media::layer::{LayerId, LayerSet, LayerSpec};
|
||||
|
||||
/// The session-level SDP attribute in which a Voelin streamer's offer lists
|
||||
/// its layers, so that a Voelin viewer can pick one (`Signal::Layer`):
|
||||
@@ -129,119 +59,10 @@ pub fn from_sdp(sdp: &str) -> Option<Vec<LayerSpec>> {
|
||||
Some(value.split_whitespace().filter_map(layer).collect())
|
||||
}
|
||||
|
||||
/// 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 layers_in_the_sdp() {
|
||||
let layers = vec![
|
||||
@@ -265,16 +86,4 @@ mod tests {
|
||||
[LayerSpec { id: 2, ..LayerSpec::single(700_000) }]
|
||||
);
|
||||
}
|
||||
|
||||
#[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));
|
||||
}
|
||||
}
|
||||
@@ -8,24 +8,10 @@ use std::sync::Arc;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use str0m::media::{Frequency, MediaKind, MediaTime};
|
||||
pub use voelin_media::stream::EncodedFrame;
|
||||
|
||||
use crate::layer::{LayerId, LayerSpec};
|
||||
|
||||
/// One encoded video or audio frame.
|
||||
#[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,
|
||||
}
|
||||
|
||||
/// Produces encoded frames in real time.
|
||||
pub trait FrameSource: Send {
|
||||
/// Append the frames that are due at `now`.
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
[package]
|
||||
name = "voelin-ui-vm"
|
||||
version = "0.0.1-alpha"
|
||||
description = "Toolkit-free view models of the desktop client: engine state turned into plain rows, shared by the Slint and GPUI front ends."
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
license.workspace = true
|
||||
repository.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[lib]
|
||||
name = "voelin_ui_vm"
|
||||
path = "src/lib.rs"
|
||||
|
||||
# No UI toolkit here (no slint, no gpui): `cargo tree -p voelin-ui-vm -e normal`
|
||||
# must show neither. The front ends convert these types (docs/ui.md).
|
||||
[dependencies]
|
||||
chrono = { version = "0.4.45", default-features = false, features = ["clock"] }
|
||||
# Picture sizes (the header of a file); PNG and JPEG are listed as the
|
||||
# front end's toolkit used to bring them.
|
||||
image = { version = "0.25", default-features = false, features = ["png", "jpeg", "gif", "webp", "bmp", "ico"] }
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
# JSON values of the settings and the gateway's configuration keys.
|
||||
serde_json = "1"
|
||||
# The Twemoji archive's blocks (raw deflate).
|
||||
miniz_oxide = "0.8"
|
||||
# Grapheme clusters for emoji in chat text.
|
||||
unicode-segmentation = "1.13"
|
||||
voelin-audio = { path = "../voelin-audio", default-features = false }
|
||||
voelin-core = { path = "../voelin-core", default-features = false, features = ["media"] }
|
||||
voelin-gateway-proto = { path = "../voelin-gateway-proto" }
|
||||
voelin-model = { path = "../voelin-model" }
|
||||
voelin-store = { path = "../voelin-store" }
|
||||
|
||||
[dev-dependencies]
|
||||
png = "0.18"
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -0,0 +1,11 @@
|
||||
# Bundled assets
|
||||
|
||||
- `twemoji.bin`: the Twemoji 15.0 SVGs (3720 emoji, from the `@twemoji/svg`
|
||||
15.0.0 package) packed by `scripts/pack-twemoji.py` into blocks of raw
|
||||
deflate with an index; `src/emoji.rs` reads it. Twemoji graphics by Twitter,
|
||||
Inc and other contributors, licensed under CC-BY 4.0
|
||||
(https://creativecommons.org/licenses/by/4.0/). The files are unchanged
|
||||
apart from surrounding whitespace.
|
||||
|
||||
It is credited in `THIRD_PARTY_NOTICES.md` and the About page, with the fonts
|
||||
and icons of the Slint front end (`crates/voelin-ui/assets/README.md`).
|
||||
File renamed without changes.
@@ -1,8 +1,10 @@
|
||||
//! Avatars without pictures: initials on a colour from the name.
|
||||
|
||||
use slint::Color;
|
||||
use unicode_segmentation::UnicodeSegmentation;
|
||||
|
||||
use crate::color::Rgb;
|
||||
use crate::image::{ImageRef, ImageSource};
|
||||
|
||||
/// Background colours for initials; white text reads on all of them.
|
||||
const TINTS: [u32; 10] = [
|
||||
0x2d6bff, 0x7c4dff, 0xc2379a, 0xe0572e, 0xd08a00, 0x1f9d6b, 0x0c93b8, 0x5865f2, 0xa0439e,
|
||||
@@ -31,10 +33,10 @@ pub fn first_letter(initials: &str) -> String {
|
||||
initials.graphemes(true).next().unwrap_or_default().to_owned()
|
||||
}
|
||||
|
||||
/// A picture from the engine's cache (an avatar, a group icon), decoded
|
||||
/// once; an empty image when there is none.
|
||||
pub fn image(path: Option<&std::path::PathBuf>) -> slint::Image {
|
||||
path.map(|p| crate::images::file(p)).unwrap_or_default()
|
||||
/// A picture from the engine's cache (an avatar, a group icon); none when
|
||||
/// there is no path.
|
||||
pub fn image(path: Option<&std::path::PathBuf>) -> ImageRef {
|
||||
path.map(ImageSource::file).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// A stable number for a name, in any case (FNV-1a).
|
||||
@@ -48,12 +50,12 @@ pub fn name_hash(name: &str) -> u32 {
|
||||
}
|
||||
|
||||
/// `0xrrggbb` as a colour.
|
||||
pub fn rgb(rgb: u32) -> Color {
|
||||
Color::from_rgb_u8((rgb >> 16) as u8, (rgb >> 8) as u8, rgb as u8)
|
||||
pub fn rgb(rgb: u32) -> Rgb {
|
||||
Rgb::from(rgb)
|
||||
}
|
||||
|
||||
/// A stable colour for a name.
|
||||
pub fn tint(name: &str) -> Color {
|
||||
pub fn tint(name: &str) -> Rgb {
|
||||
rgb(TINTS[(name_hash(name) % TINTS.len() as u32) as usize])
|
||||
}
|
||||
|
||||
@@ -86,10 +88,7 @@ mod tests {
|
||||
fn tints_are_stable() {
|
||||
assert_eq!(tint("Alice"), tint("alice"));
|
||||
let distinct: std::collections::HashSet<_> =
|
||||
["Alice", "Bob", "Carol", "Dave", "Eve", "Mallory"]
|
||||
.iter()
|
||||
.map(|n| tint(n).as_argb_encoded())
|
||||
.collect();
|
||||
["Alice", "Bob", "Carol", "Dave", "Eve", "Mallory"].iter().map(|n| tint(n).0).collect();
|
||||
assert!(distinct.len() > 2);
|
||||
}
|
||||
}
|
||||
File renamed without changes.
@@ -0,0 +1,934 @@
|
||||
//! The bridge structs: the rows and forms the screens show, as plain
|
||||
//! values. They mirror the Slint structs of `crates/voelin-ui/ui/bridge.slint`
|
||||
//! field by field (strings are shared `Arc<str>`, pictures [`ImageRef`],
|
||||
//! colours [`Rgb`], lists `Vec`); the Slint crate converts them
|
||||
//! (`bind/convert.rs`), the GPUI client will render them as they are.
|
||||
//! `MytsBadge` and `MytsForm` (account screens without a data source in this
|
||||
//! build) stay in Slint.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::color::Rgb;
|
||||
use crate::image::ImageRef;
|
||||
|
||||
/// A row or form of the bridge (the plain counterpart of the Slint struct `ServerItem`).
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct ServerItem {
|
||||
pub id: i32,
|
||||
pub name: Arc<str>,
|
||||
pub address: Arc<str>,
|
||||
/// "offline", "connecting", "observing" or "connected"
|
||||
pub status: Arc<str>,
|
||||
/// Avatar of a server without an icon.
|
||||
pub initials: Arc<str>,
|
||||
pub tint: Rgb,
|
||||
/// The server's icon, empty without one.
|
||||
pub icon: ImageRef,
|
||||
/// Unread messages in its chats.
|
||||
pub unread: i32,
|
||||
/// Someone streams in our channel there.
|
||||
pub live: bool,
|
||||
/// "9 online · 7 channels" while its presence is known, else the address.
|
||||
pub detail: Arc<str>,
|
||||
/// "TeamSpeak 6", "TeamSpeak 3", "" before it was reached.
|
||||
pub product: Arc<str>,
|
||||
/// Gateway or query credentials: presence without joining.
|
||||
pub gateway: bool,
|
||||
}
|
||||
|
||||
/// A row or form of the bridge (the plain counterpart of the Slint struct `TreeItem`).
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct TreeItem {
|
||||
pub is_channel: bool,
|
||||
/// A TeamSpeak spacer channel, its name without the `[cspacer1]` part:
|
||||
/// 0 none, 1 left, 2 centred, 3 right, 4 a line (the name repeats its
|
||||
/// pattern across the row).
|
||||
pub spacer: i32,
|
||||
pub depth: i32,
|
||||
pub id: i32,
|
||||
pub name: Arc<str>,
|
||||
pub own: bool,
|
||||
pub talking: bool,
|
||||
pub muted: bool,
|
||||
pub sound_off: bool,
|
||||
pub away: bool,
|
||||
pub streaming: bool,
|
||||
pub locked: bool,
|
||||
pub collapsed: bool,
|
||||
/// Local playback of this client: muted, or its volume in percent
|
||||
/// (100 = unchanged).
|
||||
pub local_muted: bool,
|
||||
pub local_volume: i32,
|
||||
/// Our own client.
|
||||
pub myself: bool,
|
||||
/// Avatar of a client.
|
||||
pub initials: Arc<str>,
|
||||
pub tint: Rgb,
|
||||
/// The client's avatar picture, empty without one.
|
||||
pub avatar: ImageRef,
|
||||
/// Channels: clients inside, and the limit (-1: none).
|
||||
pub members: i32,
|
||||
pub max_members: i32,
|
||||
/// Leading channel icon or trailing client icons, empty where absent: a channel's
|
||||
/// icon; a client's server group icons, its channel group's and its own,
|
||||
/// in that order (the first three).
|
||||
pub icon: ImageRef,
|
||||
pub icon_2: ImageRef,
|
||||
pub icon_3: ImageRef,
|
||||
/// A client's badges (myTeamSpeak), the first three in its order, empty
|
||||
/// where absent; shown after the name.
|
||||
pub badge: ImageRef,
|
||||
pub badge_2: ImageRef,
|
||||
pub badge_3: ImageRef,
|
||||
/// A channel's banner picture (TeamSpeak 6), drawn behind the row;
|
||||
/// Wire sizing metadata; compact decorative backgrounds always cover.
|
||||
pub banner: ImageRef,
|
||||
pub banner_mode: i32,
|
||||
}
|
||||
|
||||
/// A client for the members panel (everyone on the server) and the voice
|
||||
/// channel view (our channel).
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct MemberItem {
|
||||
pub id: i32,
|
||||
pub name: Arc<str>,
|
||||
pub initials: Arc<str>,
|
||||
pub tint: Rgb,
|
||||
pub avatar: ImageRef,
|
||||
pub talking: bool,
|
||||
pub muted: bool,
|
||||
pub sound_off: bool,
|
||||
pub away: bool,
|
||||
pub streaming: bool,
|
||||
pub myself: bool,
|
||||
/// "Speaking", "Streaming", "Away", ...
|
||||
pub status: Arc<str>,
|
||||
/// The away message, empty without one.
|
||||
pub away_message: Arc<str>,
|
||||
/// The section the row is in (a server group, "In Voice",
|
||||
/// "Streaming"), and the group's icon.
|
||||
pub group: Arc<str>,
|
||||
pub group_icon: ImageRef,
|
||||
/// The first row of its section draws the heading, with the number of
|
||||
/// rows in the section.
|
||||
pub first_in_group: bool,
|
||||
pub group_count: i32,
|
||||
/// Badges: a crown for the server's admin groups.
|
||||
pub admin: bool,
|
||||
/// A moderator group's name, shown as a role next to the name.
|
||||
pub role: Arc<str>,
|
||||
pub priority: bool,
|
||||
pub commander: bool,
|
||||
pub recording: bool,
|
||||
/// Its channel needs more talk power than it has (and it is no
|
||||
/// talker): it cannot speak.
|
||||
pub cannot_talk: bool,
|
||||
/// myTeamSpeak badges, as in `TreeItem`.
|
||||
pub badge: ImageRef,
|
||||
pub badge_2: ImageRef,
|
||||
pub badge_3: ImageRef,
|
||||
}
|
||||
|
||||
/// A myTeamSpeak badge on the member card: "Badge" and its GUID for one
|
||||
/// the app does not know; its picture is empty until it is downloaded.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct BadgeItem {
|
||||
pub name: Arc<str>,
|
||||
pub description: Arc<str>,
|
||||
pub icon: ImageRef,
|
||||
}
|
||||
|
||||
/// The member card over a member row: everything about one client and what
|
||||
/// can be done with them.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct MemberCard {
|
||||
pub open: bool,
|
||||
pub id: i32,
|
||||
pub name: Arc<str>,
|
||||
pub initials: Arc<str>,
|
||||
pub tint: Rgb,
|
||||
pub avatar: ImageRef,
|
||||
pub status: Arc<str>,
|
||||
pub description: Arc<str>,
|
||||
/// Server groups, one per line.
|
||||
pub groups: Vec<Arc<str>>,
|
||||
/// The badges the client shows (at most three, in its order).
|
||||
pub badges: Vec<BadgeItem>,
|
||||
pub country: Arc<str>,
|
||||
pub talk_power: i32,
|
||||
pub friend: bool,
|
||||
pub blocked: bool,
|
||||
/// Local playback, in percent.
|
||||
pub volume: f32,
|
||||
pub muted: bool,
|
||||
/// The client has a unique id, so contacts and private chats work.
|
||||
pub known: bool,
|
||||
/// The client streams: the card offers to watch it.
|
||||
pub streaming: bool,
|
||||
}
|
||||
|
||||
/// A row or form of the bridge (the plain counterpart of the Slint struct `ChatTab`).
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct ChatTab {
|
||||
/// "Lobby", "@alice", "Server"
|
||||
pub title: Arc<str>,
|
||||
/// The name alone ("Lobby").
|
||||
pub name: Arc<str>,
|
||||
/// 0 = server chat, 1 = channel chat, 2 = private chat
|
||||
pub kind: i32,
|
||||
pub id: i32,
|
||||
pub unread: i32,
|
||||
/// The channel's topic (channel chats).
|
||||
pub topic: Arc<str>,
|
||||
/// The last message ("Mira: the banner I promised") and its time.
|
||||
pub last: Arc<str>,
|
||||
pub time: Arc<str>,
|
||||
/// The channel's banner picture behind the chat's header (as TreeItem).
|
||||
pub banner: ImageRef,
|
||||
pub banner_mode: i32,
|
||||
}
|
||||
|
||||
/// A piece of a chat line: a word in its style, or an emoji shown as an
|
||||
/// image (`emoji` is its Twemoji key, e.g. "1f600"; `text` then holds the
|
||||
/// characters).
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct TextRun {
|
||||
pub text: Arc<str>,
|
||||
pub emoji: Arc<str>,
|
||||
pub bold: bool,
|
||||
pub italic: bool,
|
||||
pub underline: bool,
|
||||
pub strike: bool,
|
||||
/// Code: on a background.
|
||||
pub code: bool,
|
||||
/// The author's colour, made readable on each theme; transparent: the
|
||||
/// text's own.
|
||||
pub ink_dark: Option<Rgb>,
|
||||
pub ink_light: Option<Rgb>,
|
||||
/// Where it links to ("": nowhere), and whether its text shows something
|
||||
/// else (a page's name, another address): asked about before it opens.
|
||||
pub link: Arc<str>,
|
||||
pub masked: bool,
|
||||
}
|
||||
|
||||
/// A block of a chat line (`vm::bbcode`): its runs, and what it is.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct TextBlock {
|
||||
pub runs: Vec<TextRun>,
|
||||
/// 0 = a line, 1 = a quote's line, 2 = a line of code, 3 = a list item,
|
||||
/// 4 = a rule (no runs)
|
||||
pub kind: i32,
|
||||
/// Who a quote quotes, on its first line.
|
||||
pub caption: Arc<str>,
|
||||
}
|
||||
|
||||
/// One emoji under a message, with how many put it there.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct ReactionItem {
|
||||
/// The Twemoji key of the first emoji in `text` ("1f389"), for the image.
|
||||
pub key: Arc<str>,
|
||||
pub text: Arc<str>,
|
||||
pub count: i32,
|
||||
/// We reacted with it.
|
||||
pub me: bool,
|
||||
}
|
||||
|
||||
/// A file linked in a message (`ChatMessage::file_refs`).
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct FileItem {
|
||||
pub name: Arc<str>,
|
||||
/// "2.4 MB", or what the transfer is doing.
|
||||
pub detail: Arc<str>,
|
||||
/// Index of the link in the message (what `download-file` takes).
|
||||
pub index: i32,
|
||||
/// "", "running", "done", "failed"
|
||||
pub state: Arc<str>,
|
||||
/// 0 … 1 while it downloads.
|
||||
pub progress: f32,
|
||||
/// A picture, so the icon differs.
|
||||
pub picture: bool,
|
||||
/// The picture itself, once downloaded: shown inline instead of the card.
|
||||
pub preview: ImageRef,
|
||||
}
|
||||
|
||||
/// A row or form of the bridge (the plain counterpart of the Slint struct `ChatLine`).
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct ChatLine {
|
||||
/// A handle for this message in its chat, stable while the chat is open
|
||||
/// (the engine's ids do not fit a Slint int).
|
||||
pub key: i32,
|
||||
pub author: Arc<str>,
|
||||
/// The text without formatting, a line per block (shown as it is when
|
||||
/// the message has neither formatting nor emoji, and read out).
|
||||
pub text: Arc<str>,
|
||||
pub time: Arc<str>,
|
||||
/// The text in blocks of styled runs; only filled when it has
|
||||
/// formatting or emoji (`rich`).
|
||||
pub blocks: Vec<TextBlock>,
|
||||
pub rich: bool,
|
||||
/// Only one to three emoji: shown large.
|
||||
pub jumbo: bool,
|
||||
/// Same author as the line before, shortly after: no header.
|
||||
pub continued: bool,
|
||||
pub initials: Arc<str>,
|
||||
pub tint: Rgb,
|
||||
pub avatar: ImageRef,
|
||||
/// From a blocked contact.
|
||||
pub blocked: bool,
|
||||
pub pinned: bool,
|
||||
pub reactions: Vec<ReactionItem>,
|
||||
pub files: Vec<FileItem>,
|
||||
/// The gateway knows this message: it can be pinned, reacted to and
|
||||
/// made into a topic.
|
||||
pub remote: bool,
|
||||
/// The topic it belongs to, "" outside a topic.
|
||||
pub topic: Arc<str>,
|
||||
/// Highlighted after jumping to it from the pins.
|
||||
pub marked: bool,
|
||||
/// The first web address it links to, "" if none.
|
||||
pub link: Arc<str>,
|
||||
/// The first new message: the "New" divider is above it (never
|
||||
/// `continued`).
|
||||
pub unread_start: bool,
|
||||
}
|
||||
|
||||
/// A pinned message in the pins drawer.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct PinItem {
|
||||
pub line: ChatLine,
|
||||
/// "pinned by Nova · 12:04"
|
||||
pub by: Arc<str>,
|
||||
}
|
||||
|
||||
/// A gateway topic (thread).
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct TopicItem {
|
||||
pub id: i32,
|
||||
pub title: Arc<str>,
|
||||
pub creator: Arc<str>,
|
||||
/// "12 messages · by Nova"
|
||||
pub detail: Arc<str>,
|
||||
/// "Last active 3 min ago", and whether that was within the hour.
|
||||
pub activity: Arc<str>,
|
||||
pub recent: bool,
|
||||
pub archived: bool,
|
||||
}
|
||||
|
||||
/// The server dialog: a bookmark (id -1: a new one) and, from a link, where
|
||||
/// Connect goes.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct BookmarkForm {
|
||||
pub id: i32,
|
||||
pub name: Arc<str>,
|
||||
pub address: Arc<str>,
|
||||
pub nickname: Arc<str>,
|
||||
pub server_password: Arc<str>,
|
||||
/// The server has voice: no Connect.
|
||||
pub connected: bool,
|
||||
/// From a link, not stored with the server: the channel to join (a
|
||||
/// path, or /<id>), its password and a privilege key.
|
||||
pub channel: Arc<str>,
|
||||
pub channel_password: Arc<str>,
|
||||
pub token: Arc<str>,
|
||||
}
|
||||
|
||||
/// A stream on the server, ours first: a stream can be watched from any
|
||||
/// channel. An empty id: a client that streams, but whose stream is still
|
||||
/// being looked up (it started before we joined, or in another channel).
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct StreamItem {
|
||||
pub id: Arc<str>,
|
||||
pub name: Arc<str>,
|
||||
pub streamer: Arc<str>,
|
||||
/// The streamer's channel when it is not ours; empty in ours.
|
||||
pub channel: Arc<str>,
|
||||
/// The streamer's client id (their avatar in the members).
|
||||
pub streamer_id: i32,
|
||||
/// The streamer's avatar, as the members show it: their picture, or
|
||||
/// their initials on their colour (also the card's picture's colour).
|
||||
pub initials: Arc<str>,
|
||||
pub tint: Rgb,
|
||||
pub avatar: ImageRef,
|
||||
/// How many watch it (the gateway's directory; 0 unknown).
|
||||
pub viewers: i32,
|
||||
pub audio: bool,
|
||||
/// "Screen", "Window", "Camera"; and the announced bitrate ("8 Mbit/s").
|
||||
pub kind: Arc<str>,
|
||||
pub bitrate: Arc<str>,
|
||||
/// Shown in the viewer.
|
||||
pub watching: bool,
|
||||
/// Our own stream.
|
||||
pub own: bool,
|
||||
/// Ours from the Stream Studio: its preview is the card's picture.
|
||||
pub studio: bool,
|
||||
}
|
||||
|
||||
/// A viewer of our stream. state: "requested", "connecting" or "connected".
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct ViewerItem {
|
||||
pub client: i32,
|
||||
pub name: Arc<str>,
|
||||
pub state: Arc<str>,
|
||||
pub message: Arc<str>,
|
||||
/// Their avatar picture, empty without one.
|
||||
pub avatar: ImageRef,
|
||||
}
|
||||
|
||||
/// A capture source for the share dialog.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct SourceItem {
|
||||
pub name: Arc<str>,
|
||||
pub detail: Arc<str>,
|
||||
}
|
||||
|
||||
/// A row or form of the bridge (the plain counterpart of the Slint struct `ShareForm`).
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct ShareForm {
|
||||
pub source: i32,
|
||||
pub name: Arc<str>,
|
||||
/// Index into the frame rate choices (15, 30, 60, 120, 144, 240, 320).
|
||||
pub fps_index: i32,
|
||||
/// Frames per second as typed; a choice fills it in. Any number above 0.
|
||||
pub fps: Arc<str>,
|
||||
/// Index into the bitrate choices (Auto, 2.5, 4.6, 8, 10, 20, 40, 60
|
||||
/// Mbit/s).
|
||||
pub bitrate_index: i32,
|
||||
/// Video bitrate in kbit/s as typed; a choice fills it in. Empty with
|
||||
/// Auto: from the size and frame rate shared, up to 60 Mbit/s.
|
||||
pub bitrate: Arc<str>,
|
||||
pub audio: bool,
|
||||
pub auto_accept: bool,
|
||||
}
|
||||
|
||||
/// A row or form of the bridge (the plain counterpart of the Slint struct `AudioForm`).
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct AudioForm {
|
||||
/// 0 = system default, then the devices.
|
||||
pub input_index: i32,
|
||||
pub output_index: i32,
|
||||
/// 0 = push-to-talk, 1 = voice activation, 2 = continuous.
|
||||
pub transmit: i32,
|
||||
/// dBFS.
|
||||
pub vad_threshold: f32,
|
||||
pub echo_cancellation: bool,
|
||||
pub noise_suppression: bool,
|
||||
/// 0 = low ... 3 = very high.
|
||||
pub noise_level: i32,
|
||||
pub auto_gain: bool,
|
||||
/// dB.
|
||||
pub input_gain: f32,
|
||||
/// Percent.
|
||||
pub output_volume: f32,
|
||||
/// Milliseconds.
|
||||
pub playback_buffer: f32,
|
||||
}
|
||||
|
||||
/// Local playback settings of one client. volume in percent.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct ClientAudio {
|
||||
pub id: i32,
|
||||
pub name: Arc<str>,
|
||||
pub volume: f32,
|
||||
pub muted: bool,
|
||||
/// The client streams: the dialog offers to watch it.
|
||||
pub streaming: bool,
|
||||
}
|
||||
|
||||
/// The appearance settings (`ui.*` keys).
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct AppearanceForm {
|
||||
/// "dark", "light" or "system"
|
||||
pub theme: Arc<str>,
|
||||
pub font_scale: f32,
|
||||
/// Pixels.
|
||||
pub narrow_breakpoint: f32,
|
||||
pub image_cache_mb: f32,
|
||||
}
|
||||
|
||||
/// A contact (friend, blocked or neutral) and where they are now.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct ContactItem {
|
||||
pub uid: Arc<str>,
|
||||
pub name: Arc<str>,
|
||||
pub initials: Arc<str>,
|
||||
pub tint: Rgb,
|
||||
pub avatar: ImageRef,
|
||||
/// "friend", "blocked" or "neutral"
|
||||
pub relation: Arc<str>,
|
||||
pub online: bool,
|
||||
pub away: bool,
|
||||
pub streaming: bool,
|
||||
/// What they do: "In Chill Zone", "Streaming", "Away: brb", "Offline".
|
||||
pub status: Arc<str>,
|
||||
/// Where: the server of the first session that sees them, or "Last seen
|
||||
/// 2 h ago on Nightfall Guild".
|
||||
pub place: Arc<str>,
|
||||
/// "12m ago": online since (this run), else when last seen.
|
||||
pub when: Arc<str>,
|
||||
pub note: Arc<str>,
|
||||
/// Local playback in percent.
|
||||
pub volume: f32,
|
||||
pub muted: bool,
|
||||
/// "Contact since 14 Jan 2022".
|
||||
pub since: Arc<str>,
|
||||
/// Every session that sees them: "Nightfall Guild · Chill Zone".
|
||||
pub spots: Vec<Arc<str>>,
|
||||
/// A voice connection sees them: they can be messaged, poked, joined.
|
||||
pub reachable: bool,
|
||||
pub selected: bool,
|
||||
}
|
||||
|
||||
/// A live stream on one of our servers (home page).
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct LiveItem {
|
||||
/// The session (bookmark id) and the stream (directory or stream id).
|
||||
pub session: i32,
|
||||
pub id: Arc<str>,
|
||||
pub title: Arc<str>,
|
||||
pub streamer: Arc<str>,
|
||||
pub initials: Arc<str>,
|
||||
pub tint: Rgb,
|
||||
pub avatar: ImageRef,
|
||||
pub server: Arc<str>,
|
||||
pub channel: Arc<str>,
|
||||
/// 0: unknown.
|
||||
pub viewers: i32,
|
||||
/// "Screen", "Camera", ...
|
||||
pub kind: Arc<str>,
|
||||
/// The server's colour, for the card's picture.
|
||||
pub backdrop: Rgb,
|
||||
/// In our voice channel: it can be watched at once.
|
||||
pub watchable: bool,
|
||||
}
|
||||
|
||||
/// A chat in the recent chats and in the direct messages list.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct ConversationItem {
|
||||
/// Index in Rust's list (what `open-conversation` takes).
|
||||
pub key: i32,
|
||||
/// 0 server chat, 1 channel chat, 2 private chat, 3 offline message.
|
||||
pub kind: i32,
|
||||
pub title: Arc<str>,
|
||||
/// The server's name.
|
||||
pub server: Arc<str>,
|
||||
/// "You: That works!", "Sent a file".
|
||||
pub preview: Arc<str>,
|
||||
/// "11:42", "Yesterday", "Mon", "12 Mar".
|
||||
pub time: Arc<str>,
|
||||
/// "10m ago".
|
||||
pub ago: Arc<str>,
|
||||
pub unread: i32,
|
||||
pub initials: Arc<str>,
|
||||
pub tint: Rgb,
|
||||
pub avatar: ImageRef,
|
||||
pub online: bool,
|
||||
pub selected: bool,
|
||||
}
|
||||
|
||||
/// A notification of the bell.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct NoticeItem {
|
||||
pub key: i32,
|
||||
/// "mention", "poke", "message", "event", "friend"
|
||||
pub kind: Arc<str>,
|
||||
pub title: Arc<str>,
|
||||
pub body: Arc<str>,
|
||||
/// "3 min ago"
|
||||
pub time: Arc<str>,
|
||||
pub unread: bool,
|
||||
pub initials: Arc<str>,
|
||||
pub tint: Rgb,
|
||||
pub avatar: ImageRef,
|
||||
}
|
||||
|
||||
/// A result of the search (Ctrl+K).
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct SearchItem {
|
||||
/// "server", "channel", "person", "contact", "setting"
|
||||
pub kind: Arc<str>,
|
||||
pub title: Arc<str>,
|
||||
pub subtitle: Arc<str>,
|
||||
pub initials: Arc<str>,
|
||||
pub tint: Rgb,
|
||||
pub avatar: ImageRef,
|
||||
/// The first result of a group names it ("Servers", "People", ...).
|
||||
pub header: Arc<str>,
|
||||
}
|
||||
|
||||
/// Something on our servers: an event, a scheduled stream or server news.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct HappeningItem {
|
||||
/// "event", "stream", "news"
|
||||
pub kind: Arc<str>,
|
||||
pub title: Arc<str>,
|
||||
pub subtitle: Arc<str>,
|
||||
/// "Sat 26 Apr · 19:00"
|
||||
pub when: Arc<str>,
|
||||
pub session: i32,
|
||||
pub id: i32,
|
||||
pub live: bool,
|
||||
}
|
||||
|
||||
/// Home's "Continue where you left off": the voice channel we were in last.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct ResumeItem {
|
||||
/// There is one: its server is still a bookmark at the same address.
|
||||
pub shown: bool,
|
||||
pub server_id: i32,
|
||||
pub server: Arc<str>,
|
||||
pub initials: Arc<str>,
|
||||
pub tint: Rgb,
|
||||
pub icon: ImageRef,
|
||||
/// The channel's name as the tree shows it.
|
||||
pub channel: Arc<str>,
|
||||
/// Voice is connected there: the button shows the server; else it
|
||||
/// connects into the channel.
|
||||
pub open: bool,
|
||||
pub connecting: bool,
|
||||
}
|
||||
|
||||
/// A scheduled event of a server's gateway.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct EventItem {
|
||||
pub id: i32,
|
||||
pub title: Arc<str>,
|
||||
pub description: Arc<str>,
|
||||
/// The date block: "SAT", "26", "APR".
|
||||
pub weekday: Arc<str>,
|
||||
pub day: Arc<str>,
|
||||
pub month: Arc<str>,
|
||||
/// "Sat 26 Apr, 19:00 – 21:00"
|
||||
pub when: Arc<str>,
|
||||
/// "Raid Night" or "Server-wide".
|
||||
pub place: Arc<str>,
|
||||
/// A scheduled stream: "Exploring the Lands Between · Elden Ring".
|
||||
pub stream: Arc<str>,
|
||||
pub live: bool,
|
||||
pub going: i32,
|
||||
pub maybe: i32,
|
||||
pub not_going: i32,
|
||||
/// "going", "maybe", "not_going" or "".
|
||||
pub rsvp: Arc<str>,
|
||||
pub creator: Arc<str>,
|
||||
/// We may edit and delete it (ours, or we moderate).
|
||||
pub editable: bool,
|
||||
/// "Starts in 15 min", "Started 5 min ago", "".
|
||||
pub soon: Arc<str>,
|
||||
/// "Nova (going)", ...; filled once the event was opened.
|
||||
pub attendees: Vec<Arc<str>>,
|
||||
pub expanded: bool,
|
||||
}
|
||||
|
||||
/// The event form (create or edit).
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct EventForm {
|
||||
/// -1: a new event.
|
||||
pub id: i32,
|
||||
pub title: Arc<str>,
|
||||
pub description: Arc<str>,
|
||||
/// "2026-10-04 19:00", local time.
|
||||
pub start: Arc<str>,
|
||||
/// Empty: no end.
|
||||
pub end: Arc<str>,
|
||||
/// Index into `event-channels` (0: server-wide).
|
||||
pub channel: i32,
|
||||
pub stream: bool,
|
||||
pub stream_title: Arc<str>,
|
||||
pub game: Arc<str>,
|
||||
}
|
||||
|
||||
/// An offline message to write (mail the server keeps).
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct OfflineForm {
|
||||
/// The peer's unique id and name.
|
||||
pub uid: Arc<str>,
|
||||
pub to: Arc<str>,
|
||||
pub subject: Arc<str>,
|
||||
pub text: Arc<str>,
|
||||
}
|
||||
|
||||
/// The open direct message: who, and what can be done.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct DmPeer {
|
||||
pub open: bool,
|
||||
pub uid: Arc<str>,
|
||||
pub name: Arc<str>,
|
||||
pub initials: Arc<str>,
|
||||
pub tint: Rgb,
|
||||
pub avatar: ImageRef,
|
||||
pub online: bool,
|
||||
/// "Online · Nightfall Guild · Chill Zone", "Offline · last seen 2 h ago".
|
||||
pub status: Arc<str>,
|
||||
pub description: Arc<str>,
|
||||
pub groups: Vec<Arc<str>>,
|
||||
pub note: Arc<str>,
|
||||
pub since: Arc<str>,
|
||||
/// Where they are now, or where they were last seen.
|
||||
pub servers: Vec<Arc<str>>,
|
||||
/// Pictures linked in the conversation that are downloaded, newest
|
||||
/// first (at most six; `media-more` counts the others), and the other
|
||||
/// files: name, "2.4 MB · Today at 11:36", picture.
|
||||
pub media: Vec<ImageRef>,
|
||||
pub media_more: i32,
|
||||
pub files: Vec<FileItem>,
|
||||
pub friend: bool,
|
||||
pub blocked: bool,
|
||||
pub volume: f32,
|
||||
pub muted: bool,
|
||||
/// Messages can be sent now (a voice connection that sees them).
|
||||
pub can_send: bool,
|
||||
/// Why not: "Kairo is offline.", "Connect to Nightfall Guild to send."
|
||||
pub notice: Arc<str>,
|
||||
/// The server keeps offline messages: offer one.
|
||||
pub offline: bool,
|
||||
/// Connect with voice to the server of this conversation.
|
||||
pub can_connect: bool,
|
||||
/// The messages come from the store, without a session: read-only.
|
||||
pub stored: bool,
|
||||
/// An offline message is shown instead of the conversation.
|
||||
pub mail: bool,
|
||||
pub mail_subject: Arc<str>,
|
||||
pub mail_text: Arc<str>,
|
||||
pub mail_time: Arc<str>,
|
||||
}
|
||||
|
||||
/// An identity (Profiles page); never its key.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct IdentityItem {
|
||||
pub id: i32,
|
||||
pub name: Arc<str>,
|
||||
/// Unique ids on TeamSpeak 3 and TeamSpeak 6 servers.
|
||||
pub uid: Arc<str>,
|
||||
pub uid6: Arc<str>,
|
||||
pub level: i32,
|
||||
/// The store's default: servers see us as this one unless a bookmark
|
||||
/// names another.
|
||||
pub default: bool,
|
||||
/// Where it came from: "Made in Voelin", "Imported", "Chosen by you".
|
||||
pub origin: Arc<str>,
|
||||
/// Raising its level: the level aimed at and the best one reached (0: no).
|
||||
pub improving: i32,
|
||||
pub reached: i32,
|
||||
/// The bookmarks that use it.
|
||||
pub used_by: Arc<str>,
|
||||
}
|
||||
|
||||
/// An identity found in another client's files (import).
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct FoundIdentity {
|
||||
pub name: Arc<str>,
|
||||
pub uid: Arc<str>,
|
||||
pub level: i32,
|
||||
pub source: Arc<str>,
|
||||
/// Already in our identities.
|
||||
pub known: bool,
|
||||
pub picked: bool,
|
||||
}
|
||||
|
||||
/// A bookmark and the identity it connects with (Profiles page).
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct BookmarkIdentity {
|
||||
pub id: i32,
|
||||
pub name: Arc<str>,
|
||||
/// Index into `identity-names` (0: the default identity).
|
||||
pub identity: i32,
|
||||
}
|
||||
|
||||
/// Camera, video and stream quality (Voice & Video page).
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct VideoForm {
|
||||
/// Index into `cameras`.
|
||||
pub camera: i32,
|
||||
/// 0 none, 1 blur.
|
||||
pub background: i32,
|
||||
/// "auto", "1280x720", ...
|
||||
pub resolution: Arc<str>,
|
||||
/// `stream.fps` as typed.
|
||||
pub fps: Arc<str>,
|
||||
/// auto, vp8, vp9, h264, av1.
|
||||
pub codec: i32,
|
||||
pub hardware: bool,
|
||||
pub mirror: bool,
|
||||
/// everyone, friends, channel, nobody.
|
||||
pub permissions: i32,
|
||||
/// 0 auto, 1 720p, 2 1080p, 3 1440p, -1 other layers.
|
||||
pub quality: i32,
|
||||
/// kbit/s.
|
||||
pub bitrate: f32,
|
||||
/// The camera preview runs.
|
||||
pub preview: bool,
|
||||
}
|
||||
|
||||
/// A simulcast layer of our stream (Streaming page); numbers as typed.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct LayerItem {
|
||||
/// "1920x1080", or a scale like "0.5".
|
||||
pub size: Arc<str>,
|
||||
/// Frames per second; "" no cap.
|
||||
pub fps: Arc<str>,
|
||||
/// kbit/s.
|
||||
pub bitrate: Arc<str>,
|
||||
pub min_bitrate: Arc<str>,
|
||||
pub max_bitrate: Arc<str>,
|
||||
}
|
||||
|
||||
/// An audio source mixed into our stream.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct AudioSourceItem {
|
||||
/// "desktop", "app", "window", "microphone", "synthetic"
|
||||
pub kind: Arc<str>,
|
||||
pub name: Arc<str>,
|
||||
pub detail: Arc<str>,
|
||||
/// Percent.
|
||||
pub gain: f32,
|
||||
pub muted: bool,
|
||||
}
|
||||
|
||||
/// Stream defaults (Streaming page).
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct StreamingForm {
|
||||
pub fps: Arc<str>,
|
||||
pub bitrate: Arc<str>,
|
||||
/// auto, vp8, vp9, h264, av1.
|
||||
pub codec: i32,
|
||||
/// auto, portal, wlroots, x11.
|
||||
pub capture: i32,
|
||||
pub replay_seconds: Arc<str>,
|
||||
pub replay_memory: Arc<str>,
|
||||
pub recording_dir: Arc<str>,
|
||||
}
|
||||
|
||||
/// Notification kinds: 0 off, 1 in the app, 2 also on the desktop.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct NotifyForm {
|
||||
pub mentions: i32,
|
||||
pub pokes: i32,
|
||||
pub messages: i32,
|
||||
pub events: i32,
|
||||
pub friends: i32,
|
||||
}
|
||||
|
||||
/// Privacy & Safety.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct PrivacyForm {
|
||||
/// 0 hide, 1 show flagged.
|
||||
pub block_mode: i32,
|
||||
/// everyone, friends, nobody.
|
||||
pub messages: i32,
|
||||
pub pokes: i32,
|
||||
}
|
||||
|
||||
/// A server's gateway (Integrations page).
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct GatewayItem {
|
||||
pub session: i32,
|
||||
pub server: Arc<str>,
|
||||
pub url: Arc<str>,
|
||||
/// "connected", "connecting", "off"
|
||||
pub status: Arc<str>,
|
||||
pub features: Vec<Arc<str>>,
|
||||
pub admin: bool,
|
||||
}
|
||||
|
||||
/// A gateway configuration key (gateway administration).
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct ConfigItem {
|
||||
pub key: Arc<str>,
|
||||
/// JSON.
|
||||
pub value: Arc<str>,
|
||||
pub source: Arc<str>,
|
||||
pub description: Arc<str>,
|
||||
pub kind: Arc<str>,
|
||||
pub bootstrap: bool,
|
||||
}
|
||||
|
||||
/// A gateway permission rule.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct PermItem {
|
||||
pub action: Arc<str>,
|
||||
/// "Everyone", "Server groups 6, 7", "Default: server admins".
|
||||
pub rule: Arc<str>,
|
||||
pub source: Arc<str>,
|
||||
pub everyone: bool,
|
||||
pub server_groups: Arc<str>,
|
||||
pub channel_groups: Arc<str>,
|
||||
}
|
||||
|
||||
/// A video encoder backend (Integrations page).
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct EncoderItem {
|
||||
pub name: Arc<str>,
|
||||
pub api: Arc<str>,
|
||||
pub codec: Arc<str>,
|
||||
pub hardware: bool,
|
||||
pub ok: bool,
|
||||
/// Why it does not work, or "used first".
|
||||
pub status: Arc<str>,
|
||||
}
|
||||
|
||||
/// Any registered setting (Advanced page).
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct SettingItem {
|
||||
pub key: Arc<str>,
|
||||
pub doc: Arc<str>,
|
||||
/// JSON.
|
||||
pub value: Arc<str>,
|
||||
/// "set here", "command line", "config file", "default".
|
||||
pub source: Arc<str>,
|
||||
}
|
||||
|
||||
/// A recording or clip of the Stream Studio (Library).
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct RecordingItem {
|
||||
pub name: Arc<str>,
|
||||
/// "12.3 MB · 3 Oct 18:04".
|
||||
pub detail: Arc<str>,
|
||||
pub clip: bool,
|
||||
pub path: Arc<str>,
|
||||
}
|
||||
|
||||
/// Encoders, chat history, cache and logs (Advanced page); numbers as typed.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct AdvancedForm {
|
||||
pub encoder: Arc<str>,
|
||||
pub hardware: bool,
|
||||
/// `stream.decoder_backend`, `stream.hardware_decoding`.
|
||||
pub decoder: Arc<str>,
|
||||
pub hardware_decoding: bool,
|
||||
pub store_history: bool,
|
||||
pub history_page: Arc<str>,
|
||||
pub dedupe_ms: Arc<str>,
|
||||
pub retention_days: Arc<str>,
|
||||
pub cache_mb: Arc<str>,
|
||||
pub fetch_images: bool,
|
||||
pub progress_ms: Arc<str>,
|
||||
/// `ui.image_preview_kb`.
|
||||
pub preview_kb: Arc<str>,
|
||||
pub logs: Arc<str>,
|
||||
pub crash_dir: Arc<str>,
|
||||
}
|
||||
|
||||
/// A row or form of the bridge (the plain counterpart of the Slint struct `AccountForm`).
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct AccountForm {
|
||||
pub nickname: Arc<str>,
|
||||
pub identity: Arc<str>,
|
||||
pub uid: Arc<str>,
|
||||
pub uid6: Arc<str>,
|
||||
pub level: i32,
|
||||
pub server: Arc<str>,
|
||||
}
|
||||
|
||||
/// One emoji of the picker. `text` is what picking it inserts.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct EmojiCell {
|
||||
pub key: Arc<str>,
|
||||
pub name: Arc<str>,
|
||||
pub text: Arc<str>,
|
||||
}
|
||||
|
||||
/// A row or form of the bridge (the plain counterpart of the Slint struct `EmojiRow`).
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct EmojiRow {
|
||||
pub cells: Vec<EmojiCell>,
|
||||
}
|
||||
@@ -6,17 +6,17 @@ use std::borrow::Cow;
|
||||
use std::cell::RefCell;
|
||||
use std::collections::HashMap;
|
||||
use std::path::PathBuf;
|
||||
use std::rc::Rc;
|
||||
|
||||
use slint::{Color, Image, ModelRc, VecModel};
|
||||
use unicode_segmentation::UnicodeSegmentation;
|
||||
use voelin_core::HistoryMessage;
|
||||
use voelin_model::{ChatMessage, ChatTarget, FileRef, Presence};
|
||||
|
||||
use crate::app::{ChatLine, FileItem, ReactionItem, TextBlock, TextRun};
|
||||
use crate::avatar;
|
||||
use crate::bbcode::{self, BlockKind, Doc, Span, Style};
|
||||
use crate::bridge::{ChatLine, FileItem, ReactionItem, TextBlock, TextRun};
|
||||
use crate::color::Rgb;
|
||||
use crate::emoji;
|
||||
use crate::vm::avatar;
|
||||
use crate::vm::bbcode::{self, BlockKind, Doc, Span, Style};
|
||||
use crate::image::ImageRef;
|
||||
|
||||
/// Lines of the same author within this time are grouped (no header).
|
||||
const GROUP_MS: i64 = 5 * 60 * 1000;
|
||||
@@ -29,6 +29,7 @@ pub struct Previous {
|
||||
}
|
||||
|
||||
impl Previous {
|
||||
/// The line `message` is, as the line after it sees it.
|
||||
pub fn of(message: &ChatMessage) -> Self {
|
||||
Self { author: message.author_name.clone(), ts_ms: message.ts_ms }
|
||||
}
|
||||
@@ -40,7 +41,7 @@ pub struct LineCtx<'a> {
|
||||
/// The message's handle in its chat.
|
||||
pub key: i32,
|
||||
/// The author's avatar picture.
|
||||
pub avatar: Image,
|
||||
pub avatar: ImageRef,
|
||||
/// The gateway takes reactions and pins for this chat.
|
||||
pub gateway: bool,
|
||||
/// Highlighted (jumped to from the pins).
|
||||
@@ -50,7 +51,7 @@ pub struct LineCtx<'a> {
|
||||
/// The state of the downloads started from this message, by link index.
|
||||
pub downloads: Vec<(usize, FileItem)>,
|
||||
/// Pictures of the links shown inline, by link index.
|
||||
pub previews: Vec<(usize, Image)>,
|
||||
pub previews: Vec<(usize, ImageRef)>,
|
||||
/// Pictures on the web in the engine's cache, by address: the `[img]`
|
||||
/// pictures here show as picture cards, the others as links (`None`:
|
||||
/// all as links).
|
||||
@@ -137,7 +138,7 @@ pub fn size_text(bytes: u64) -> String {
|
||||
#[derive(Clone, Default)]
|
||||
struct Body {
|
||||
text: String,
|
||||
blocks: ModelRc<TextBlock>,
|
||||
blocks: Vec<TextBlock>,
|
||||
rich: bool,
|
||||
jumbo: bool,
|
||||
link: String,
|
||||
@@ -152,10 +153,9 @@ struct Read {
|
||||
}
|
||||
|
||||
/// What lines of a chat were built from, by message id, kept between
|
||||
/// refreshes: a message whose text, reactions and cards did not change is
|
||||
/// not read again and gets the same models (they compare by pointer), so
|
||||
/// its line compares equal and `list::sync` leaves its row. (Not with an
|
||||
/// empty picture: Slint's empty `Image` equals nothing, not even itself.)
|
||||
/// refreshes: a message whose text did not change is not read again (its
|
||||
/// BBCode parsed, its blocks and runs split), and builds the same line, so
|
||||
/// the list diff leaves its row.
|
||||
#[derive(Default)]
|
||||
pub struct LineCache(RefCell<HashMap<i64, Parts>>);
|
||||
|
||||
@@ -166,8 +166,6 @@ struct Parts {
|
||||
read: Option<Read>,
|
||||
/// The body last built, and which pictures were cards then.
|
||||
body: Option<(Vec<bool>, Body)>,
|
||||
reactions: (Vec<ReactionItem>, ModelRc<ReactionItem>),
|
||||
files: (Vec<FileItem>, ModelRc<FileItem>),
|
||||
}
|
||||
|
||||
impl LineCache {
|
||||
@@ -190,22 +188,6 @@ fn current<'a>(all: &'a mut HashMap<i64, Parts>, id: i64, rev: i64, text: &str)
|
||||
parts
|
||||
}
|
||||
|
||||
/// `rows` as a model: the one in `kept` when they are the same rows.
|
||||
fn model_of<T: Clone + PartialEq + 'static>(
|
||||
rows: Vec<T>,
|
||||
kept: Option<&mut (Vec<T>, ModelRc<T>)>,
|
||||
) -> ModelRc<T> {
|
||||
match kept {
|
||||
Some((old, model)) if *old == rows => model.clone(),
|
||||
Some(kept) => {
|
||||
let model = ModelRc::from(Rc::new(VecModel::from(rows.clone())));
|
||||
*kept = (rows, model.clone());
|
||||
model
|
||||
}
|
||||
None => ModelRc::from(Rc::new(VecModel::from(rows))),
|
||||
}
|
||||
}
|
||||
|
||||
/// A link to a channel's file, which the chat shows as a card.
|
||||
fn is_file(address: &str) -> bool {
|
||||
FileRef::parse(address).is_some()
|
||||
@@ -236,11 +218,13 @@ pub fn web_pictures(text: &str) -> Vec<String> {
|
||||
|
||||
/// The colours of a span: the author's made readable on the dark and the
|
||||
/// light theme, or transparent for the text's own.
|
||||
fn inks(color: Option<[u8; 3]>) -> (Color, Color) {
|
||||
let rgb = |[r, g, b]: [u8; 3]| Color::from_rgb_u8(r, g, b);
|
||||
fn inks(color: Option<[u8; 3]>) -> (Option<Rgb>, Option<Rgb>) {
|
||||
match color {
|
||||
Some(c) => (rgb(bbcode::readable(c, true)), rgb(bbcode::readable(c, false))),
|
||||
None => (Color::default(), Color::default()),
|
||||
Some(c) => (
|
||||
Some(Rgb::from(bbcode::readable(c, true))),
|
||||
Some(Rgb::from(bbcode::readable(c, false))),
|
||||
),
|
||||
None => (None, None),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -251,7 +235,7 @@ fn run(
|
||||
emoji: Option<String>,
|
||||
style: &Style,
|
||||
masked: bool,
|
||||
inks: (Color, Color),
|
||||
inks: (Option<Rgb>, Option<Rgb>),
|
||||
) -> TextRun {
|
||||
TextRun {
|
||||
text: text.into(),
|
||||
@@ -356,11 +340,7 @@ fn blocks_of(doc: &Doc) -> Option<(Vec<TextBlock>, bool)> {
|
||||
if count > bbcode::MAX_RUNS {
|
||||
return None;
|
||||
}
|
||||
blocks.push(TextBlock {
|
||||
runs: ModelRc::from(Rc::new(VecModel::from(runs))),
|
||||
kind,
|
||||
caption: caption.into(),
|
||||
});
|
||||
blocks.push(TextBlock { runs, kind, caption: caption.into() });
|
||||
}
|
||||
}
|
||||
Some((blocks, any_emoji))
|
||||
@@ -388,19 +368,13 @@ fn body_of(doc: &Doc, cards: &[bool]) -> Body {
|
||||
let rich = !doc.is_plain() || words.iter().any(|w| w.emoji.is_some());
|
||||
// Past the runs a line can have: its plain text.
|
||||
match rich.then(|| blocks_of(&doc)).flatten() {
|
||||
Some((blocks, _)) => Body {
|
||||
text,
|
||||
blocks: ModelRc::from(Rc::new(VecModel::from(blocks))),
|
||||
rich: true,
|
||||
jumbo,
|
||||
link,
|
||||
},
|
||||
None => Body { text, blocks: ModelRc::default(), rich: false, jumbo, link },
|
||||
Some((blocks, _)) => Body { text, blocks, rich: true, jumbo, link },
|
||||
None => Body { text, blocks: Vec::new(), rich: false, jumbo, link },
|
||||
}
|
||||
}
|
||||
|
||||
/// The picture at `url`, if the engine has it and it can be shown.
|
||||
fn picture(pictures: Option<&HashMap<String, PathBuf>>, url: &str) -> Option<Image> {
|
||||
fn picture(pictures: Option<&HashMap<String, PathBuf>>, url: &str) -> Option<ImageRef> {
|
||||
let image = avatar::image(pictures?.get(url));
|
||||
(image.size().width > 0).then_some(image)
|
||||
}
|
||||
@@ -417,7 +391,7 @@ pub fn tab_title(presence: &Presence, target: &ChatTarget, peer: &str) -> String
|
||||
match target {
|
||||
ChatTarget::Channel(cid) => presence.channels.get(cid).map_or_else(
|
||||
|| format!("Channel {cid}"),
|
||||
|c| crate::vm::tree::channel_title(c).0.to_owned(),
|
||||
|c| crate::tree::channel_title(c).0.to_owned(),
|
||||
),
|
||||
ChatTarget::Private(_) => format!("@{peer}"),
|
||||
ChatTarget::Server => "Server".into(),
|
||||
@@ -469,7 +443,7 @@ pub fn preview(message: &ChatMessage) -> (String, String) {
|
||||
std::iter::once(read.doc.one_line()).chain(names).collect::<Vec<_>>().join(" ")
|
||||
};
|
||||
// A one-line text cannot show emoji (they are pictures): left out.
|
||||
let mut text = crate::vm::social::without_emoji(&text);
|
||||
let mut text = crate::social::without_emoji(&text);
|
||||
if text.is_empty() {
|
||||
text = "sent an emoji".into();
|
||||
}
|
||||
@@ -560,12 +534,11 @@ fn line_of(
|
||||
&& previous.is_some_and(|p| {
|
||||
p.author == message.author_name && (0..GROUP_MS).contains(&(message.ts_ms - p.ts_ms))
|
||||
});
|
||||
let cached = parts.is_some();
|
||||
let mut own = Parts::default();
|
||||
let parts = parts.unwrap_or(&mut own);
|
||||
let read = parts.read.get_or_insert_with(|| read(message));
|
||||
// Pictures on the web that are here are cards, after the files'.
|
||||
let pictures: Vec<Option<Image>> =
|
||||
let pictures: Vec<Option<ImageRef>> =
|
||||
read.images.iter().map(|url| picture(ctx.pictures, url)).collect();
|
||||
let shown: Vec<bool> = pictures.iter().map(Option::is_some).collect();
|
||||
let body = match &parts.body {
|
||||
@@ -612,8 +585,6 @@ fn line_of(
|
||||
});
|
||||
}
|
||||
}
|
||||
let files = model_of(cards, cached.then_some(&mut parts.files));
|
||||
let reactions = model_of(reactions, cached.then_some(&mut parts.reactions));
|
||||
ChatLine {
|
||||
key: ctx.key,
|
||||
author: message.author_name.clone().into(),
|
||||
@@ -629,7 +600,7 @@ fn line_of(
|
||||
blocked: message.blocked,
|
||||
pinned: false,
|
||||
reactions,
|
||||
files,
|
||||
files: cards,
|
||||
remote: false,
|
||||
topic: ctx.topic.clone().into(),
|
||||
marked: ctx.marked,
|
||||
@@ -645,6 +616,7 @@ pub fn picture_link(message: &ChatMessage, index: usize) -> Option<String> {
|
||||
index.checked_sub(read.files.len()).and_then(|i| read.images.into_iter().nth(i))
|
||||
}
|
||||
|
||||
/// Whether a file name is a picture's, by its extension.
|
||||
pub fn is_picture(name: &str) -> bool {
|
||||
let lower = name.to_ascii_lowercase();
|
||||
[".png", ".jpg", ".jpeg", ".gif", ".webp", ".bmp", ".svg"].iter().any(|e| lower.ends_with(e))
|
||||
@@ -652,7 +624,7 @@ pub fn is_picture(name: &str) -> bool {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use slint::Model;
|
||||
use crate::image::ImageSource;
|
||||
use voelin_core::HistoryMessage;
|
||||
use voelin_gateway_proto::ReactionCount;
|
||||
use voelin_store::MessageSource;
|
||||
@@ -690,7 +662,7 @@ mod tests {
|
||||
let first = message("Alice", "hi", 1_000_000);
|
||||
let a = line(&first, None);
|
||||
assert!(!a.continued);
|
||||
assert_eq!(a.initials, "AL");
|
||||
assert_eq!(&*a.initials, "AL");
|
||||
let prev = Previous::of(&first);
|
||||
assert!(line(&message("Alice", "again", 1_060_000), Some(&prev)).continued);
|
||||
assert!(!line(&message("Bob", "me", 1_060_000), Some(&prev)).continued);
|
||||
@@ -744,27 +716,27 @@ mod tests {
|
||||
|
||||
/// The runs of block `i` of a line, as (text, emoji).
|
||||
fn runs(line: &ChatLine, i: usize) -> Vec<TextRun> {
|
||||
line.blocks.row_data(i).unwrap().runs.iter().collect()
|
||||
line.blocks[i].runs.clone()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn emoji_runs() {
|
||||
let plain = line(&message("A", "no emoji here\nnor here", 0), None);
|
||||
assert!(!plain.rich && plain.blocks.row_count() == 0);
|
||||
assert_eq!(plain.text, "no emoji here\nnor here");
|
||||
assert!(!plain.rich && plain.blocks.is_empty());
|
||||
assert_eq!(&*plain.text, "no emoji here\nnor here");
|
||||
let rich = line(&message("A", "gg 🎉", 0), None);
|
||||
assert!(rich.rich && !rich.jumbo);
|
||||
assert_eq!(rich.blocks.row_count(), 1);
|
||||
assert_eq!(rich.blocks.len(), 1);
|
||||
let r = runs(&rich, 0);
|
||||
assert_eq!((r.len(), r[0].text.as_str(), r[1].emoji.as_str()), (2, "gg ", "1f389"));
|
||||
assert_eq!((r.len(), r[0].text.as_ref(), r[1].emoji.as_ref()), (2, "gg ", "1f389"));
|
||||
assert!(line(&message("A", "🎉", 0), None).jumbo);
|
||||
// Formatting around it: still large.
|
||||
let jumbo = line(&message("A", "[b]🎉[/b]", 0), None);
|
||||
assert!(jumbo.rich && jumbo.jumbo);
|
||||
// Lines stay lines with emoji (they were run together).
|
||||
let lines = line(&message("A", "first 🎉\nsecond", 0), None);
|
||||
assert_eq!(lines.blocks.row_count(), 2);
|
||||
assert_eq!(lines.text, "first 🎉\nsecond");
|
||||
assert_eq!(lines.blocks.len(), 2);
|
||||
assert_eq!(&*lines.text, "first 🎉\nsecond");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -775,10 +747,10 @@ mod tests {
|
||||
let line = line(&message("A", text, 0), None);
|
||||
assert!(line.rich && !line.jumbo);
|
||||
assert_eq!(
|
||||
line.text,
|
||||
&*line.text,
|
||||
"Raid at 8, see https://x.org/raid\n> Nova: bring elixirs\n• one\n• two\n---\na\n\nb"
|
||||
);
|
||||
assert_eq!(line.link, "https://x.org/raid");
|
||||
assert_eq!(&*line.link, "https://x.org/raid");
|
||||
let kinds: Vec<(i32, String)> =
|
||||
line.blocks.iter().map(|b| (b.kind, b.caption.to_string())).collect();
|
||||
let kind = |k: i32| (k, String::new());
|
||||
@@ -787,15 +759,15 @@ mod tests {
|
||||
[kind(0), (1, "Nova".into()), kind(3), kind(3), kind(4), kind(2), kind(2), kind(2)]
|
||||
);
|
||||
let first = runs(&line, 0);
|
||||
assert!(first[0].bold && first[0].text == "Raid");
|
||||
assert!(first[0].bold && &*first[0].text == "Raid");
|
||||
let eight = first.iter().find(|r| r.text.starts_with('8')).unwrap();
|
||||
// The author's red, readable on both themes.
|
||||
assert!(eight.ink_dark.alpha() == 255 && eight.ink_light.alpha() == 255);
|
||||
assert!(eight.ink_dark.red() > eight.ink_dark.green());
|
||||
assert_eq!(first[0].ink_dark.alpha(), 0, "the text's own colour");
|
||||
let (dark, light) = (eight.ink_dark.unwrap(), eight.ink_light.unwrap());
|
||||
assert!(dark.r() > dark.g() && light.r() > light.g());
|
||||
assert_eq!(first[0].ink_dark, None, "the text's own colour");
|
||||
let address = first.iter().find(|r| !r.link.is_empty()).unwrap();
|
||||
assert_eq!(
|
||||
(address.text.as_str(), address.link.as_str()),
|
||||
(address.text.as_ref(), address.link.as_ref()),
|
||||
("https://x.org/raid", "https://x.org/raid")
|
||||
);
|
||||
assert!(!address.masked, "its own address");
|
||||
@@ -807,10 +779,10 @@ mod tests {
|
||||
// Inline code: one run.
|
||||
let inline = super::line(&message("A", "run [code]/pull 10[/code]", 0), None);
|
||||
let r = runs(&inline, 0);
|
||||
assert!(r[1].code && r[1].text == "/pull 10");
|
||||
assert!(r[1].code && &*r[1].text == "/pull 10");
|
||||
// Not formatting: plain.
|
||||
let relayed = super::line(&message("A", "[Nova] hi [1]", 0), None);
|
||||
assert!(!relayed.rich && relayed.text == "[Nova] hi [1]" && relayed.link.is_empty());
|
||||
assert!(!relayed.rich && &*relayed.text == "[Nova] hi [1]" && relayed.link.is_empty());
|
||||
}
|
||||
|
||||
/// A link whose text is not its address asks before it opens: each of
|
||||
@@ -916,15 +888,15 @@ mod tests {
|
||||
let url = format!("https://x.org/{}", "a".repeat(40));
|
||||
let line = line(&message("A", &format!("see {url}"), 0), None);
|
||||
let r = runs(&line, 0);
|
||||
let pieces: Vec<&str> = r[1..].iter().map(|r| r.text.as_str()).collect();
|
||||
let pieces: Vec<&str> = r[1..].iter().map(|r| r.text.as_ref()).collect();
|
||||
assert_eq!(pieces.concat(), url);
|
||||
assert!(pieces.len() == 3 && pieces.iter().all(|p| p.chars().count() <= LONG_WORD));
|
||||
assert!(r[1..].iter().all(|r| r.link == url.as_str()));
|
||||
assert!(r[1..].iter().all(|r| &*r.link == url.as_str()));
|
||||
let code = "cargo build --release --locked -j 1";
|
||||
let line = super::line(&message("A", &format!("[code]{code}[/code]"), 0), None);
|
||||
let r = runs(&line, 0);
|
||||
assert!(r.len() > 1 && r.iter().all(|r| r.code));
|
||||
assert_eq!(r.iter().map(|r| r.text.as_str()).collect::<String>(), code);
|
||||
assert_eq!(r.iter().map(|r| r.text.as_ref()).collect::<String>(), code);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -933,9 +905,9 @@ mod tests {
|
||||
let text = format!("loot [img]{url}[/img]");
|
||||
// Not here (or not fetched): the address, as a link.
|
||||
let link = line(&message("A", &text, 0), None);
|
||||
assert_eq!(link.files.row_count(), 0);
|
||||
assert_eq!(link.files.len(), 0);
|
||||
let r = runs(&link, 0);
|
||||
assert_eq!((r[1].text.as_str(), r[1].link.as_str()), (url, url));
|
||||
assert_eq!((r[1].text.as_ref(), r[1].link.as_ref()), (url, url));
|
||||
// Here: a picture card after the files, and no address.
|
||||
let dir = std::env::temp_dir().join(format!("voelin-chat-picture-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
@@ -951,10 +923,10 @@ mod tests {
|
||||
let stored = stored(message("A", &format!("{text} [URL={file}]plan.pdf[/URL]"), 0));
|
||||
let ctx = LineCtx { pictures: Some(&pictures), ..Default::default() };
|
||||
let shown = history_line(&stored, None, &ctx);
|
||||
assert_eq!(shown.text, "loot");
|
||||
assert_eq!(shown.files.row_count(), 2);
|
||||
let card = shown.files.row_data(1).unwrap();
|
||||
assert_eq!((card.name.as_str(), card.index, card.preview.size().width), ("loot.png", 1, 4));
|
||||
assert_eq!(&*shown.text, "loot");
|
||||
assert_eq!(shown.files.len(), 2);
|
||||
let card = shown.files[1].clone();
|
||||
assert_eq!((card.name.as_ref(), card.index, card.preview.size().width), ("loot.png", 1, 4));
|
||||
assert_eq!(picture_link(&stored.message, 1).as_deref(), Some(url));
|
||||
assert_eq!(picture_link(&stored.message, 0), None);
|
||||
assert_eq!(web_pictures(&text), [url]);
|
||||
@@ -962,20 +934,18 @@ mod tests {
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
/// A line built again from an unchanged message is equal (its models
|
||||
/// are the same), so `list::sync` leaves its row; a change builds anew.
|
||||
/// A line built again from an unchanged message is equal (so the list diff
|
||||
/// leaves its row), with the cache or without; a change builds anew.
|
||||
#[test]
|
||||
fn unchanged_lines_compare_equal() {
|
||||
let cache = LineCache::default();
|
||||
// An avatar: an empty picture is never equal.
|
||||
let avatar = Image::from_rgba8(slint::SharedPixelBuffer::new(1, 1));
|
||||
let avatar = ImageSource::rgba(1, 1, vec![0u8; 4]);
|
||||
let ctx = LineCtx { key: 3, avatar, cache: Some(&cache), ..Default::default() };
|
||||
let mut stored = stored(message("A", "[b]hi[/b] 🎉", 0));
|
||||
let first = history_line(&stored, None, &ctx);
|
||||
assert!(first == history_line(&stored, None, &ctx));
|
||||
// Without the cache, models are new each time.
|
||||
let plain = LineCtx { key: 3, avatar: ctx.avatar.clone(), ..Default::default() };
|
||||
assert!(history_line(&stored, None, &plain) != history_line(&stored, None, &plain));
|
||||
assert!(history_line(&stored, None, &plain) == first);
|
||||
stored.reactions[0].count = 3;
|
||||
let reacted = history_line(&stored, None, &ctx);
|
||||
assert!(reacted != first && reacted.blocks == first.blocks);
|
||||
@@ -983,7 +953,7 @@ mod tests {
|
||||
stored.rev = 2;
|
||||
let edited = history_line(&stored, None, &ctx);
|
||||
assert!(edited.blocks != first.blocks);
|
||||
assert_eq!(edited.text, "edited");
|
||||
assert_eq!(&*edited.text, "edited");
|
||||
cache.keep([], 0);
|
||||
assert_eq!(cache.0.borrow().len(), 1, "few: kept");
|
||||
}
|
||||
@@ -994,9 +964,9 @@ mod tests {
|
||||
let ctx = LineCtx { key: -1, cache: Some(&cache), ..Default::default() };
|
||||
let welcome =
|
||||
server_line("Nightfall", "Welcome to [b]Nightfall[/b]!", i64::MIN, false, &ctx);
|
||||
assert_eq!((welcome.author.as_str(), welcome.time.as_str()), ("Nightfall", ""));
|
||||
assert_eq!((welcome.author.as_ref(), welcome.time.as_ref()), ("Nightfall", ""));
|
||||
assert!(welcome.rich && !welcome.continued && !welcome.remote && welcome.key == -1);
|
||||
assert_eq!(welcome.text, "Welcome to Nightfall!");
|
||||
assert_eq!(&*welcome.text, "Welcome to Nightfall!");
|
||||
assert!(server_line("Nightfall", "News", i64::MIN + 1, true, &ctx).continued);
|
||||
}
|
||||
|
||||
@@ -1005,9 +975,9 @@ mod tests {
|
||||
let ctx = LineCtx { key: 4, gateway: true, ..Default::default() };
|
||||
let line = history_line(&stored(message("A", "hi", 0)), None, &ctx);
|
||||
assert!(line.pinned && line.remote && line.key == 4);
|
||||
assert_eq!(line.reactions.row_count(), 1);
|
||||
let r = line.reactions.row_data(0).unwrap();
|
||||
assert_eq!((r.key.as_str(), r.count, r.me), ("1f389", 2, true));
|
||||
assert_eq!(line.reactions.len(), 1);
|
||||
let r = line.reactions[0].clone();
|
||||
assert_eq!((r.key.as_ref(), r.count, r.me), ("1f389", 2, true));
|
||||
// Without a gateway nothing can be pinned or reacted to.
|
||||
let plain = history_line(&stored(message("A", "hi", 0)), None, &LineCtx::default());
|
||||
assert!(!plain.remote);
|
||||
@@ -1022,10 +992,10 @@ mod tests {
|
||||
format!("here you go {url} 🎉"),
|
||||
] {
|
||||
let line = line(&message("A", &text, 0), None);
|
||||
assert_eq!(line.files.row_count(), 1);
|
||||
let file = line.files.row_data(0).unwrap();
|
||||
assert_eq!((file.name.as_str(), file.detail.as_str()), ("plan.pdf", "2.0 kB"));
|
||||
assert_eq!(line.text, "here you go 🎉");
|
||||
assert_eq!(line.files.len(), 1);
|
||||
let file = line.files[0].clone();
|
||||
assert_eq!((file.name.as_ref(), file.detail.as_ref()), ("plan.pdf", "2.0 kB"));
|
||||
assert_eq!(&*line.text, "here you go 🎉");
|
||||
assert!(line.rich);
|
||||
}
|
||||
// Only the link: no text.
|
||||
@@ -0,0 +1,55 @@
|
||||
//! Colours without a toolkit.
|
||||
|
||||
/// An opaque colour as `0xrrggbb`. Where "no colour" means something (a
|
||||
/// text's own colour), the field is an `Option<Rgb>`.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
|
||||
pub struct Rgb(pub u32);
|
||||
|
||||
impl Rgb {
|
||||
/// The colour with these channels.
|
||||
pub const fn new(r: u8, g: u8, b: u8) -> Self {
|
||||
Self((r as u32) << 16 | (g as u32) << 8 | b as u32)
|
||||
}
|
||||
|
||||
/// The red channel.
|
||||
pub const fn r(self) -> u8 {
|
||||
(self.0 >> 16) as u8
|
||||
}
|
||||
|
||||
/// The green channel.
|
||||
pub const fn g(self) -> u8 {
|
||||
(self.0 >> 8) as u8
|
||||
}
|
||||
|
||||
/// The blue channel.
|
||||
pub const fn b(self) -> u8 {
|
||||
self.0 as u8
|
||||
}
|
||||
}
|
||||
|
||||
impl From<u32> for Rgb {
|
||||
/// `0xrrggbb`; the top byte is ignored.
|
||||
fn from(rgb: u32) -> Self {
|
||||
Self(rgb & 0x00ff_ffff)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<[u8; 3]> for Rgb {
|
||||
fn from([r, g, b]: [u8; 3]) -> Self {
|
||||
Self::new(r, g, b)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn channels() {
|
||||
let c = Rgb::from(0x2d6bff);
|
||||
assert_eq!((c.r(), c.g(), c.b()), (0x2d, 0x6b, 0xff));
|
||||
assert_eq!(Rgb::new(0x2d, 0x6b, 0xff), c);
|
||||
assert_eq!(Rgb::from([1, 2, 3]), Rgb(0x010203));
|
||||
assert_eq!(Rgb::from(0xff12_3456), Rgb(0x123456));
|
||||
}
|
||||
}
|
||||
@@ -119,12 +119,7 @@ impl Archive {
|
||||
.map(|i| &self.entries[i])
|
||||
}
|
||||
|
||||
/// Number of emoji in the archive.
|
||||
#[cfg(test)]
|
||||
pub fn len(&self) -> usize {
|
||||
self.entries.len()
|
||||
}
|
||||
|
||||
/// The archive has an emoji for this key (code points joined by `-`).
|
||||
pub fn contains(&self, key: &str) -> bool {
|
||||
self.find(key).is_some()
|
||||
}
|
||||
@@ -350,7 +345,7 @@ mod tests {
|
||||
#[test]
|
||||
fn archive_opens() {
|
||||
let a = archive();
|
||||
assert!(a.len() > 3000);
|
||||
assert!(a.entries.len() > 3000);
|
||||
assert!(a.contains("1f600"));
|
||||
assert!(!a.contains("zzz"));
|
||||
assert_eq!(a.name("1f600"), Some("grinning face"));
|
||||
File renamed without changes.
@@ -0,0 +1,308 @@
|
||||
//! Pictures without a toolkit: where a picture comes from, and how large it
|
||||
//! is. A front end turns an [`ImageRef`] into its own image type (Slint's
|
||||
//! `Image` through its decoded-picture cache, GPUI's `img()`).
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::fmt;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::SystemTime;
|
||||
|
||||
/// A picture: shared, cheap to clone, compared by what it is made of.
|
||||
pub type ImageRef = Arc<ImageSource>;
|
||||
|
||||
/// Where a picture comes from.
|
||||
#[derive(Clone, Default, PartialEq, Eq)]
|
||||
pub enum ImageSource {
|
||||
/// No picture.
|
||||
#[default]
|
||||
None,
|
||||
/// A file of the engine's picture cache (`avatars/<md5>`, `icons/<id>`,
|
||||
/// banners): PNG, JPEG, GIF, WebP, BMP, ICO or SVG, told by content, not
|
||||
/// by name. The engine writes a picture that arrives again into the same
|
||||
/// file, so the reference carries the file's [`Stamp`]: a changed file is
|
||||
/// another picture, and a list that shows it redraws the row.
|
||||
File {
|
||||
/// Where the file is.
|
||||
path: PathBuf,
|
||||
/// What the file was when the reference was made.
|
||||
stamp: Stamp,
|
||||
},
|
||||
/// Decoded pixels, 4 bytes per pixel in the order red, green, blue, alpha.
|
||||
Rgba {
|
||||
/// Width in pixels.
|
||||
w: u32,
|
||||
/// Height in pixels.
|
||||
h: u32,
|
||||
/// `w * h * 4` bytes.
|
||||
bytes: Arc<[u8]>,
|
||||
},
|
||||
/// An SVG document.
|
||||
Svg(Arc<[u8]>),
|
||||
/// A picture file held in memory (a chat picture downloaded for its
|
||||
/// preview): the file's bytes, and a key the front end may keep its
|
||||
/// decoded picture under.
|
||||
Memory {
|
||||
/// Names the picture, for caches.
|
||||
key: Arc<str>,
|
||||
/// The file's bytes.
|
||||
bytes: Arc<[u8]>,
|
||||
},
|
||||
}
|
||||
|
||||
impl fmt::Debug for ImageSource {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::None => f.write_str("None"),
|
||||
Self::File { path, .. } => f.debug_tuple("File").field(path).finish(),
|
||||
Self::Rgba { w, h, .. } => write!(f, "Rgba({w}x{h})"),
|
||||
Self::Svg(bytes) => write!(f, "Svg({} bytes)", bytes.len()),
|
||||
Self::Memory { key, bytes } => write!(f, "Memory({key}, {} bytes)", bytes.len()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What identifies a file's content without reading it: its length and the
|
||||
/// time it was last written. Both zero for a file that is missing.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub struct Stamp {
|
||||
len: u64,
|
||||
modified: Option<SystemTime>,
|
||||
}
|
||||
|
||||
impl Stamp {
|
||||
/// The stamp of the file at `path`.
|
||||
pub fn of(path: &Path) -> Self {
|
||||
std::fs::metadata(path)
|
||||
.map(|meta| Self { len: meta.len(), modified: meta.modified().ok() })
|
||||
.unwrap_or_default()
|
||||
}
|
||||
}
|
||||
|
||||
/// A picture's size in pixels.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub struct Size {
|
||||
/// Width, 0 for no picture.
|
||||
pub width: u32,
|
||||
/// Height, 0 for no picture.
|
||||
pub height: u32,
|
||||
}
|
||||
|
||||
impl ImageSource {
|
||||
/// A reference to no picture.
|
||||
pub fn none() -> ImageRef {
|
||||
ImageRef::default()
|
||||
}
|
||||
|
||||
/// A reference to a file of the picture cache, as the file is now.
|
||||
pub fn file(path: impl Into<PathBuf>) -> ImageRef {
|
||||
let path = path.into();
|
||||
let stamp = Stamp::of(&path);
|
||||
Arc::new(Self::File { path, stamp })
|
||||
}
|
||||
|
||||
/// A reference to decoded pixels (`bytes`: `w * h * 4`, red, green, blue,
|
||||
/// alpha); no picture if the length does not fit.
|
||||
pub fn rgba(w: u32, h: u32, bytes: impl Into<Arc<[u8]>>) -> ImageRef {
|
||||
let bytes = bytes.into();
|
||||
if bytes.len() as u64 == u64::from(w) * u64::from(h) * 4 {
|
||||
Arc::new(Self::Rgba { w, h, bytes })
|
||||
} else {
|
||||
Self::none()
|
||||
}
|
||||
}
|
||||
|
||||
/// The size the picture shows with; 0 by 0 when there is none or it can
|
||||
/// not be shown: a file that is missing, is not a picture, or is too
|
||||
/// large to decode (a front end drops those, as it would show nothing).
|
||||
/// A file's size is read from its header, once while it stays as it is;
|
||||
/// a vector picture has none of its own: its stated width and height,
|
||||
/// else 1 by 1.
|
||||
pub fn size(&self) -> Size {
|
||||
match self {
|
||||
Self::None => Size::default(),
|
||||
Self::File { path, stamp } => file_size(path, *stamp),
|
||||
Self::Rgba { w, h, .. } => Size { width: *w, height: *h },
|
||||
Self::Svg(bytes) => svg_size(bytes),
|
||||
Self::Memory { bytes, .. } => bytes_size(bytes),
|
||||
}
|
||||
}
|
||||
|
||||
/// There is no picture, or it can not be shown ([`Self::size`]).
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.size().width == 0
|
||||
}
|
||||
}
|
||||
|
||||
/// A picture with more pixels than this (as RGBA bytes) is not decoded.
|
||||
const MAX_DECODED_BYTES: u64 = 128 << 20;
|
||||
|
||||
fn checked(width: u32, height: u32) -> Size {
|
||||
if width == 0 || height == 0 || u64::from(width) * u64::from(height) * 4 > MAX_DECODED_BYTES {
|
||||
Size::default()
|
||||
} else {
|
||||
Size { width, height }
|
||||
}
|
||||
}
|
||||
|
||||
/// The size of a picture file's bytes, told by content.
|
||||
fn bytes_size(bytes: &[u8]) -> Size {
|
||||
let bytes = bytes.strip_prefix(b"\xef\xbb\xbf").unwrap_or(bytes);
|
||||
let Ok(reader) = image::ImageReader::new(std::io::Cursor::new(bytes)).with_guessed_format()
|
||||
else {
|
||||
return Size::default();
|
||||
};
|
||||
if reader.format().is_none() {
|
||||
return if voelin_core::is_svg(bytes) { svg_size(bytes) } else { Size::default() };
|
||||
}
|
||||
reader.into_dimensions().map_or_else(|_| Size::default(), |(w, h)| checked(w, h))
|
||||
}
|
||||
|
||||
/// The number at the start of an attribute's value ("48", "48px", "4.5em").
|
||||
fn number(value: &str) -> Option<u32> {
|
||||
let end = value.find(|c: char| !c.is_ascii_digit() && c != '.').unwrap_or(value.len());
|
||||
value[..end].parse::<f32>().ok().filter(|v| *v >= 1.0).map(|v| v as u32)
|
||||
}
|
||||
|
||||
/// The value of `name="…"` in the root tag of an SVG.
|
||||
fn attribute<'a>(tag: &'a str, name: &str) -> Option<&'a str> {
|
||||
let mut rest = tag;
|
||||
while let Some(at) = rest.find(name) {
|
||||
let before = rest[..at].chars().next_back();
|
||||
let after = &rest[at + name.len()..];
|
||||
let after = after.trim_start();
|
||||
if before.is_none_or(char::is_whitespace)
|
||||
&& let Some(value) = after.strip_prefix('=')
|
||||
{
|
||||
let value = value.trim_start();
|
||||
let quote = value.chars().next().filter(|q| matches!(q, '"' | '\''))?;
|
||||
return value[1..].split(quote).next();
|
||||
}
|
||||
rest = &rest[at + name.len()..];
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn svg_size(bytes: &[u8]) -> Size {
|
||||
let text = String::from_utf8_lossy(bytes);
|
||||
let Some(start) = text.find("<svg") else { return Size { width: 1, height: 1 } };
|
||||
let tag = &text[start..];
|
||||
let tag = &tag[..tag.find('>').unwrap_or(tag.len())];
|
||||
let stated =
|
||||
attribute(tag, "width").and_then(number).zip(attribute(tag, "height").and_then(number));
|
||||
let boxed = || {
|
||||
let mut parts = attribute(tag, "viewBox")?.split([' ', ',']).filter(|p| !p.is_empty());
|
||||
let (_, _, w, h) = (parts.next()?, parts.next()?, parts.next()?, parts.next()?);
|
||||
number(w).zip(number(h))
|
||||
};
|
||||
let (width, height) = stated.or_else(boxed).unwrap_or((1, 1));
|
||||
checked(width, height)
|
||||
}
|
||||
|
||||
/// What a probe of a file found, and what the file was then.
|
||||
type Probe = (Stamp, Size);
|
||||
|
||||
/// Probed files, so a picture shown in many rows is read once; entries are
|
||||
/// checked against the file's length and time before use.
|
||||
static PROBES: Mutex<Option<HashMap<PathBuf, Probe>>> = Mutex::new(None);
|
||||
|
||||
/// Probes kept at most; the picture cache is far smaller than this.
|
||||
const MAX_PROBES: usize = 4096;
|
||||
|
||||
fn file_size(path: &Path, stamp: Stamp) -> Size {
|
||||
if stamp == Stamp::default() {
|
||||
return Size::default();
|
||||
}
|
||||
let mut guard = PROBES.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let probes = guard.get_or_insert_with(HashMap::new);
|
||||
if let Some((was, size)) = probes.get(path)
|
||||
&& *was == stamp
|
||||
{
|
||||
return *size;
|
||||
}
|
||||
// The file is read with the lock held; probes are short and rare.
|
||||
let size = std::fs::read(path).map_or_else(|_| Size::default(), |bytes| bytes_size(&bytes));
|
||||
if probes.len() >= MAX_PROBES {
|
||||
probes.clear();
|
||||
}
|
||||
probes.insert(path.to_owned(), (stamp, size));
|
||||
size
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// A PNG of `width` by `height` pixels.
|
||||
pub(crate) fn png(width: u32, height: u32) -> Vec<u8> {
|
||||
let mut bytes = Vec::new();
|
||||
let mut encoder = ::png::Encoder::new(&mut bytes, width, height);
|
||||
encoder.set_color(::png::ColorType::Rgba);
|
||||
encoder.set_depth(::png::BitDepth::Eight);
|
||||
let pixels = vec![200; width as usize * height as usize * 4];
|
||||
encoder.write_header().unwrap().write_image_data(&pixels).unwrap();
|
||||
bytes
|
||||
}
|
||||
|
||||
fn temp(name: &str) -> PathBuf {
|
||||
let dir = std::env::temp_dir().join(format!("voelin-ui-vm-{name}-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
dir
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pixels_and_nothing() {
|
||||
assert_eq!(ImageSource::none().size(), Size::default());
|
||||
assert!(ImageSource::none().is_empty());
|
||||
let pixels = ImageSource::rgba(2, 3, vec![0u8; 24]);
|
||||
assert_eq!(pixels.size(), Size { width: 2, height: 3 });
|
||||
assert!(!pixels.is_empty());
|
||||
// The wrong length is no picture.
|
||||
assert!(ImageSource::rgba(2, 3, vec![0u8; 23]).is_empty());
|
||||
assert_eq!(format!("{pixels:?}"), "Rgba(2x3)");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn files_by_content() {
|
||||
let dir = temp("files");
|
||||
// No extension: the cache's files have none.
|
||||
let path = dir.join("1234");
|
||||
std::fs::write(&path, png(4, 2)).unwrap();
|
||||
assert_eq!(ImageSource::file(&path).size(), Size { width: 4, height: 2 });
|
||||
let before = ImageSource::file(&path);
|
||||
// A changed file is read again.
|
||||
std::fs::write(&path, png(5, 3)).unwrap();
|
||||
let after = ImageSource::file(&path);
|
||||
assert_eq!(after.size(), Size { width: 5, height: 3 });
|
||||
// The same file, another picture: a list redraws the row.
|
||||
assert_ne!(before, after);
|
||||
assert_eq!(after, ImageSource::file(&path));
|
||||
let junk = dir.join("junk");
|
||||
std::fs::write(&junk, b"not a picture").unwrap();
|
||||
assert!(ImageSource::file(&junk).is_empty());
|
||||
assert!(ImageSource::file(dir.join("missing")).is_empty());
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vector_pictures() {
|
||||
let size = |svg: &str| ImageSource::Svg(svg.as_bytes().into()).size();
|
||||
assert_eq!(size("<svg width=\"32\" height=\"16\"/>"), Size { width: 32, height: 16 });
|
||||
assert_eq!(size("<svg viewBox='0 0 24 12'/>"), Size { width: 24, height: 12 });
|
||||
assert_eq!(size("<svg xmlns='http://www.w3.org/2000/svg'/>"), Size { width: 1, height: 1 });
|
||||
assert_eq!(size("<svg width=\"4096px\" height=\"4096px\"/>").width, 4096);
|
||||
// Too large to decode.
|
||||
assert!(
|
||||
ImageSource::Svg(b"<svg width=\"99999\" height=\"99999\"/>".as_slice().into())
|
||||
.is_empty()
|
||||
);
|
||||
// An SVG file with a byte order mark and a prolog, and in memory.
|
||||
let svg: &[u8] = b"\xef\xbb\xbf<?xml version=\"1.0\"?><svg width=\"8\" height=\"8\"/>";
|
||||
let dir = temp("svg");
|
||||
std::fs::write(dir.join("icon"), svg).unwrap();
|
||||
assert_eq!(ImageSource::file(dir.join("icon")).size().width, 8);
|
||||
let memory = ImageSource::Memory { key: "k".into(), bytes: png(3, 3).into() };
|
||||
assert_eq!(memory.size(), Size { width: 3, height: 3 });
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
//! Toolkit-free view models of the desktop client: engine state turned into
|
||||
//! plain rows and forms, with the logic that decides what the screens show.
|
||||
//! Neither Slint nor GPUI is a dependency; each front end converts these
|
||||
//! types (docs/ui.md, "Two crates").
|
||||
|
||||
pub mod avatar;
|
||||
pub mod bbcode;
|
||||
pub mod bridge;
|
||||
pub mod chat;
|
||||
pub mod color;
|
||||
pub mod emoji;
|
||||
pub mod home;
|
||||
pub mod image;
|
||||
pub mod list;
|
||||
pub mod servers;
|
||||
pub mod settings;
|
||||
pub mod settings_pages;
|
||||
pub mod social;
|
||||
pub mod state;
|
||||
pub mod streams;
|
||||
pub mod studio;
|
||||
pub mod studio_bridge;
|
||||
pub mod tree;
|
||||
|
||||
pub use color::Rgb;
|
||||
pub use image::{ImageRef, ImageSource, Size};
|
||||
@@ -0,0 +1,138 @@
|
||||
//! Incremental list updates: what changed between two versions of a list,
|
||||
//! as row operations. A front end that keeps a list model (Slint's
|
||||
//! `VecModel`) applies them row by row, so a client that starts talking
|
||||
//! redraws one row of the tree; one that rebuilds from the list (GPUI) just
|
||||
//! re-renders and has no use for them.
|
||||
|
||||
/// One row operation of a [`Changes`].
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Change {
|
||||
/// Row `i` holds another value: `new[i]`.
|
||||
Update(usize),
|
||||
/// Row `i` is gone.
|
||||
Remove(usize),
|
||||
/// `new[i]` is a new row, at `i`.
|
||||
Insert(usize),
|
||||
}
|
||||
|
||||
/// Row operations that turn the old list into the new one, in the order to
|
||||
/// apply them: updates, then removals (each at the index it has when its
|
||||
/// turn comes), then insertions (in ascending order).
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct Changes(pub Vec<Change>);
|
||||
|
||||
impl Changes {
|
||||
/// Nothing changed.
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.0.is_empty()
|
||||
}
|
||||
|
||||
/// How many rows are updated in place.
|
||||
pub fn updated(&self) -> usize {
|
||||
self.0.iter().filter(|c| matches!(c, Change::Update(_))).count()
|
||||
}
|
||||
|
||||
/// How many rows are removed.
|
||||
pub fn removed(&self) -> usize {
|
||||
self.0.iter().filter(|c| matches!(c, Change::Remove(_))).count()
|
||||
}
|
||||
|
||||
/// How many rows are inserted.
|
||||
pub fn inserted(&self) -> usize {
|
||||
self.0.iter().filter(|c| matches!(c, Change::Insert(_))).count()
|
||||
}
|
||||
|
||||
/// Apply the changes to `rows` (the old list), which then equals `new`.
|
||||
/// Also the reference for front ends: their models do the same
|
||||
/// operations in the same order.
|
||||
pub fn apply<T: Clone>(&self, rows: &mut Vec<T>, new: &[T]) {
|
||||
for change in &self.0 {
|
||||
match *change {
|
||||
Change::Update(i) => rows[i] = new[i].clone(),
|
||||
Change::Remove(i) => {
|
||||
rows.remove(i);
|
||||
}
|
||||
Change::Insert(i) => rows.insert(i, new[i].clone()),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What changes `old` into `new` with few row operations: the rows both
|
||||
/// share at the start and the end stay, rows in between are changed in
|
||||
/// place where they differ, and the rest inserted or removed.
|
||||
pub fn diff<T: PartialEq>(old: &[T], new: &[T]) -> Changes {
|
||||
let min = old.len().min(new.len());
|
||||
let prefix = old.iter().zip(new).take_while(|(a, b)| a == b).count();
|
||||
let suffix = old[prefix..]
|
||||
.iter()
|
||||
.rev()
|
||||
.zip(new[prefix..].iter().rev())
|
||||
.take(min - prefix)
|
||||
.take_while(|(a, b)| a == b)
|
||||
.count();
|
||||
let old_mid = old.len() - prefix - suffix;
|
||||
let new_mid = new.len() - prefix - suffix;
|
||||
let common = old_mid.min(new_mid);
|
||||
let mut changes = Vec::new();
|
||||
for i in prefix..prefix + common {
|
||||
if old[i] != new[i] {
|
||||
changes.push(Change::Update(i));
|
||||
}
|
||||
}
|
||||
let at = prefix + common;
|
||||
changes.extend((new_mid..old_mid).map(|_| Change::Remove(at)));
|
||||
changes.extend((at..at + new_mid.saturating_sub(old_mid)).map(Change::Insert));
|
||||
Changes(changes)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// The changes from `old` to `new`; applying them gives `new`.
|
||||
fn run(old: &[i32], new: &[i32]) -> Changes {
|
||||
let changes = diff(old, new);
|
||||
let mut rows = old.to_vec();
|
||||
changes.apply(&mut rows, new);
|
||||
assert_eq!(rows, new, "{old:?} -> {new:?}");
|
||||
changes
|
||||
}
|
||||
|
||||
fn counts(changes: &Changes) -> (usize, usize, usize) {
|
||||
(changes.updated(), changes.inserted(), changes.removed())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn minimal_changes() {
|
||||
assert!(run(&[1, 2, 3], &[1, 2, 3]).is_empty());
|
||||
assert_eq!(run(&[1, 2, 3], &[1, 9, 3]), Changes(vec![Change::Update(1)]));
|
||||
assert_eq!(run(&[1, 2, 3], &[1, 2, 7, 3]), Changes(vec![Change::Insert(2)]));
|
||||
assert_eq!(run(&[1, 2, 3], &[1, 3]), Changes(vec![Change::Remove(1)]));
|
||||
assert_eq!(counts(&run(&[], &[1, 2])), (0, 2, 0));
|
||||
assert_eq!(counts(&run(&[1, 2], &[])), (0, 0, 2));
|
||||
assert_eq!(run(&[1, 2, 3, 4], &[5, 6]).updated(), 2);
|
||||
run(&[1, 1, 1], &[1, 1]);
|
||||
run(&[1, 2, 1], &[1, 1, 2, 1]);
|
||||
run(&[4, 5, 6], &[1, 2, 3, 4, 5, 6, 7]);
|
||||
}
|
||||
|
||||
/// Whatever the lists, applying the changes gives the new list, and
|
||||
/// rows that stay at the ends are not touched.
|
||||
#[test]
|
||||
fn every_small_pair() {
|
||||
let lists: Vec<Vec<i32>> = (0..4usize)
|
||||
.flat_map(|n| (0..3i32.pow(n as u32)).map(move |k| (n, k)))
|
||||
.map(|(n, k)| (0..n as u32).map(|i| (k / 3i32.pow(i)) % 3).collect())
|
||||
.collect();
|
||||
for old in &lists {
|
||||
for new in &lists {
|
||||
let changes = run(old, new);
|
||||
let kept = old.iter().zip(new).take_while(|(a, b)| a == b).count();
|
||||
assert!(changes.0.iter().all(|c| match *c {
|
||||
Change::Update(i) | Change::Remove(i) | Change::Insert(i) => i >= kept,
|
||||
}));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,16 +1,19 @@
|
||||
//! The server rail, the server dialog, and joining a channel.
|
||||
|
||||
use slint::{Color, SharedString};
|
||||
use std::sync::Arc;
|
||||
|
||||
use voelin_core::{ObserveState, SessionState, VoiceState};
|
||||
use voelin_model::{ChannelId, ChannelInfo, Presence, ServerLink};
|
||||
use voelin_store::Bookmark;
|
||||
|
||||
use crate::app::{BookmarkForm, ServerItem};
|
||||
use crate::vm::avatar;
|
||||
use crate::avatar;
|
||||
use crate::bridge::{BookmarkForm, ServerItem};
|
||||
use crate::color::Rgb;
|
||||
use crate::image::ImageRef;
|
||||
|
||||
/// Restore a known server icon before any session exists. A missing/evicted
|
||||
/// cache file falls back to initials; the bookmark stores no filesystem path.
|
||||
pub fn cached_icon(bookmark: &Bookmark, cache: &voelin_core::Cache) -> slint::Image {
|
||||
pub fn cached_icon(bookmark: &Bookmark, cache: &voelin_core::Cache) -> ImageRef {
|
||||
avatar::image(bookmark.server_icon_id().and_then(|id| cache.icon(id)).as_ref())
|
||||
}
|
||||
|
||||
@@ -33,7 +36,7 @@ const SERVER_TINTS: [u32; 10] = [
|
||||
/// when an earlier server has it, it takes the next free one. So no two
|
||||
/// share a colour until there are more servers than colours (then they
|
||||
/// start over), and adding a server leaves the others' colours.
|
||||
pub fn tints(bookmarks: &[Bookmark]) -> Vec<Color> {
|
||||
pub fn tints(bookmarks: &[Bookmark]) -> Vec<Rgb> {
|
||||
let n = SERVER_TINTS.len();
|
||||
let mut taken = [false; SERVER_TINTS.len()];
|
||||
bookmarks
|
||||
@@ -65,7 +68,7 @@ pub fn status(state: &SessionState) -> &'static str {
|
||||
|
||||
/// A server of the rail and the home page. `unread`: messages in its
|
||||
/// chats; `live`: streams on it; `detail`: who is there ("9 online · 7
|
||||
/// channels"), empty for its address; `flavor`: "TeamSpeak 6" once
|
||||
/// channels"), empty for its address; `product`: "TeamSpeak 6" once
|
||||
/// reached; `icon`: the server's icon (empty: its initials) on `tint`
|
||||
/// ([`tints`]).
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
@@ -75,9 +78,9 @@ pub fn item(
|
||||
unread: i32,
|
||||
live: bool,
|
||||
detail: String,
|
||||
flavor: String,
|
||||
icon: slint::Image,
|
||||
tint: Color,
|
||||
product: String,
|
||||
icon: ImageRef,
|
||||
tint: Rgb,
|
||||
) -> ServerItem {
|
||||
ServerItem {
|
||||
id: bookmark.id as i32,
|
||||
@@ -90,7 +93,7 @@ pub fn item(
|
||||
unread,
|
||||
live,
|
||||
detail: if detail.is_empty() { bookmark.address.clone() } else { detail }.into(),
|
||||
flavor: flavor.into(),
|
||||
product: product.into(),
|
||||
gateway: bookmark.gateway_url.is_some() || bookmark.query.is_some(),
|
||||
}
|
||||
}
|
||||
@@ -106,7 +109,7 @@ pub fn form(
|
||||
BookmarkForm {
|
||||
id: bookmark.id as i32,
|
||||
name: if bookmark.name == bookmark.address {
|
||||
SharedString::new()
|
||||
"".into()
|
||||
} else {
|
||||
bookmark.name.clone().into()
|
||||
},
|
||||
@@ -134,7 +137,7 @@ pub struct ConnectTo {
|
||||
/// channel; and the link's privilege key.
|
||||
pub fn connect_to(form: &BookmarkForm, saved: Option<&Bookmark>) -> Option<ConnectTo> {
|
||||
let saved = saved?;
|
||||
let given = |text: &SharedString| Some(text.to_string()).filter(|t| !t.is_empty());
|
||||
let given = |text: &Arc<str>| Some(text.to_string()).filter(|t| !t.is_empty());
|
||||
let channel = given(&form.channel);
|
||||
Some(ConnectTo {
|
||||
channel_password: channel.as_ref().and_then(|_| given(&form.channel_password)),
|
||||
@@ -215,7 +218,7 @@ pub fn link_form(
|
||||
mut form: BookmarkForm,
|
||||
default_nickname: &str,
|
||||
) -> BookmarkForm {
|
||||
let text = |value: &Option<String>| SharedString::from(value.as_deref().unwrap_or_default());
|
||||
let text = |value: &Option<String>| Arc::<str>::from(value.as_deref().unwrap_or_default());
|
||||
if form.id < 0 {
|
||||
form.address = link.address().into();
|
||||
}
|
||||
@@ -223,7 +226,7 @@ pub fn link_form(
|
||||
form.nickname = link.nickname.as_deref().unwrap_or(default_nickname).into();
|
||||
}
|
||||
if let Some(password) = &link.password {
|
||||
form.server_password = password.into();
|
||||
form.server_password = password.as_str().into();
|
||||
}
|
||||
form.channel = text(&link.channel);
|
||||
form.channel_password = text(&link.channel_password);
|
||||
@@ -302,9 +305,9 @@ mod tests {
|
||||
String::new(),
|
||||
String::new(),
|
||||
cached_icon(&bookmark, &cache),
|
||||
Color::default(),
|
||||
Rgb::default(),
|
||||
);
|
||||
assert_eq!(server.status.as_str(), "offline");
|
||||
assert_eq!(server.status.as_ref(), "offline");
|
||||
assert_eq!(server.icon.size().width, 4);
|
||||
bookmark.address = "different.test".into();
|
||||
assert_eq!(cached_icon(&bookmark, &cache).size().width, 0);
|
||||
@@ -314,12 +317,34 @@ mod tests {
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
/// The chip of a server reads the product its session reported.
|
||||
#[test]
|
||||
fn a_server_shows_the_product_it_runs() {
|
||||
let bookmark = Bookmark { address: "example.test".into(), ..Default::default() };
|
||||
let state = SessionState::default();
|
||||
let on = |product: &str| {
|
||||
item(
|
||||
&bookmark,
|
||||
&state,
|
||||
0,
|
||||
false,
|
||||
String::new(),
|
||||
product.into(),
|
||||
Default::default(),
|
||||
Rgb::default(),
|
||||
)
|
||||
};
|
||||
assert_eq!(on("TeamSpeak 6").product.as_ref(), "TeamSpeak 6");
|
||||
// Before the server answered, and for software nobody recognised: none.
|
||||
assert_eq!(on("").product.as_ref(), "");
|
||||
}
|
||||
|
||||
fn named(names: &[&str]) -> Vec<Bookmark> {
|
||||
names.iter().map(|n| Bookmark { name: (*n).into(), ..Default::default() }).collect()
|
||||
}
|
||||
|
||||
/// The colour a name picks.
|
||||
fn own_tint(name: &str, step: usize) -> Color {
|
||||
fn own_tint(name: &str, step: usize) -> Rgb {
|
||||
let n = SERVER_TINTS.len();
|
||||
avatar::rgb(SERVER_TINTS[(avatar::name_hash(name) as usize + step) % n])
|
||||
}
|
||||
@@ -329,7 +354,7 @@ mod tests {
|
||||
let names: Vec<String> = (0..SERVER_TINTS.len()).map(|i| format!("Server {i}")).collect();
|
||||
let mut bookmarks = named(&names.iter().map(String::as_str).collect::<Vec<_>>());
|
||||
let distinct: std::collections::HashSet<_> =
|
||||
tints(&bookmarks).iter().map(|t| t.as_argb_encoded()).collect();
|
||||
tints(&bookmarks).iter().map(|t| t.0).collect();
|
||||
assert_eq!(distinct.len(), SERVER_TINTS.len());
|
||||
// One more starts over with its name's colour.
|
||||
bookmarks.extend(named(&["One more"]));
|
||||
@@ -363,8 +388,8 @@ mod tests {
|
||||
};
|
||||
let mut state = SessionState::default();
|
||||
let f = form(&b, None, "pw");
|
||||
assert_eq!((f.id, f.name.as_str(), f.address.as_str()), (3, "", "ts.example.test"));
|
||||
assert_eq!((f.nickname.as_str(), f.server_password.as_str()), ("Nova", "pw"));
|
||||
assert_eq!((f.id, f.name.as_ref(), f.address.as_ref()), (3, "", "ts.example.test"));
|
||||
assert_eq!((f.nickname.as_ref(), f.server_password.as_ref()), ("Nova", "pw"));
|
||||
assert!(!f.connected);
|
||||
for (voice, connected) in [
|
||||
(VoiceState::Disconnected, false),
|
||||
@@ -380,7 +405,7 @@ mod tests {
|
||||
state.observe = ObserveState::Observing;
|
||||
assert!(!form(&b, Some(&state), "").connected);
|
||||
let named = Bookmark { name: "Nightfall".into(), ..b };
|
||||
assert_eq!(form(&named, None, "").name.as_str(), "Nightfall");
|
||||
assert_eq!(form(&named, None, "").name.as_ref(), "Nightfall");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -546,16 +571,16 @@ mod tests {
|
||||
// A new server: the link's address, nickname and password.
|
||||
let new = BookmarkForm { id: -1, nickname: "Me".into(), ..Default::default() };
|
||||
let f = link_form(&link, new.clone(), "Me");
|
||||
assert_eq!((f.id, f.name.as_str(), f.address.as_str()), (-1, "", "ts.example.org:9988"));
|
||||
assert_eq!((f.nickname.as_str(), f.server_password.as_str()), ("Link", "pw"));
|
||||
assert_eq!((f.id, f.name.as_ref(), f.address.as_ref()), (-1, "", "ts.example.org:9988"));
|
||||
assert_eq!((f.nickname.as_ref(), f.server_password.as_ref()), ("Link", "pw"));
|
||||
assert_eq!(
|
||||
(f.channel.as_str(), f.channel_password.as_str(), f.token.as_str()),
|
||||
(f.channel.as_ref(), f.channel_password.as_ref(), f.token.as_ref()),
|
||||
("Gaming/Raid Night", "raid", "key")
|
||||
);
|
||||
let f = link_form(&bare, new, "Me");
|
||||
assert_eq!((f.address.as_str(), f.nickname.as_str()), ("ts.example.org", "Me"));
|
||||
assert_eq!((f.address.as_ref(), f.nickname.as_ref()), ("ts.example.org", "Me"));
|
||||
assert_eq!(
|
||||
(f.server_password.as_str(), f.channel.as_str(), f.token.as_str()),
|
||||
(f.server_password.as_ref(), f.channel.as_ref(), f.token.as_ref()),
|
||||
("", "", "")
|
||||
);
|
||||
// A saved server keeps its address, name, nickname and password...
|
||||
@@ -569,14 +594,14 @@ mod tests {
|
||||
};
|
||||
let f = link_form(&bare, saved.clone(), "Me");
|
||||
assert_eq!(
|
||||
(f.id, f.name.as_str(), f.address.as_str()),
|
||||
(f.id, f.name.as_ref(), f.address.as_ref()),
|
||||
(3, "Nightfall", "TS.example.org:9988")
|
||||
);
|
||||
assert_eq!((f.nickname.as_str(), f.server_password.as_str()), ("Nova", "stored"));
|
||||
assert_eq!((f.nickname.as_ref(), f.server_password.as_ref()), ("Nova", "stored"));
|
||||
// ...the link's password in place of the stored one.
|
||||
let f = link_form(&link, saved, "Me");
|
||||
assert_eq!((f.nickname.as_str(), f.server_password.as_str()), ("Nova", "pw"));
|
||||
assert_eq!((f.channel.as_str(), f.token.as_str()), ("Gaming/Raid Night", "key"));
|
||||
assert_eq!((f.nickname.as_ref(), f.server_password.as_ref()), ("Nova", "pw"));
|
||||
assert_eq!((f.channel.as_ref(), f.token.as_ref()), ("Gaming/Raid Night", "key"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -9,7 +9,7 @@ use voelin_audio::process::NoiseLevel;
|
||||
use voelin_core::settings::{Key, Kind};
|
||||
use voelin_core::{AudioSettings, TransmitMode};
|
||||
|
||||
use crate::app::AudioForm;
|
||||
use crate::bridge::AudioForm;
|
||||
|
||||
/// The window's settings, one value (the `ui` blob of earlier versions).
|
||||
pub static UI: Key<UiSettings> = Key::new(
|
||||
@@ -39,6 +39,7 @@ pub enum ThemeChoice {
|
||||
}
|
||||
|
||||
impl ThemeChoice {
|
||||
/// The value stored for this choice.
|
||||
pub fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
Self::Dark => "dark",
|
||||
@@ -47,6 +48,7 @@ impl ThemeChoice {
|
||||
}
|
||||
}
|
||||
|
||||
/// The choice a stored value names (dark for any other).
|
||||
pub fn parse(text: &str) -> Self {
|
||||
match text {
|
||||
"light" => Self::Light,
|
||||
@@ -133,10 +135,12 @@ pub enum NotifyLevel {
|
||||
}
|
||||
|
||||
impl NotifyLevel {
|
||||
/// The position in the settings' list (off, app, desktop).
|
||||
pub fn index(self) -> i32 {
|
||||
self as i32
|
||||
}
|
||||
|
||||
/// The choice at a list position (desktop for any other).
|
||||
pub fn from_index(index: i32) -> Self {
|
||||
match index {
|
||||
0 => Self::Off,
|
||||
@@ -155,22 +159,26 @@ pub static NOTIFY_MENTIONS: Key<NotifyLevel> = Key::new(
|
||||
"Our name in a channel or server chat: off, app (the bell) or desktop.",
|
||||
NotifyLevel::default,
|
||||
);
|
||||
/// Private messages: off, app (the bell) or desktop.
|
||||
pub static NOTIFY_MESSAGES: Key<NotifyLevel> = Key::new(
|
||||
"notify.private_messages",
|
||||
NOTIFY_LEVELS,
|
||||
"Private messages: off, app (the bell) or desktop.",
|
||||
NotifyLevel::default,
|
||||
);
|
||||
/// Pokes: off, app (the bell) or desktop.
|
||||
pub static NOTIFY_POKES: Key<NotifyLevel> =
|
||||
Key::new("notify.pokes", NOTIFY_LEVELS, "Pokes: off, app (the bell) or desktop.", || {
|
||||
NotifyLevel::Desktop
|
||||
});
|
||||
/// Reminders of scheduled events: off, app (the bell) or desktop.
|
||||
pub static NOTIFY_EVENTS: Key<NotifyLevel> = Key::new(
|
||||
"notify.event_reminders",
|
||||
NOTIFY_LEVELS,
|
||||
"Reminders of scheduled events: off, app (the bell) or desktop.",
|
||||
NotifyLevel::default,
|
||||
);
|
||||
/// Friends coming online: off, app (the bell) or desktop.
|
||||
pub static NOTIFY_FRIENDS: Key<NotifyLevel> = Key::new(
|
||||
"notify.friends_online",
|
||||
NOTIFY_LEVELS,
|
||||
@@ -253,11 +261,14 @@ pub fn page_keys() -> [&'static dyn voelin_core::settings::Setting; 10] {
|
||||
/// offers, in the order of its lists (`dialogs.slint`); any other value can
|
||||
/// be typed in.
|
||||
pub const FPS_CHOICES: [u32; 7] = [15, 30, 60, 120, 144, 240, 320];
|
||||
/// The bitrates (kbit/s, 0 for automatic) the share dialog offers, in the
|
||||
/// order of its list.
|
||||
pub const BITRATE_CHOICES: [u32; 8] = [0, 2500, 4608, 8000, 10_000, 20_000, 40_000, 60_000];
|
||||
|
||||
/// The share dialog's lists before they grew, which [`ShareDefaults`]
|
||||
/// indexes for older versions.
|
||||
pub const LEGACY_FPS_CHOICES: [u32; 3] = [15, 30, 60];
|
||||
/// The bitrates of the share dialog's list before it grew.
|
||||
pub const LEGACY_BITRATE_CHOICES: [u32; 4] = [2500, 4608, 8000, 10_000];
|
||||
|
||||
/// The index of the choice closest to `value`.
|
||||
@@ -270,6 +281,8 @@ pub fn parse_positive(text: &str) -> Option<u32> {
|
||||
text.trim().parse().ok().filter(|v| *v > 0)
|
||||
}
|
||||
|
||||
/// The `ui` settings: what the front end keeps about itself (the push-to-talk
|
||||
/// hotkey, codecs, the share dialog's defaults, the last voice channel).
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(default)]
|
||||
pub struct UiSettings {
|
||||
@@ -347,11 +360,13 @@ impl Default for ClientPlayback {
|
||||
}
|
||||
|
||||
impl ClientPlayback {
|
||||
/// Nothing differs from the defaults, so there is nothing to store.
|
||||
pub fn is_default(&self) -> bool {
|
||||
*self == Self::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// Each client's playback settings, by the client's unique id.
|
||||
pub type ClientPlaybackMap = BTreeMap<String, ClientPlayback>;
|
||||
|
||||
/// Audio devices as listed in the settings: the system default first.
|
||||
@@ -387,10 +402,14 @@ impl DeviceChoices {
|
||||
choices
|
||||
}
|
||||
|
||||
/// The index of the choice for device `id` (the system default for `None` or
|
||||
/// an unknown id).
|
||||
pub fn index_of(&self, id: Option<&str>) -> usize {
|
||||
self.ids.iter().position(|i| i.as_deref() == id).unwrap_or(0)
|
||||
}
|
||||
|
||||
/// The device id of choice `index`; `None` for the system default or an index
|
||||
/// outside the list.
|
||||
pub fn id_at(&self, index: i32) -> Option<String> {
|
||||
usize::try_from(index).ok().and_then(|i| self.ids.get(i).cloned()).flatten()
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,7 @@
|
||||
//! The settings pages added with the new design: My Account, Profiles
|
||||
//! (identities), Voice & Video, Streaming, Devices, Notifications, Privacy &
|
||||
//! Safety, Integrations (gateways, gateway administration, encoders) and
|
||||
//! Advanced. [`logic`] has what the pages show and what their controls
|
||||
//! change; the front ends put the rows on screen.
|
||||
|
||||
pub mod logic;
|
||||
@@ -4,6 +4,23 @@
|
||||
//! chats of the home sidebar; pure, so they are tested here.
|
||||
|
||||
use chrono::{DateTime, Local, NaiveDateTime, TimeZone};
|
||||
use voelin_core::HistoryMessage;
|
||||
use voelin_model::ChatTarget;
|
||||
|
||||
/// A chat of any server.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct ChatRef {
|
||||
/// The bookmark (session) it belongs to, when known.
|
||||
pub session: Option<i64>,
|
||||
/// The server's unique id.
|
||||
pub server_uid: Option<String>,
|
||||
/// Which chat of the server.
|
||||
pub target: ChatTarget,
|
||||
/// Its newest message.
|
||||
pub last: Option<HistoryMessage>,
|
||||
/// Messages not read.
|
||||
pub unread: i32,
|
||||
}
|
||||
|
||||
fn local(ts_ms: i64) -> Option<NaiveDateTime> {
|
||||
DateTime::from_timestamp_millis(ts_ms).map(|t| t.with_timezone(&Local).naive_local())
|
||||
@@ -18,6 +35,7 @@ pub fn ago(ts_ms: i64) -> String {
|
||||
ago_at(ts_ms, chrono::Utc::now().timestamp_millis())
|
||||
}
|
||||
|
||||
/// [`ago`] for a given time `now_ms`.
|
||||
pub fn ago_at(ts_ms: i64, now_ms: i64) -> String {
|
||||
if ts_ms <= 0 {
|
||||
return String::new();
|
||||
@@ -39,6 +57,7 @@ pub fn list_time(ts_ms: i64) -> String {
|
||||
local(ts_ms).map(|t| list_time_at(t, now_local())).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// [`list_time`] for a given local time `now`.
|
||||
pub fn list_time_at(then: NaiveDateTime, now: NaiveDateTime) -> String {
|
||||
use chrono::Datelike;
|
||||
let days = (now.date() - then.date()).num_days();
|
||||
@@ -53,7 +72,7 @@ pub fn list_time_at(then: NaiveDateTime, now: NaiveDateTime) -> String {
|
||||
|
||||
/// Chat text without BBCode (`[b]`, `[URL=…]`, `[/URL]`), on one line.
|
||||
pub fn plain(text: &str) -> String {
|
||||
without_emoji(&crate::vm::bbcode::parse(text).one_line())
|
||||
without_emoji(&crate::bbcode::parse(text).one_line())
|
||||
}
|
||||
|
||||
/// Text without emoji, runs of spaces as one: one line of text draws no
|
||||
@@ -76,7 +95,7 @@ fn is_emoji(c: char) -> bool {
|
||||
pub fn preview(text: &str, mine: bool, files: &[voelin_model::FileRef]) -> String {
|
||||
let body = if files.is_empty() { plain(text) } else { String::new() };
|
||||
let body = if body.is_empty() && !files.is_empty() {
|
||||
if files.iter().any(|f| crate::vm::chat::is_picture(&f.name)) {
|
||||
if files.iter().any(|f| crate::chat::is_picture(&f.name)) {
|
||||
"Sent a picture".to_owned()
|
||||
} else {
|
||||
"Sent a file".to_owned()
|
||||
@@ -116,7 +135,7 @@ pub fn poke_message(text: &str) -> String {
|
||||
|
||||
/// The private chats of the home sidebar, by their index in `chats`
|
||||
/// (newest first): at most `n`, those with unread messages first.
|
||||
pub fn sidebar_dms(chats: &[crate::messages::ChatRef], n: usize) -> Vec<usize> {
|
||||
pub fn sidebar_dms(chats: &[ChatRef], n: usize) -> Vec<usize> {
|
||||
let mut private: Vec<usize> = (0..chats.len())
|
||||
.filter(|&i| matches!(chats[i].target, voelin_model::ChatTarget::Private(_)))
|
||||
.collect();
|
||||
@@ -133,7 +152,7 @@ pub fn found_channels<'a>(
|
||||
) -> Vec<(u64, &'a str)> {
|
||||
channels
|
||||
.into_iter()
|
||||
.filter_map(|c| Some((c.id, crate::vm::tree::listed_title(c)?)))
|
||||
.filter_map(|c| Some((c.id, crate::tree::listed_title(c)?)))
|
||||
.filter(|(_, title)| matches(query, &[*title]))
|
||||
.collect()
|
||||
}
|
||||
@@ -287,7 +306,7 @@ mod tests {
|
||||
#[test]
|
||||
fn sidebar_chats() {
|
||||
use voelin_model::ChatTarget;
|
||||
let chat = |target: ChatTarget, unread| crate::messages::ChatRef {
|
||||
let chat = |target: ChatTarget, unread| ChatRef {
|
||||
session: Some(1),
|
||||
server_uid: None,
|
||||
target,
|
||||
@@ -0,0 +1,723 @@
|
||||
//! What the client knows, apart from how it is shown: the servers' sessions
|
||||
//! with their chat tabs, and the data the screens share. A front end owns
|
||||
//! one [`AppState`] and fills it from the engine's events; the view models
|
||||
//! (`chat`, `tree`, `servers`, ...) turn it into rows.
|
||||
//!
|
||||
//! The lines of a chat tab are the front end's own list type `L`: a Slint
|
||||
//! model (`bind::rows::Rows`), or a plain `Vec` of rows.
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
|
||||
use voelin_core::stream::StreamInfo;
|
||||
use voelin_core::{
|
||||
AudioSettings, Bytes, Contact, HistoryMessage, OfflineMessageInfo, SessionState, TransferState,
|
||||
VoiceState,
|
||||
};
|
||||
use voelin_gateway_proto::{
|
||||
Action, ActivityEntry, ConfigEntry, EventInfo, PermRuleInfo, StreamEntry, TopicInfo,
|
||||
};
|
||||
use voelin_model::{Capabilities, ChannelId, ChatMessage, ChatTarget, GroupInfo, Presence};
|
||||
use voelin_store::Bookmark;
|
||||
|
||||
use crate::chat::{LineCache, Previous};
|
||||
use crate::image::ImageRef;
|
||||
use crate::settings::{ClientPlaybackMap, DeviceChoices, UiSettings};
|
||||
|
||||
/// The store's name of a chat.
|
||||
pub fn store_target(target: &ChatTarget) -> voelin_store::ChatTarget {
|
||||
match target {
|
||||
ChatTarget::Server => voelin_store::ChatTarget::Server,
|
||||
ChatTarget::Channel(cid) => voelin_store::ChatTarget::Channel(*cid),
|
||||
ChatTarget::Private(uid) => voelin_store::ChatTarget::Private(uid.clone()),
|
||||
}
|
||||
}
|
||||
|
||||
/// A file being downloaded from a chat message.
|
||||
pub struct Download {
|
||||
/// The message's handle.
|
||||
pub key: i32,
|
||||
/// Which of the message's links this is.
|
||||
pub index: usize,
|
||||
/// The file's name.
|
||||
pub name: String,
|
||||
/// How the transfer stands.
|
||||
pub state: TransferState,
|
||||
}
|
||||
|
||||
/// A pinned message of a chat, with who pinned it.
|
||||
pub struct PinRow {
|
||||
/// The message's handle.
|
||||
pub key: i32,
|
||||
/// The message.
|
||||
pub message: HistoryMessage,
|
||||
/// Who pinned it.
|
||||
pub by: String,
|
||||
/// When it was pinned.
|
||||
pub ts_ms: i64,
|
||||
}
|
||||
|
||||
/// A linked picture.
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum Preview {
|
||||
/// Downloading (transfer id).
|
||||
Loading(u64),
|
||||
/// Downloaded: the file's bytes.
|
||||
Ready(Bytes),
|
||||
/// Too large, not a picture, or the download failed.
|
||||
Failed,
|
||||
}
|
||||
|
||||
/// What a session's gateway and voice connection add for these screens.
|
||||
#[derive(Default)]
|
||||
pub struct SessionExtra {
|
||||
/// The gateway's stream directory.
|
||||
pub directory: Vec<StreamEntry>,
|
||||
/// The gateway's events by start time.
|
||||
pub events: Vec<EventInfo>,
|
||||
/// The events were asked for and arrived.
|
||||
pub events_loaded: bool,
|
||||
/// The events whose answers are shown (by event id).
|
||||
pub expanded: HashSet<i64>,
|
||||
/// The activity feed, newest first.
|
||||
pub activity: Vec<ActivityEntry>,
|
||||
/// Our unique id at the gateway.
|
||||
pub gateway_uid: Option<String>,
|
||||
/// What we may do at the gateway.
|
||||
pub actions: Vec<Action>,
|
||||
/// Gateway administration: its keys.
|
||||
pub config: Vec<ConfigEntry>,
|
||||
/// Gateway administration: its permission rules.
|
||||
pub perms: Vec<PermRuleInfo>,
|
||||
/// Offline messages (voice).
|
||||
pub inbox: Vec<OfflineMessageInfo>,
|
||||
/// The offline messages were asked for.
|
||||
pub inbox_asked: bool,
|
||||
/// Pictures linked in chat, by link.
|
||||
pub previews: HashMap<String, Preview>,
|
||||
/// When this session's presence first came (ms): friends found in it
|
||||
/// then are not "coming online".
|
||||
pub presence_since: i64,
|
||||
/// "TeamSpeak 6", "TeamSpeak 3" once the server told what it runs;
|
||||
/// empty before that, and for software nobody recognised.
|
||||
pub product: String,
|
||||
}
|
||||
|
||||
/// A message of a chat with the handle the UI knows it by: the engine's
|
||||
/// local ids are 64 bit, a bridge `int` is not.
|
||||
pub struct Msg {
|
||||
/// The handle (see [`Tab::take_key`]).
|
||||
pub key: i32,
|
||||
/// The message as the engine stored it.
|
||||
pub message: HistoryMessage,
|
||||
}
|
||||
|
||||
/// A chat of a session: its lines (`L`) are what the chat view shows while
|
||||
/// the tab is selected, so a new message is one row appended.
|
||||
pub struct Tab<L> {
|
||||
/// The chat.
|
||||
pub target: ChatTarget,
|
||||
/// The tab's name.
|
||||
pub title: String,
|
||||
/// The lines the chat view shows.
|
||||
pub lines: L,
|
||||
/// The messages, oldest first, by `(ts_ms, id)`.
|
||||
pub messages: Vec<Msg>,
|
||||
/// Live messages of a session that keeps no history (no server unique
|
||||
/// id yet): grouped from the message before, without ids.
|
||||
pub last: Option<Previous>,
|
||||
/// Messages not read, not ours: those after `read` (without stored
|
||||
/// history, those that came while the tab was not on screen).
|
||||
pub unread: i32,
|
||||
/// The newest message read, by `(ts_ms, id)`: kept in the store
|
||||
/// (`chat_reads`) when the tab is left, the session closes and on exit
|
||||
/// (`App::save_read`). `stored_read` is what the store has.
|
||||
pub read: Option<(i64, i64)>,
|
||||
/// What the store has of `read`.
|
||||
pub stored_read: Option<(i64, i64)>,
|
||||
/// The message the "New" divider is above: the first that was new when
|
||||
/// the tab came on screen. It stays until the tab is left.
|
||||
pub divider: Option<i64>,
|
||||
/// Nothing older exists as far as the engine can tell.
|
||||
pub complete: bool,
|
||||
/// A gateway page arrived: the chat is not only what we saw.
|
||||
pub synced: bool,
|
||||
/// An older page was asked for.
|
||||
pub loading: bool,
|
||||
/// The next message handle.
|
||||
next_key: i32,
|
||||
/// The pins of this chat, once asked for.
|
||||
pub pins: Vec<PinRow>,
|
||||
/// The pins were asked for and arrived.
|
||||
pub pins_loaded: bool,
|
||||
/// The gateway topics of this chat.
|
||||
pub topics: Vec<TopicInfo>,
|
||||
/// The topics were asked for and arrived.
|
||||
pub topics_loaded: bool,
|
||||
/// The open topic.
|
||||
pub topic: Option<i64>,
|
||||
/// The messages of the open topic.
|
||||
pub topic_messages: Vec<Msg>,
|
||||
/// The message jumped to from the pins.
|
||||
pub marked: Option<i64>,
|
||||
/// What the lines of `messages` were built from.
|
||||
pub cache: LineCache,
|
||||
}
|
||||
|
||||
impl<L: Default> Tab<L> {
|
||||
/// An empty tab for a chat, nothing read or asked for.
|
||||
pub fn new(target: ChatTarget, title: String) -> Self {
|
||||
Self {
|
||||
target,
|
||||
title,
|
||||
lines: L::default(),
|
||||
messages: Vec::new(),
|
||||
last: None,
|
||||
unread: 0,
|
||||
read: None,
|
||||
stored_read: None,
|
||||
divider: None,
|
||||
complete: false,
|
||||
synced: false,
|
||||
loading: false,
|
||||
next_key: 1,
|
||||
pins: Vec::new(),
|
||||
pins_loaded: false,
|
||||
topics: Vec::new(),
|
||||
topics_loaded: false,
|
||||
topic: None,
|
||||
topic_messages: Vec::new(),
|
||||
marked: None,
|
||||
cache: Default::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<L> Tab<L> {
|
||||
/// A private chat (on the Direct Messages page, not in the chat strip).
|
||||
pub fn is_private(&self) -> bool {
|
||||
matches!(self.target, ChatTarget::Private(_))
|
||||
}
|
||||
|
||||
/// A handle for a message that has none yet.
|
||||
pub fn take_key(&mut self) -> i32 {
|
||||
self.next_key += 1;
|
||||
self.next_key
|
||||
}
|
||||
|
||||
/// The message with this handle, in the chat or in the open topic.
|
||||
pub fn message(&self, key: i32) -> Option<&HistoryMessage> {
|
||||
self.messages.iter().chain(&self.topic_messages).find(|m| m.key == key).map(|m| &m.message)
|
||||
}
|
||||
|
||||
/// Where each message is and whether it is ours (`own`), for the read
|
||||
/// markers ([`crate::chat::first_unread`]).
|
||||
pub fn positions(&self, own: impl Fn(&ChatMessage) -> bool) -> Vec<(i64, i64, bool)> {
|
||||
self.messages
|
||||
.iter()
|
||||
.map(|m| (m.message.message.ts_ms, m.message.id, own(&m.message.message)))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Where the newest message is.
|
||||
pub fn newest(&self) -> Option<(i64, i64)> {
|
||||
self.messages.last().map(|m| (m.message.message.ts_ms, m.message.id))
|
||||
}
|
||||
|
||||
/// The tab came on screen: the first new message gets the divider
|
||||
/// (unless one shows), and everything is read.
|
||||
pub fn enter(&mut self, own: impl Fn(&ChatMessage) -> bool) {
|
||||
if self.unread > 0 && self.divider.is_none() {
|
||||
let first = crate::chat::first_unread(&self.positions(own), self.read);
|
||||
self.divider = first.map(|i| self.messages[i].message.id);
|
||||
}
|
||||
self.catch_up();
|
||||
}
|
||||
|
||||
/// Everything in the tab is read (it is on screen).
|
||||
pub fn catch_up(&mut self) {
|
||||
self.read = self.read.max(self.newest());
|
||||
self.unread = 0;
|
||||
}
|
||||
|
||||
/// Count what is not read: what came after `read`, not ours.
|
||||
pub fn count_unread(&mut self, own: impl Fn(&ChatMessage) -> bool) {
|
||||
self.unread = crate::chat::unread_count(&self.positions(own), self.read);
|
||||
}
|
||||
|
||||
/// Start from where the store says the chat was read (`reads`: by the
|
||||
/// store's name of the chat).
|
||||
pub fn read_from(&mut self, reads: &HashMap<String, (i64, i64)>) {
|
||||
if let Some(&read) = reads.get(&store_target(&self.target).key()) {
|
||||
self.read = self.read.max(Some(read));
|
||||
self.stored_read = Some(read);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What we know about one server session.
|
||||
pub struct SessionView<L> {
|
||||
/// Where the connections stand.
|
||||
pub state: SessionState,
|
||||
/// What the server offers.
|
||||
pub capabilities: Capabilities,
|
||||
/// The server's channels and clients.
|
||||
pub presence: Arc<Presence>,
|
||||
/// The channels folded in the tree.
|
||||
pub collapsed: HashSet<ChannelId>,
|
||||
/// The clients talking now.
|
||||
pub talking: HashSet<u16>,
|
||||
/// The chats, the server's first.
|
||||
pub tabs: Vec<Tab<L>>,
|
||||
/// The chat on screen (an index of `tabs`).
|
||||
pub current_tab: usize,
|
||||
/// The chat strip's chat last current (the server's or a channel's): a
|
||||
/// private chat is current only on the Direct Messages page, and this
|
||||
/// one is current again when that page is left.
|
||||
pub channel_tab: ChatTarget,
|
||||
/// The own channel's tab was focused for this voice connection.
|
||||
pub focused_own_channel: bool,
|
||||
/// The streams in our channel (TeamSpeak 6).
|
||||
pub streams: Vec<StreamInfo>,
|
||||
/// Clients whose stored volume was sent for this voice connection.
|
||||
pub applied_playback: HashSet<u16>,
|
||||
/// Avatar pictures in the engine's cache, by unique id
|
||||
/// ([`Event::AvatarReady`]).
|
||||
pub avatars: HashMap<String, PathBuf>,
|
||||
/// Icons in the engine's cache, by icon id ([`Event::IconReady`]).
|
||||
pub icons: HashMap<u32, PathBuf>,
|
||||
/// Banners and badges in the engine's cache, by address
|
||||
/// ([`Event::PictureReady`]).
|
||||
pub pictures: HashMap<String, PathBuf>,
|
||||
/// The server's icon id as its voice connection last told it
|
||||
/// ([`Event::ServerDetails`]); kept while disconnected, for the rail.
|
||||
pub server_icon: u32,
|
||||
/// Bookmark address that supplied this session's icon.
|
||||
pub icon_address: Option<String>,
|
||||
/// The server groups in display order ([`Event::Groups`]).
|
||||
pub server_groups: Vec<GroupInfo>,
|
||||
/// The channel groups ([`Event::Groups`]).
|
||||
pub channel_groups: Vec<GroupInfo>,
|
||||
/// What the session's gateway offers (`voelin_gateway_proto::feature`).
|
||||
pub gateway_caps: Vec<String>,
|
||||
/// The client whose member card is open.
|
||||
pub member_card: Option<u16>,
|
||||
/// Passwords given for locked channels, until voice disconnects.
|
||||
pub channel_passwords: HashMap<ChannelId, String>,
|
||||
/// The channel a voice connection was asked into, until it is joined
|
||||
/// or joined again (`App::join_after_connect`).
|
||||
pub join_after_connect: Option<ChannelId>,
|
||||
/// Viewers of the streams in the gateway's directory, by stream id.
|
||||
pub stream_viewers: HashMap<String, u32>,
|
||||
/// Downloads started from chat, by transfer id.
|
||||
pub downloads: HashMap<u64, Download>,
|
||||
/// The next transfer id.
|
||||
pub next_transfer: u64,
|
||||
/// What the home, messages and events screens keep of the session.
|
||||
pub extra: SessionExtra,
|
||||
/// Where its chats were read, from the store (by the store's name of
|
||||
/// the chat), for the server unique id `reads_of`.
|
||||
pub reads: HashMap<String, (i64, i64)>,
|
||||
/// The server unique id `reads` are for.
|
||||
pub reads_of: Option<String>,
|
||||
}
|
||||
|
||||
impl<L: Default> Default for SessionView<L> {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
state: SessionState::default(),
|
||||
capabilities: Capabilities::default(),
|
||||
presence: Arc::default(),
|
||||
collapsed: HashSet::new(),
|
||||
talking: HashSet::new(),
|
||||
tabs: vec![Tab::new(ChatTarget::Server, "Server".into())],
|
||||
current_tab: 0,
|
||||
channel_tab: ChatTarget::Server,
|
||||
focused_own_channel: false,
|
||||
streams: Vec::new(),
|
||||
applied_playback: HashSet::new(),
|
||||
avatars: HashMap::new(),
|
||||
icons: HashMap::new(),
|
||||
pictures: HashMap::new(),
|
||||
server_icon: 0,
|
||||
icon_address: None,
|
||||
server_groups: Vec::new(),
|
||||
channel_groups: Vec::new(),
|
||||
gateway_caps: Vec::new(),
|
||||
member_card: None,
|
||||
channel_passwords: HashMap::new(),
|
||||
join_after_connect: None,
|
||||
stream_viewers: HashMap::new(),
|
||||
downloads: HashMap::new(),
|
||||
next_transfer: 1,
|
||||
extra: Default::default(),
|
||||
reads: HashMap::new(),
|
||||
reads_of: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<L> SessionView<L> {
|
||||
/// Streams can be watched and shared: TeamSpeak 6, connected with voice.
|
||||
pub fn streams_available(&self) -> bool {
|
||||
self.capabilities.streams && self.state.voice == VoiceState::Connected
|
||||
}
|
||||
|
||||
/// The channel a client is in.
|
||||
pub fn channel_of(&self, client: u16) -> Option<u64> {
|
||||
self.presence.clients.get(&client).map(|c| c.channel)
|
||||
}
|
||||
|
||||
/// The name of a client's channel when it is not ours; empty in ours.
|
||||
pub fn other_channel_name(&self, client: u16) -> String {
|
||||
self.channel_of(client)
|
||||
.filter(|c| Some(*c) != self.state.own_channel)
|
||||
.and_then(|c| self.presence.channels.get(&c))
|
||||
.map_or_else(String::new, |c| crate::tree::channel_title(c).0.to_owned())
|
||||
}
|
||||
|
||||
/// A client's nickname, or its id.
|
||||
pub fn nickname(&self, client: u16) -> String {
|
||||
self.presence
|
||||
.clients
|
||||
.get(&client)
|
||||
.map_or_else(|| format!("client {client}"), |c| c.nickname.clone())
|
||||
}
|
||||
|
||||
/// Unread messages in the server's and the channels' chats (the rail and
|
||||
/// the chat strip count them; private chats count on the Direct
|
||||
/// Messages page).
|
||||
pub fn channel_unread(&self) -> i32 {
|
||||
self.tabs.iter().filter(|t| !t.is_private()).map(|t| t.unread).sum()
|
||||
}
|
||||
|
||||
/// Unread messages in private chats.
|
||||
pub fn private_unread(&self) -> i32 {
|
||||
self.tabs.iter().filter(|t| t.is_private()).map(|t| t.unread).sum()
|
||||
}
|
||||
|
||||
/// Make tab `index` the current one; the chat strip remembers it unless
|
||||
/// it is a private chat.
|
||||
pub fn set_current_tab(&mut self, index: usize) {
|
||||
self.current_tab = index;
|
||||
if let Some(tab) = self.tabs.get(index).filter(|t| !t.is_private()) {
|
||||
self.channel_tab = tab.target.clone();
|
||||
}
|
||||
}
|
||||
|
||||
/// Focus tab `index`. While a private chat is current (the Direct
|
||||
/// Messages page shows it, and its composer sends there), a chat of the
|
||||
/// strip does not take its place: it is the strip's chat, current once
|
||||
/// that page is left (voice connecting focuses its channel's chat).
|
||||
pub fn focus_tab(&mut self, index: usize) {
|
||||
let Some(tab) = self.tabs.get(index) else { return };
|
||||
if !tab.is_private() && self.tabs.get(self.current_tab).is_some_and(Tab::is_private) {
|
||||
self.channel_tab = tab.target.clone();
|
||||
} else {
|
||||
self.set_current_tab(index);
|
||||
}
|
||||
}
|
||||
|
||||
/// Remove tab `index`. The current tab stays; when it is this one, the
|
||||
/// chat strip's next tab takes its place, else its last.
|
||||
pub fn remove_tab(&mut self, index: usize) -> Tab<L> {
|
||||
let tab = self.tabs.remove(index);
|
||||
if self.current_tab > index {
|
||||
self.current_tab -= 1;
|
||||
} else if self.current_tab == index {
|
||||
let (strip, _) = crate::chat::strip(self.tabs.iter().map(|t| &t.target), 0);
|
||||
let next = strip.iter().find(|&&i| i >= index).or(strip.last()).copied();
|
||||
self.set_current_tab(next.unwrap_or(0));
|
||||
}
|
||||
tab
|
||||
}
|
||||
|
||||
/// Leave a current private chat for the chat strip's last one (the
|
||||
/// Direct Messages page was left); `true` if the current tab changed.
|
||||
pub fn leave_private(&mut self) -> bool {
|
||||
if !self.tabs.get(self.current_tab).is_some_and(Tab::is_private) {
|
||||
return false;
|
||||
}
|
||||
self.current_tab = self.tabs.iter().position(|t| t.target == self.channel_tab).unwrap_or(0);
|
||||
true
|
||||
}
|
||||
|
||||
/// The session's gateway offers this feature
|
||||
/// (`voelin_gateway_proto::feature`).
|
||||
pub fn gateway_has(&self, feature: &str) -> bool {
|
||||
self.gateway_caps.iter().any(|c| c == feature)
|
||||
}
|
||||
|
||||
/// The chat history is kept by the engine (it knows the server): its
|
||||
/// messages come with ids, reactions and pins.
|
||||
pub fn has_history(&self) -> bool {
|
||||
self.state.server_uid.is_some()
|
||||
}
|
||||
|
||||
/// The avatar picture of a client, if the engine fetched one.
|
||||
pub fn avatar(&self, client: u16) -> Option<&PathBuf> {
|
||||
let uid = self.presence.clients.get(&client)?.uid.as_deref()?;
|
||||
self.avatars.get(uid)
|
||||
}
|
||||
|
||||
/// The server's icon, if it has one and the engine fetched it.
|
||||
pub fn server_icon(&self) -> ImageRef {
|
||||
crate::avatar::image(self.icons.get(&self.server_icon).filter(|_| self.server_icon != 0))
|
||||
}
|
||||
|
||||
/// Icons stay associated with the address that supplied them, including
|
||||
/// while a reconnect to an edited bookmark is pending or has failed.
|
||||
pub fn server_icon_for(&self, address: &str) -> ImageRef {
|
||||
if self.icon_address.as_deref() == Some(address) {
|
||||
self.server_icon()
|
||||
} else {
|
||||
ImageRef::default()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<L: Default> SessionView<L> {
|
||||
/// A new tab for `target`, read as far as the store says.
|
||||
pub fn new_tab(&self, target: ChatTarget, title: String) -> Tab<L> {
|
||||
let mut tab = Tab::new(target, title);
|
||||
tab.read_from(&self.reads);
|
||||
tab
|
||||
}
|
||||
}
|
||||
|
||||
/// The data the screens share, apart from the engine and the toolkit: the
|
||||
/// servers and what is known of their sessions, the settings the screens
|
||||
/// show and the dialogs' targets.
|
||||
pub struct AppState<L> {
|
||||
/// The saved servers, in the rail's order.
|
||||
pub bookmarks: Vec<Bookmark>,
|
||||
/// The server shown (a bookmark id).
|
||||
pub current: Option<i64>,
|
||||
/// What is known of each server's session, by bookmark id.
|
||||
pub sessions: HashMap<i64, SessionView<L>>,
|
||||
/// The line at the bottom: what happened last.
|
||||
pub status: String,
|
||||
/// What the toast of the next copy says instead of "Copied" (an invite
|
||||
/// names its channel and link).
|
||||
pub copy_note: Option<String>,
|
||||
/// The members panel's search.
|
||||
pub member_filter: String,
|
||||
/// The topics drawer's search.
|
||||
pub topic_filter: String,
|
||||
/// The voice channel view is shown (its people come first in the
|
||||
/// members panel).
|
||||
pub voice_view: bool,
|
||||
/// The UI's own settings (a working copy of the `ui` key).
|
||||
pub settings: UiSettings,
|
||||
/// The audio settings (a working copy).
|
||||
pub audio: AudioSettings,
|
||||
/// Audio settings changed since they were last stored.
|
||||
pub audio_dirty: bool,
|
||||
/// The input devices, as the settings list them.
|
||||
pub inputs: DeviceChoices,
|
||||
/// The output devices, as the settings list them.
|
||||
pub outputs: DeviceChoices,
|
||||
/// Local playback of each client, by unique id.
|
||||
pub playback: ClientPlaybackMap,
|
||||
/// The engine's contacts, by unique id.
|
||||
pub contacts: HashMap<String, Contact>,
|
||||
/// The client in the volume dialog: session, client id, unique id.
|
||||
pub playback_dialog: Option<(i64, u16, Option<String>)>,
|
||||
/// The locked channel the password dialog is for: session, channel.
|
||||
pub join_target: Option<(i64, ChannelId)>,
|
||||
/// Who the poke dialog pokes: session, client, nickname.
|
||||
pub poke_target: Option<(i64, u16, String)>,
|
||||
/// The window has the focus (desktop: the toolkit tells; elsewhere
|
||||
/// assumed): messages are read only then.
|
||||
pub focused: bool,
|
||||
/// The chat whose messages are on screen (session, target): when it is
|
||||
/// left, it is stored and loses its divider.
|
||||
pub reading: Option<(i64, ChatTarget)>,
|
||||
/// The microphone test runs.
|
||||
pub mic_test: bool,
|
||||
/// The capture for a share is being started.
|
||||
pub share_busy: bool,
|
||||
/// Why the last share did not start.
|
||||
pub share_error: String,
|
||||
/// A client whose stream was asked for before it was known (session,
|
||||
/// client): watched when the lookup brings it.
|
||||
pub pending_watch: Option<(i64, u16)>,
|
||||
/// Stream volume in percent, kept between streams.
|
||||
pub stream_volume: f32,
|
||||
/// Servers whose gateway was looked up in this run.
|
||||
pub gateways_looked_up: HashSet<i64>,
|
||||
/// Files being uploaded to a channel from the composer: session,
|
||||
/// channel and name, so the link can be posted when they are up.
|
||||
pub uploads: HashMap<u64, (i64, u64, String)>,
|
||||
}
|
||||
|
||||
impl<L> AppState<L> {
|
||||
/// The state at start: the saved servers (the first one shown), the
|
||||
/// stored settings, nothing known of any session yet.
|
||||
pub fn new(
|
||||
bookmarks: Vec<Bookmark>,
|
||||
settings: UiSettings,
|
||||
audio: AudioSettings,
|
||||
playback: ClientPlaybackMap,
|
||||
) -> Self {
|
||||
Self {
|
||||
current: bookmarks.first().map(|b| b.id),
|
||||
bookmarks,
|
||||
sessions: HashMap::new(),
|
||||
status: String::new(),
|
||||
copy_note: None,
|
||||
member_filter: String::new(),
|
||||
topic_filter: String::new(),
|
||||
voice_view: false,
|
||||
settings,
|
||||
audio,
|
||||
audio_dirty: false,
|
||||
inputs: DeviceChoices::default(),
|
||||
outputs: DeviceChoices::default(),
|
||||
playback,
|
||||
contacts: HashMap::new(),
|
||||
playback_dialog: None,
|
||||
join_target: None,
|
||||
poke_target: None,
|
||||
focused: true,
|
||||
reading: None,
|
||||
mic_test: false,
|
||||
share_busy: false,
|
||||
share_error: String::new(),
|
||||
pending_watch: None,
|
||||
stream_volume: 100.0,
|
||||
gateways_looked_up: HashSet::new(),
|
||||
uploads: HashMap::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use voelin_store::MessageSource;
|
||||
|
||||
use super::*;
|
||||
|
||||
fn msg(key: i32, id: i64, ts_ms: i64, own: bool) -> Msg {
|
||||
Msg {
|
||||
key,
|
||||
message: HistoryMessage {
|
||||
id,
|
||||
message: ChatMessage {
|
||||
target: ChatTarget::Server,
|
||||
author_name: if own { "me" } else { "you" }.into(),
|
||||
author_uid: None,
|
||||
author_id: None,
|
||||
text: format!("message {id}"),
|
||||
ts_ms,
|
||||
via_relay: false,
|
||||
blocked: false,
|
||||
},
|
||||
source: MessageSource::Voice,
|
||||
remote_id: None,
|
||||
topic_id: None,
|
||||
reactions: Vec::new(),
|
||||
pinned: false,
|
||||
rev: 0,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fn is_own(message: &ChatMessage) -> bool {
|
||||
message.author_name == "me"
|
||||
}
|
||||
|
||||
/// A session with the server's chat and then these.
|
||||
fn session(targets: &[ChatTarget]) -> SessionView<()> {
|
||||
let mut view = SessionView::<()>::default();
|
||||
for target in targets {
|
||||
view.tabs.push(Tab::new(target.clone(), "chat".into()));
|
||||
}
|
||||
view
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_private_chat_stays_current_until_its_page_is_left() {
|
||||
let mut view = session(&[ChatTarget::Channel(1), ChatTarget::Private("uid".into())]);
|
||||
view.set_current_tab(2);
|
||||
assert_eq!((view.current_tab, &view.channel_tab), (2, &ChatTarget::Server));
|
||||
// A chat of the strip does not take the private chat's place ...
|
||||
view.focus_tab(1);
|
||||
assert_eq!((view.current_tab, &view.channel_tab), (2, &ChatTarget::Channel(1)));
|
||||
// ... it is current once the page is left, and only once.
|
||||
assert!(view.leave_private());
|
||||
assert_eq!(view.current_tab, 1);
|
||||
assert!(!view.leave_private());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn removing_a_tab_keeps_the_current_one_or_picks_the_next_of_the_strip() {
|
||||
let mut view = session(&[ChatTarget::Channel(1), ChatTarget::Channel(2)]);
|
||||
view.set_current_tab(2);
|
||||
view.remove_tab(1);
|
||||
assert_eq!(view.current_tab, 1);
|
||||
assert_eq!(view.tabs[1].target, ChatTarget::Channel(2));
|
||||
// The current tab itself: the strip's next one takes its place.
|
||||
let mut view = session(&[ChatTarget::Channel(1), ChatTarget::Channel(2)]);
|
||||
view.set_current_tab(1);
|
||||
view.remove_tab(1);
|
||||
assert_eq!(view.tabs[view.current_tab].target, ChatTarget::Channel(2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unread_messages_are_counted_after_the_read_marker_and_not_ours() {
|
||||
let mut tab = Tab::<()>::new(ChatTarget::Server, "Server".into());
|
||||
tab.messages = vec![msg(1, 1, 100, false), msg(2, 2, 200, true), msg(3, 3, 300, false)];
|
||||
tab.count_unread(is_own);
|
||||
assert_eq!(tab.unread, 2);
|
||||
tab.read = Some((100, 1));
|
||||
tab.count_unread(is_own);
|
||||
assert_eq!(tab.unread, 1);
|
||||
assert_eq!(tab.newest(), Some((300, 3)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn entering_a_tab_puts_the_divider_above_the_first_new_message() {
|
||||
let mut tab = Tab::<()>::new(ChatTarget::Server, "Server".into());
|
||||
tab.messages = vec![msg(1, 1, 100, false), msg(2, 2, 200, false), msg(3, 3, 300, false)];
|
||||
tab.read = Some((100, 1));
|
||||
tab.count_unread(is_own);
|
||||
tab.enter(is_own);
|
||||
assert_eq!(tab.divider, Some(2));
|
||||
assert_eq!((tab.unread, tab.read), (0, Some((300, 3))));
|
||||
// A divider that shows stays when the tab is entered again.
|
||||
tab.unread = 1;
|
||||
tab.enter(is_own);
|
||||
assert_eq!(tab.divider, Some(2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_new_tab_starts_from_where_the_store_says_the_chat_was_read() {
|
||||
let mut view = SessionView::<()>::default();
|
||||
view.reads.insert(store_target(&ChatTarget::Channel(5)).key(), (700, 9));
|
||||
let tab = view.new_tab(ChatTarget::Channel(5), "five".into());
|
||||
assert_eq!((tab.read, tab.stored_read), (Some((700, 9)), Some((700, 9))));
|
||||
let other = view.new_tab(ChatTarget::Channel(6), "six".into());
|
||||
assert_eq!((other.read, other.stored_read), (None, None));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn handles_are_taken_one_by_one_and_found_in_topics_too() {
|
||||
let mut tab = Tab::<()>::new(ChatTarget::Server, "Server".into());
|
||||
let (a, b) = (tab.take_key(), tab.take_key());
|
||||
assert_ne!(a, b);
|
||||
tab.topic_messages.push(msg(a, 4, 400, false));
|
||||
assert_eq!(tab.message(a).map(|m| m.id), Some(4));
|
||||
assert!(tab.message(b).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unread_counts_split_between_the_strip_and_private_chats() {
|
||||
let mut view = session(&[ChatTarget::Channel(1), ChatTarget::Private("uid".into())]);
|
||||
view.tabs[0].unread = 2;
|
||||
view.tabs[1].unread = 3;
|
||||
view.tabs[2].unread = 4;
|
||||
assert_eq!((view.channel_unread(), view.private_unread()), (5, 4));
|
||||
}
|
||||
}
|
||||
@@ -5,8 +5,8 @@ use std::path::PathBuf;
|
||||
|
||||
use voelin_core::stream::StreamKind;
|
||||
|
||||
use crate::app::StreamItem;
|
||||
use crate::vm::avatar;
|
||||
use crate::avatar;
|
||||
use crate::bridge::StreamItem;
|
||||
|
||||
/// "Screen", "Window", "Camera"; "" for a kind we do not know.
|
||||
pub fn kind_label(kind: &StreamKind) -> &'static str {
|
||||
@@ -40,6 +40,7 @@ pub fn streamer(name: &str, picture: Option<&PathBuf>) -> StreamItem {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::Size;
|
||||
|
||||
#[test]
|
||||
fn kinds_have_labels() {
|
||||
@@ -60,10 +61,10 @@ mod tests {
|
||||
#[test]
|
||||
fn streamers_look_as_in_the_members() {
|
||||
let item = streamer("Nova Star", None);
|
||||
assert_eq!(item.streamer, "Nova Star");
|
||||
assert_eq!(item.initials, "NS");
|
||||
assert_eq!(&*item.streamer, "Nova Star");
|
||||
assert_eq!(&*item.initials, "NS");
|
||||
assert_eq!(item.tint, avatar::tint("Nova Star"));
|
||||
assert_eq!(item.avatar.size(), slint::Image::default().size());
|
||||
assert_eq!(item.avatar.size(), Size::default());
|
||||
assert!(item.id.is_empty() && !item.own && !item.studio);
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,6 +1,9 @@
|
||||
//! The Stream Studio's view models: scene, source, mixer and layer rows,
|
||||
//! the header's numbers, the source dialog's form, where new sources go and
|
||||
//! the overlay sources the stream settings' switches keep in the scenes.
|
||||
//! Decisions of the studio (what it does when) are in [`logic`].
|
||||
|
||||
pub mod logic;
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
@@ -11,7 +14,7 @@ use voelin_core::studio::scene::{
|
||||
Align, Background, Colour, Crop, Fit, Scene, Scenes, Source, SourceKind, Transform,
|
||||
};
|
||||
|
||||
use crate::app::{StudioAudio, StudioLayer, StudioScene, StudioSource, StudioSourceForm};
|
||||
use crate::studio_bridge::{StudioAudio, StudioLayer, StudioScene, StudioSource, StudioSourceForm};
|
||||
|
||||
/// The scenes; the live one marked, each with what it shows.
|
||||
pub fn scenes(scenes: &Scenes) -> Vec<StudioScene> {
|
||||
@@ -36,6 +39,7 @@ fn summary(scene: &Scene) -> String {
|
||||
if names.is_empty() { "Empty".into() } else { names.join(" + ") }
|
||||
}
|
||||
|
||||
/// The kind of a background by name: keep, blur, image or colour.
|
||||
pub fn background_name(background: &Background) -> &'static str {
|
||||
match background {
|
||||
Background::Keep => "keep",
|
||||
@@ -259,6 +263,7 @@ pub fn parse_colour(text: &str) -> Option<Colour> {
|
||||
Some(Colour::rgba(byte(0)?, byte(2)?, byte(4)?, a))
|
||||
}
|
||||
|
||||
/// A colour as `#rrggbb`, or `#rrggbbaa` when it is not opaque.
|
||||
pub fn colour_text(c: Colour) -> String {
|
||||
if c.a == 255 {
|
||||
format!("#{:02x}{:02x}{:02x}", c.r, c.g, c.b)
|
||||
@@ -356,7 +361,7 @@ fn transform(form: &StudioSourceForm) -> Result<Transform, String> {
|
||||
width: parse_size(&form.width, "width")?,
|
||||
height: parse_size(&form.height, "height")?,
|
||||
scale,
|
||||
fit: match form.fit.as_str() {
|
||||
fit: match form.fit.as_ref() {
|
||||
"cover" => Fit::Cover,
|
||||
"stretch" => Fit::Stretch,
|
||||
_ => Fit::Contain,
|
||||
@@ -365,7 +370,7 @@ fn transform(form: &StudioSourceForm) -> Result<Transform, String> {
|
||||
}
|
||||
|
||||
fn background(form: &StudioSourceForm) -> Result<Background, String> {
|
||||
Ok(match form.background.as_str() {
|
||||
Ok(match form.background.as_ref() {
|
||||
"blur" => Background::Blur { strength: parse_f32(&form.blur, "blur")?.max(0.0) / 100.0 },
|
||||
"image" if !form.background_path.trim().is_empty() => {
|
||||
Background::Image { path: form.background_path.trim().into() }
|
||||
@@ -392,7 +397,7 @@ pub fn change(form: &StudioSourceForm, old: &Source) -> Result<SourceChange, Str
|
||||
let opacity = (form.opacity / 100.0).clamp(0.0, 1.0);
|
||||
let differs = |a: bool| a.then_some(());
|
||||
Ok(SourceChange {
|
||||
name: differs(form.name.as_str() != old.name).map(|_| form.name.to_string()),
|
||||
name: differs(form.name.as_ref() != old.name).map(|_| form.name.to_string()),
|
||||
kind: differs(kind != old.kind).map(|_| kind),
|
||||
transform: differs(transform != old.transform).map(|_| transform),
|
||||
crop: differs(crop != old.crop).map(|_| crop),
|
||||
@@ -406,7 +411,7 @@ pub fn change(form: &StudioSourceForm, old: &Source) -> Result<SourceChange, Str
|
||||
/// The kind as the form says: text, colour and image from their fields, a
|
||||
/// camera's mirroring, anything else as it was.
|
||||
fn kind(form: &StudioSourceForm, old: Option<&SourceKind>) -> Result<SourceKind, String> {
|
||||
Ok(match (form.kind.as_str(), old) {
|
||||
Ok(match (form.kind.as_ref(), old) {
|
||||
("text", old) => {
|
||||
let (font, backdrop, align, padding) = match old {
|
||||
Some(SourceKind::Text { font, backdrop, align, padding, .. }) => {
|
||||
@@ -454,7 +459,7 @@ pub fn new_source(form: &StudioSourceForm, output: (u32, u32)) -> Result<Source,
|
||||
let kind = kind(form, None)?;
|
||||
let mut source = Source::new(0, kind);
|
||||
source.name = form.name.trim().to_owned();
|
||||
source.transform = if form.kind == "colour" {
|
||||
source.transform = if &*form.kind == "colour" {
|
||||
Transform::full(output.0, output.1)
|
||||
} else {
|
||||
let mut t = placement(&source.kind, output);
|
||||
@@ -501,8 +506,11 @@ pub struct Overlay {
|
||||
pub text: Option<String>,
|
||||
}
|
||||
|
||||
/// The overlay source that shows how many are watching.
|
||||
pub const OVERLAY_VIEWERS: &str = "Viewer count";
|
||||
/// The overlay source that shows the stream chat's last lines.
|
||||
pub const OVERLAY_CHAT: &str = "Chat overlay";
|
||||
/// The overlay source that names what plays.
|
||||
pub const OVERLAY_NOW_PLAYING: &str = "Now playing";
|
||||
|
||||
fn overlay_kind(name: &str, text: &str) -> SourceKind {
|
||||
@@ -598,11 +606,11 @@ mod tests {
|
||||
let rows = super::scenes(&scenes);
|
||||
assert_eq!(rows.len(), 2);
|
||||
assert!(rows[0].live && !rows[1].live);
|
||||
assert_eq!(rows[0].detail, "Screen + Camera");
|
||||
assert_eq!(rows[1].detail, "Empty");
|
||||
assert_eq!(&*rows[0].detail, "Screen + Camera");
|
||||
assert_eq!(&*rows[1].detail, "Empty");
|
||||
let sources = super::sources(scenes.active(), &[]);
|
||||
assert_eq!(
|
||||
sources.iter().map(|s| s.name.as_str()).collect::<Vec<_>>(),
|
||||
sources.iter().map(|s| s.name.as_ref()).collect::<Vec<_>>(),
|
||||
["Camera", "Screen"]
|
||||
);
|
||||
assert!(sources[0].front && !sources[0].back && sources[1].back);
|
||||
@@ -652,7 +660,7 @@ mod tests {
|
||||
assert!(parse_layer(&row("big", "", "800"), &old).is_err());
|
||||
assert!(parse_layer(&row("1", "", "fast"), &old).is_err());
|
||||
let rows = layers(&[l]);
|
||||
assert_eq!((rows[0].scale.as_str(), rows[0].bitrate.as_str()), ("0.5", "800"));
|
||||
assert_eq!((rows[0].scale.as_ref(), rows[0].bitrate.as_ref()), ("0.5", "800"));
|
||||
let below = next_layer(&[LayerSetting { bitrate: 8_000_000, ..old.clone() }], 8000);
|
||||
assert_eq!((below.scale, below.bitrate), (0.5, 2_000_000));
|
||||
}
|
||||
@@ -673,8 +681,8 @@ mod tests {
|
||||
);
|
||||
source.transform = Transform::box_at(10.0, 20.0, 300.0, 100.0);
|
||||
let mut f = form(&source);
|
||||
assert_eq!(f.text, "Hello\\nthere");
|
||||
assert_eq!((f.x.as_str(), f.width.as_str()), ("10", "300"));
|
||||
assert_eq!(&*f.text, "Hello\\nthere");
|
||||
assert_eq!((f.x.as_ref(), f.width.as_ref()), ("10", "300"));
|
||||
assert_eq!(change(&f, &source).unwrap(), SourceChange::default());
|
||||
f.x = "40".into();
|
||||
f.opacity = 50.0;
|
||||
@@ -0,0 +1,195 @@
|
||||
//! The Stream Studio's structs: the plain counterparts of
|
||||
//! `crates/voelin-ui/ui/studio-bridge.slint`, as [`crate::bridge`] has those of
|
||||
//! `bridge.slint`.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::image::ImageRef;
|
||||
|
||||
/// A scene of the studio.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct StudioScene {
|
||||
pub id: i32,
|
||||
pub name: Arc<str>,
|
||||
/// Its sources, front first: "Screen + Camera + Text".
|
||||
pub detail: Arc<str>,
|
||||
/// Composited now (the live scene).
|
||||
pub live: bool,
|
||||
/// The kind of its front-most source (for the icon).
|
||||
pub kind: Arc<str>,
|
||||
}
|
||||
|
||||
/// A source of the live scene, front first.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct StudioSource {
|
||||
pub id: i32,
|
||||
pub name: Arc<str>,
|
||||
/// screen, window, portal, camera, image, text, colour, pattern
|
||||
pub kind: Arc<str>,
|
||||
pub visible: bool,
|
||||
pub locked: bool,
|
||||
/// keep, blur, image, colour
|
||||
pub background: Arc<str>,
|
||||
/// Why it shows nothing ("" while it works).
|
||||
pub error: Arc<str>,
|
||||
/// "1920×1080 · 60 fps"
|
||||
pub info: Arc<str>,
|
||||
/// At the front or the back (cannot move further).
|
||||
pub front: bool,
|
||||
pub back: bool,
|
||||
}
|
||||
|
||||
/// An audio source of the stream (`stream.audio_sources`).
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct StudioAudio {
|
||||
pub name: Arc<str>,
|
||||
/// "Elgato Wave:3", the application...
|
||||
pub detail: Arc<str>,
|
||||
/// microphone, desktop, app, window, tone
|
||||
pub kind: Arc<str>,
|
||||
pub gain_db: f32,
|
||||
pub muted: bool,
|
||||
/// The meter in dBFS, after the gain.
|
||||
pub level: f32,
|
||||
/// Why it captures nothing.
|
||||
pub error: Arc<str>,
|
||||
}
|
||||
|
||||
/// A simulcast layer (`stream.layers`) as typed: any numbers.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct StudioLayer {
|
||||
/// "1280x720"; empty: `scale` of the output.
|
||||
pub size: Arc<str>,
|
||||
pub scale: Arc<str>,
|
||||
/// Frame-rate cap; empty: the output's.
|
||||
pub fps: Arc<str>,
|
||||
/// kbit/s.
|
||||
pub bitrate: Arc<str>,
|
||||
/// kbit/s a viewer needs for this layer.
|
||||
pub min_bitrate: Arc<str>,
|
||||
}
|
||||
|
||||
/// A viewer of the studio's stream.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct StudioViewer {
|
||||
pub client: i32,
|
||||
pub name: Arc<str>,
|
||||
/// requested, connecting, connected
|
||||
pub state: Arc<str>,
|
||||
}
|
||||
|
||||
/// An entry of a picker (screens, windows, cameras, audio sources).
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct StudioPick {
|
||||
pub name: Arc<str>,
|
||||
pub detail: Arc<str>,
|
||||
/// For the icon: monitor, window, portal, camera, microphone, desktop, app, tone
|
||||
pub kind: Arc<str>,
|
||||
/// The application's own icon (audio), if it has one.
|
||||
pub icon: ImageRef,
|
||||
/// Already mixed in (audio): picking it again takes it out.
|
||||
pub selected: bool,
|
||||
}
|
||||
|
||||
/// The header, the preview's badges and the bottom bar.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct StudioStatus {
|
||||
/// The engine runs (preview, mixer, replay buffer).
|
||||
pub running: bool,
|
||||
/// "Chill Zone • Starfall Community"; empty without a destination.
|
||||
pub destination: Arc<str>,
|
||||
/// 0: not live, 1: poor, 2: fair, 3: good, 4: excellent.
|
||||
pub quality: i32,
|
||||
pub quality_text: Arc<str>,
|
||||
/// "1080p • 60 FPS • 8,250 kbps"
|
||||
pub format: Arc<str>,
|
||||
/// The numbers behind it, for the info button.
|
||||
pub details: Arc<str>,
|
||||
pub live: bool,
|
||||
/// Going live: waiting for the server.
|
||||
pub starting: bool,
|
||||
/// "00:12:34"
|
||||
pub elapsed: Arc<str>,
|
||||
pub viewers: i32,
|
||||
pub participants: i32,
|
||||
pub can_go_live: bool,
|
||||
/// Why Go Live is off, or what goes wrong.
|
||||
pub hint: Arc<str>,
|
||||
pub recording: bool,
|
||||
pub recorded: Arc<str>,
|
||||
/// The replay buffer's window (0: off) and what it holds now.
|
||||
pub replay_seconds: i32,
|
||||
pub replay_held: Arc<str>,
|
||||
pub output_width: i32,
|
||||
pub output_height: i32,
|
||||
pub fps: i32,
|
||||
pub detached: bool,
|
||||
/// A window of its own is possible (not on Android).
|
||||
pub can_detach: bool,
|
||||
/// The live scene shows a screen, a camera, a window (the phone's cards).
|
||||
pub screen_shown: bool,
|
||||
pub camera_shown: bool,
|
||||
pub window_shown: bool,
|
||||
}
|
||||
|
||||
/// The stream settings panel (`studio.stream`, `stream.bitrate_kbps`).
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct StudioForm {
|
||||
pub destination: i32,
|
||||
pub title: Arc<str>,
|
||||
pub game: Arc<str>,
|
||||
pub message: Arc<str>,
|
||||
pub show_viewers: bool,
|
||||
pub show_chat: bool,
|
||||
pub show_now_playing: bool,
|
||||
pub audio: bool,
|
||||
/// kbit/s of the stream without layers, as typed.
|
||||
pub bitrate: Arc<str>,
|
||||
}
|
||||
|
||||
/// The source properties dialog (also for adding text, colour and image
|
||||
/// sources: `id` -1). Numbers as typed.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct StudioSourceForm {
|
||||
pub id: i32,
|
||||
pub name: Arc<str>,
|
||||
pub kind: Arc<str>,
|
||||
pub x: Arc<str>,
|
||||
pub y: Arc<str>,
|
||||
/// Empty: the source's own size times `scale`.
|
||||
pub width: Arc<str>,
|
||||
pub height: Arc<str>,
|
||||
pub scale: Arc<str>,
|
||||
/// contain, cover, stretch
|
||||
pub fit: Arc<str>,
|
||||
pub crop_left: Arc<str>,
|
||||
pub crop_top: Arc<str>,
|
||||
pub crop_right: Arc<str>,
|
||||
pub crop_bottom: Arc<str>,
|
||||
/// Percent.
|
||||
pub opacity: f32,
|
||||
pub locked: bool,
|
||||
pub visible: bool,
|
||||
/// keep, blur, image, colour
|
||||
pub background: Arc<str>,
|
||||
/// Blur radius in percent of the picture's height.
|
||||
pub blur: Arc<str>,
|
||||
pub background_path: Arc<str>,
|
||||
pub background_colour: Arc<str>,
|
||||
/// Text, colour ("#rrggbb" or "#rrggbbaa") and image sources.
|
||||
pub text: Arc<str>,
|
||||
pub text_size: Arc<str>,
|
||||
pub colour: Arc<str>,
|
||||
pub path: Arc<str>,
|
||||
pub mirror: bool,
|
||||
}
|
||||
|
||||
/// The studio settings dialog (`studio.*` keys and the preview).
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct StudioSettingsForm {
|
||||
pub replay_seconds: Arc<str>,
|
||||
pub replay_memory: Arc<str>,
|
||||
pub recording_dir: Arc<str>,
|
||||
pub preview_width: Arc<str>,
|
||||
pub preview_fps: Arc<str>,
|
||||
}
|
||||
@@ -10,9 +10,10 @@ use voelin_model::{
|
||||
tree_rows,
|
||||
};
|
||||
|
||||
use crate::app::{BadgeItem, MemberItem, TreeItem};
|
||||
use crate::avatar;
|
||||
use crate::bridge::{BadgeItem, MemberItem, TreeItem};
|
||||
use crate::image::ImageRef;
|
||||
use crate::settings::ClientPlaybackMap;
|
||||
use crate::vm::avatar;
|
||||
|
||||
/// A banner mode as the UI takes it (`TreeItem.banner-mode`).
|
||||
pub fn banner_mode(mode: BannerMode) -> i32 {
|
||||
@@ -24,12 +25,12 @@ pub fn banner_mode(mode: BannerMode) -> i32 {
|
||||
}
|
||||
|
||||
/// The picture of a banner address, if the engine fetched it.
|
||||
pub fn banner(pictures: &HashMap<String, PathBuf>, url: Option<&str>) -> slint::Image {
|
||||
pub fn banner(pictures: &HashMap<String, PathBuf>, url: Option<&str>) -> ImageRef {
|
||||
avatar::image(url.and_then(|u| pictures.get(u)))
|
||||
}
|
||||
|
||||
/// A badge's picture, if the engine fetched it.
|
||||
fn badge_icon(pictures: &HashMap<String, PathBuf>, guid: &str) -> slint::Image {
|
||||
fn badge_icon(pictures: &HashMap<String, PathBuf>, guid: &str) -> ImageRef {
|
||||
avatar::image(badges::icon_url(guid).and_then(|url| pictures.get(&url)))
|
||||
}
|
||||
|
||||
@@ -79,19 +80,19 @@ pub struct TreeInput<'a> {
|
||||
}
|
||||
|
||||
impl TreeInput<'_> {
|
||||
fn avatar(&self, client: &ClientInfo) -> slint::Image {
|
||||
fn avatar(&self, client: &ClientInfo) -> ImageRef {
|
||||
avatar::image(client.uid.as_ref().and_then(|uid| self.avatars.get(uid)))
|
||||
}
|
||||
|
||||
/// An icon by id, if the engine fetched it (0: none).
|
||||
fn icon(&self, id: u32) -> Option<slint::Image> {
|
||||
fn icon(&self, id: u32) -> Option<ImageRef> {
|
||||
let path = self.icons.get(&id).filter(|_| id != 0)?;
|
||||
Some(avatar::image(Some(path))).filter(|i| i.size().width > 0)
|
||||
}
|
||||
|
||||
/// The icons beside a client, as TeamSpeak shows them: its server
|
||||
/// groups' in display order, its channel group's, its own.
|
||||
fn client_icons(&self, client: &ClientInfo) -> Vec<slint::Image> {
|
||||
fn client_icons(&self, client: &ClientInfo) -> Vec<ImageRef> {
|
||||
let groups = self.groups.iter().filter(|g| client.server_groups.contains(&g.id));
|
||||
let channel_group =
|
||||
self.channel_groups.iter().filter(|g| client.channel_group == Some(g.id));
|
||||
@@ -105,7 +106,7 @@ impl TreeInput<'_> {
|
||||
|
||||
/// The pictures of the badges a client shows that arrived, in its
|
||||
/// order; empty slots last.
|
||||
fn badges(&self, client: &ClientInfo) -> [slint::Image; badges::SHOWN] {
|
||||
fn badges(&self, client: &ClientInfo) -> [ImageRef; badges::SHOWN] {
|
||||
let mut icons = client
|
||||
.badges
|
||||
.iter()
|
||||
@@ -384,7 +385,7 @@ impl TreeInput<'_> {
|
||||
#[derive(Clone, Default)]
|
||||
struct Section {
|
||||
title: String,
|
||||
icon: slint::Image,
|
||||
icon: ImageRef,
|
||||
}
|
||||
|
||||
/// Rows in sections: each section's first row carries the heading and how
|
||||
@@ -456,7 +457,7 @@ pub fn matching(rows: Vec<MemberItem>, filter: &str) -> Vec<MemberItem> {
|
||||
pub fn server_members(input: &TreeInput, voice_first: bool) -> Vec<MemberItem> {
|
||||
let first = Section {
|
||||
title: if voice_first { "In Voice" } else { "Streaming" }.into(),
|
||||
icon: slint::Image::default(),
|
||||
icon: ImageRef::default(),
|
||||
};
|
||||
let clients = input
|
||||
.presence
|
||||
@@ -596,7 +597,7 @@ mod tests {
|
||||
};
|
||||
let (t, c, pb) = (HashSet::new(), HashSet::new(), ClientPlaybackMap::new());
|
||||
let rows = rows(&input(&p, &t, &c, &pb, "", &e));
|
||||
let width = |i: &slint::Image| i.size().width;
|
||||
let width = |i: &ImageRef| i.size().width;
|
||||
let lobby = &rows[0];
|
||||
assert_eq!((width(&lobby.icon), width(&lobby.banner), lobby.banner_mode), (7, 9, 2));
|
||||
let alice = &rows[1];
|
||||
@@ -631,11 +632,11 @@ mod tests {
|
||||
pictures: HashMap::from([picture(0, 3), picture(2, 5), picture(3, 7)]),
|
||||
..Default::default()
|
||||
};
|
||||
let width = |i: &slint::Image| i.size().width;
|
||||
let width = |i: &ImageRef| i.size().width;
|
||||
let card = badge_items(&guids, &e.pictures);
|
||||
let names: Vec<_> = card.iter().map(|b| b.name.as_str()).collect();
|
||||
let names: Vec<_> = card.iter().map(|b| b.name.as_ref()).collect();
|
||||
assert_eq!(names, ["20th Anniversary", "Badge", "April Fools!"]);
|
||||
assert_eq!(card[1].description.as_str(), guids[1]);
|
||||
assert_eq!(card[1].description.as_ref(), guids[1]);
|
||||
assert_eq!(card.iter().map(|b| width(&b.icon)).collect::<Vec<_>>(), [3, 0, 5]);
|
||||
|
||||
let mut p = presence();
|
||||
@@ -697,7 +698,7 @@ mod tests {
|
||||
let c = HashSet::new();
|
||||
let rows = super::rows(&input(&p, &t, &c, &pb, "", &e));
|
||||
let chess = rows.iter().find(|r| r.is_channel && r.id == 3).unwrap();
|
||||
assert_eq!((chess.name.as_str(), chess.spacer), ("[cspacer1]Chess", 0));
|
||||
assert_eq!((chess.name.as_ref(), chess.spacer), ("[cspacer1]Chess", 0));
|
||||
assert_eq!(channel_title(&p.channels[&2]), ("Гамесы", Some(Spacer::Center)));
|
||||
assert_eq!(channel_title(&p.channels[&3]), ("[cspacer1]Chess", None));
|
||||
// Lists and pickers leave out what only separates.
|
||||
@@ -737,12 +738,12 @@ mod tests {
|
||||
let (t, c, pb) = (HashSet::from([11]), HashSet::new(), ClientPlaybackMap::new());
|
||||
let e = Extras::default();
|
||||
let rows = rows(&input(&p, &t, &c, &pb, "", &e));
|
||||
let names: Vec<_> = rows.iter().map(|r| r.name.as_str()).collect();
|
||||
let names: Vec<_> = rows.iter().map(|r| r.name.as_ref()).collect();
|
||||
assert_eq!(names, ["Lobby", "Alice", "Games", "bob", "Chess", "Carol"]);
|
||||
assert_eq!((rows[0].members, rows[0].max_members), (1, -1));
|
||||
assert_eq!((rows[2].members, rows[2].max_members, rows[2].own), (1, 5, true));
|
||||
assert!(rows[3].talking && rows[3].myself);
|
||||
assert_eq!(rows[3].initials, "BO");
|
||||
assert_eq!(&*rows[3].initials, "BO");
|
||||
assert_eq!(stats(&p), "3 online · 3 channels");
|
||||
}
|
||||
|
||||
@@ -752,7 +753,7 @@ mod tests {
|
||||
let (t, c, pb) = (HashSet::new(), HashSet::new(), ClientPlaybackMap::new());
|
||||
let e = Extras::default();
|
||||
let rows = rows(&input(&p, &t, &c, &pb, "car", &e));
|
||||
let names: Vec<_> = rows.iter().map(|r| r.name.as_str()).collect();
|
||||
let names: Vec<_> = rows.iter().map(|r| r.name.as_ref()).collect();
|
||||
assert_eq!(names, ["Games", "Chess", "Carol"]);
|
||||
let rows = super::rows(&input(&p, &t, &c, &pb, "LOBBY", &e));
|
||||
assert_eq!(rows.len(), 1);
|
||||
@@ -766,7 +767,7 @@ mod tests {
|
||||
let (t, c, pb) = (HashSet::new(), HashSet::new(), ClientPlaybackMap::new());
|
||||
let e = Extras::default();
|
||||
let members = members(&input(&p, &t, &c, &pb, "", &e));
|
||||
let names: Vec<_> = members.iter().map(|m| (m.name.as_str(), m.status.as_str())).collect();
|
||||
let names: Vec<_> = members.iter().map(|m| (m.name.as_ref(), m.status.as_ref())).collect();
|
||||
assert_eq!(names, [("bob", "Listening"), ("Carol", "Away")]);
|
||||
}
|
||||
|
||||
@@ -790,7 +791,7 @@ mod tests {
|
||||
let (t, c, pb) = (HashSet::new(), HashSet::new(), ClientPlaybackMap::new());
|
||||
let members = members(&input(&p, &t, &c, &pb, "", &e));
|
||||
let rows: Vec<_> =
|
||||
members.iter().map(|m| (m.name.as_str(), m.group.as_str(), m.first_in_group)).collect();
|
||||
members.iter().map(|m| (m.name.as_ref(), m.group.as_ref(), m.first_in_group)).collect();
|
||||
assert_eq!(rows, [("Carol", "Server Admin", true), ("bob", "Guest", true)]);
|
||||
assert!(members[0].admin && !members[1].admin);
|
||||
}
|
||||
@@ -884,12 +885,14 @@ mod tests {
|
||||
]
|
||||
);
|
||||
let all = server_members(&input(&p, &t, &c, &pb, "", &e), false);
|
||||
assert_eq!(all[1].role, "Moderator");
|
||||
assert_eq!(&*all[1].role, "Moderator");
|
||||
assert!(!all[1].admin);
|
||||
// The search keeps the sections of what it finds.
|
||||
let found = matching(all, "al");
|
||||
assert_eq!(found.len(), 1);
|
||||
assert!(found[0].first_in_group && found[0].group == "Guest" && found[0].group_count == 1);
|
||||
assert!(
|
||||
found[0].first_in_group && &*found[0].group == "Guest" && found[0].group_count == 1
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -24,8 +24,6 @@ dirs = "6"
|
||||
# avatars, icons and banners on TeamSpeak servers are GIF and WebP too (the
|
||||
# decoders are in the tree already, for SVG pictures).
|
||||
image = { version = "0.25", default-features = false, features = ["gif", "webp", "bmp", "ico"] }
|
||||
# Twemoji archive blocks (raw deflate); already used by png.
|
||||
miniz_oxide = "0.8"
|
||||
png = "0.18"
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
# Settings and gateway values as JSON (the advanced and integrations pages).
|
||||
@@ -44,6 +42,7 @@ voelin-model = { path = "../voelin-model" }
|
||||
voelin-platform = { path = "../voelin-platform", default-features = false }
|
||||
voelin-query = { path = "../voelin-query" }
|
||||
voelin-store = { path = "../voelin-store" }
|
||||
voelin-ui-vm = { path = "../voelin-ui-vm" }
|
||||
tsclientlib = { path = "../proto/tsclientlib" }
|
||||
|
||||
# Desktop: the keyring for passwords, stream media with libvpx, OpenH264, X11
|
||||
|
||||
@@ -1,11 +1,7 @@
|
||||
# Bundled assets
|
||||
|
||||
- `twemoji.bin`: the Twemoji 15.0 SVGs (3720 emoji, from the `@twemoji/svg`
|
||||
15.0.0 package) packed by `scripts/pack-twemoji.py` into blocks of raw
|
||||
deflate with an index; `src/emoji.rs` reads it. Twemoji graphics by Twitter,
|
||||
Inc and other contributors, licensed under CC-BY 4.0
|
||||
(https://creativecommons.org/licenses/by/4.0/). The files are unchanged
|
||||
apart from surrounding whitespace.
|
||||
The Twemoji archive is with the code that reads it, in
|
||||
`crates/voelin-ui-vm/assets/` (its license note is there).
|
||||
|
||||
The fonts (Inter, SIL OFL 1.1) and icons (Lucide, ISC) that the Slint files
|
||||
import are under `ui/assets/`, each with its license. All three are credited
|
||||
|
||||
+150
-551
File diff suppressed because it is too large.
Load diff
@@ -6,12 +6,13 @@
|
||||
use slint::ComponentHandle;
|
||||
use tracing::warn;
|
||||
|
||||
use crate::app::{App, AppearanceForm, Bridge, Nav, Theme};
|
||||
use crate::app::{App, Bridge, Nav, Theme};
|
||||
use crate::images;
|
||||
use crate::settings::{
|
||||
ThemeChoice, UI_FONT_SCALE, UI_IMAGE_CACHE_MB, UI_MEMBERS_WIDTH, UI_NARROW_BREAKPOINT,
|
||||
UI_THEME, UI_VOICE_COMPACT,
|
||||
};
|
||||
use crate::vm::bridge::AppearanceForm;
|
||||
|
||||
impl App {
|
||||
/// Show the current values of the appearance keys.
|
||||
@@ -33,12 +34,15 @@ impl App {
|
||||
}
|
||||
nav.set_voice_compact(self.prefs.get(&UI_VOICE_COMPACT));
|
||||
let bridge = ui.global::<Bridge>();
|
||||
bridge.set_appearance(AppearanceForm {
|
||||
theme: theme.as_str().into(),
|
||||
font_scale: scale,
|
||||
narrow_breakpoint: breakpoint as f32,
|
||||
image_cache_mb: cache_mb as f32,
|
||||
});
|
||||
bridge.set_appearance(
|
||||
AppearanceForm {
|
||||
theme: theme.as_str().into(),
|
||||
font_scale: scale,
|
||||
narrow_breakpoint: breakpoint as f32,
|
||||
image_cache_mb: cache_mb as f32,
|
||||
}
|
||||
.into(),
|
||||
);
|
||||
bridge.set_image_cache_usage(images::usage_text().into());
|
||||
self.theme_windows();
|
||||
}
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
//! Plain view-model values (`voelin-ui-vm`) to Slint values, and back where
|
||||
//! that can be done. Temporary, like the Slint front end itself: the rows
|
||||
//! (`items`) are converted when [`super::rows::Rows`] applies a change, so
|
||||
//! only changed rows pay for it.
|
||||
|
||||
use std::rc::Rc;
|
||||
use std::sync::Arc;
|
||||
|
||||
use slint::{Color, Image, ModelRc, Rgba8Pixel, SharedPixelBuffer, SharedString, VecModel};
|
||||
use voelin_ui_vm::{ImageRef, ImageSource, Rgb};
|
||||
|
||||
mod items;
|
||||
|
||||
/// An opaque colour.
|
||||
pub(crate) fn color(c: Rgb) -> Color {
|
||||
Color::from_rgb_u8(c.r(), c.g(), c.b())
|
||||
}
|
||||
|
||||
/// A colour that may be absent: transparent is the text's own colour.
|
||||
pub(crate) fn ink(c: Option<Rgb>) -> Color {
|
||||
c.map(color).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// The opaque colour of a Slint colour (its transparency is dropped).
|
||||
pub(crate) fn unrgb(c: Color) -> Rgb {
|
||||
Rgb::new(c.red(), c.green(), c.blue())
|
||||
}
|
||||
|
||||
/// The colour of a Slint colour, none for a transparent one.
|
||||
pub(crate) fn unink(c: Color) -> Option<Rgb> {
|
||||
(c.alpha() > 0).then(|| unrgb(c))
|
||||
}
|
||||
|
||||
/// A picture as Slint shows it: files and downloaded pictures through the
|
||||
/// decoded-picture cache (`images.rs`), pixels as they are.
|
||||
pub(crate) fn image(picture: &ImageRef) -> Image {
|
||||
match &**picture {
|
||||
ImageSource::None => Image::default(),
|
||||
ImageSource::File { path, .. } => crate::images::file(path),
|
||||
ImageSource::Rgba { w, h, bytes } => {
|
||||
Image::from_rgba8(SharedPixelBuffer::<Rgba8Pixel>::clone_from_slice(bytes, *w, *h))
|
||||
}
|
||||
ImageSource::Svg(data) => Image::load_from_svg_data(data).unwrap_or_default(),
|
||||
ImageSource::Memory { key, bytes } => crate::images::picture(key, bytes),
|
||||
}
|
||||
}
|
||||
|
||||
/// A model of pictures.
|
||||
pub(crate) fn images(pictures: &[ImageRef]) -> ModelRc<Image> {
|
||||
ModelRc::from(Rc::new(VecModel::from(pictures.iter().map(image).collect::<Vec<_>>())))
|
||||
}
|
||||
|
||||
/// A model of strings.
|
||||
pub(crate) fn strings(texts: &[Arc<str>]) -> ModelRc<SharedString> {
|
||||
ModelRc::from(Rc::new(VecModel::from(
|
||||
texts.iter().map(|t| SharedString::from(&**t)).collect::<Vec<_>>(),
|
||||
)))
|
||||
}
|
||||
|
||||
/// The strings of a model.
|
||||
pub(crate) fn unstrings(model: &ModelRc<SharedString>) -> Vec<Arc<str>> {
|
||||
slint::Model::iter(model).map(|t| Arc::from(t.as_str())).collect()
|
||||
}
|
||||
|
||||
/// A model of the Slint rows the plain rows convert to.
|
||||
pub(crate) fn model<V, S: for<'a> From<&'a V> + Clone + 'static>(rows: &[V]) -> ModelRc<S> {
|
||||
ModelRc::from(Rc::new(VecModel::from(rows.iter().map(S::from).collect::<Vec<_>>())))
|
||||
}
|
||||
|
||||
/// The plain rows of a model.
|
||||
pub(crate) fn rows<S: Clone + 'static, V: From<S>>(model: &ModelRc<S>) -> Vec<V> {
|
||||
slint::Model::iter(model).map(V::from).collect()
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -2,8 +2,10 @@
|
||||
//! area; each has a `wire` that the window calls once.
|
||||
|
||||
mod chat;
|
||||
pub(crate) mod convert;
|
||||
mod emoji;
|
||||
mod pages;
|
||||
pub(crate) mod rows;
|
||||
mod servers;
|
||||
mod settings;
|
||||
mod social;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//! The settings pages of the new design (settings_pages.rs).
|
||||
//! The settings pages of the new design (`settings_pages/`).
|
||||
|
||||
use slint::ComponentHandle;
|
||||
|
||||
@@ -33,7 +33,7 @@ pub(super) fn wire(ui: &MainWindow) {
|
||||
});
|
||||
// Voice & Video.
|
||||
bridge.on_video_changed(|form| {
|
||||
with_app(|app| app.video_changed(&form));
|
||||
with_app(|app| app.video_changed(&form.into()));
|
||||
});
|
||||
bridge.on_toggle_camera_preview(|| {
|
||||
with_app(|app| app.toggle_camera_preview());
|
||||
@@ -43,10 +43,10 @@ pub(super) fn wire(ui: &MainWindow) {
|
||||
});
|
||||
// Streaming.
|
||||
bridge.on_streaming_changed(|form| {
|
||||
with_app(|app| app.streaming_changed(&form));
|
||||
with_app(|app| app.streaming_changed(&form.into()));
|
||||
});
|
||||
bridge.on_layer_changed(|index, item| {
|
||||
with_app(|app| app.layer_changed(index, &item));
|
||||
with_app(|app| app.layer_changed(index, &item.into()));
|
||||
});
|
||||
bridge.on_add_layer(|| {
|
||||
with_app(|app| app.add_layer());
|
||||
@@ -55,7 +55,7 @@ pub(super) fn wire(ui: &MainWindow) {
|
||||
with_app(|app| app.remove_layer(index));
|
||||
});
|
||||
bridge.on_audio_source_changed(|index, item| {
|
||||
with_app(|app| app.audio_source_changed(index, &item));
|
||||
with_app(|app| app.audio_source_changed(index, &item.into()));
|
||||
});
|
||||
bridge.on_add_audio_source(|kind, name| {
|
||||
with_app(|app| app.add_audio_source(&kind, &name));
|
||||
@@ -65,13 +65,13 @@ pub(super) fn wire(ui: &MainWindow) {
|
||||
});
|
||||
// Notifications, privacy.
|
||||
bridge.on_notify_changed(|form| {
|
||||
with_app(|app| app.notify_changed(&form));
|
||||
with_app(|app| app.notify_changed(&form.into()));
|
||||
});
|
||||
bridge.on_test_notification(|| {
|
||||
with_app(|app| app.test_notification());
|
||||
});
|
||||
bridge.on_privacy_changed(|form| {
|
||||
with_app(|app| app.privacy_changed(&form));
|
||||
with_app(|app| app.privacy_changed(&form.into()));
|
||||
});
|
||||
// Integrations.
|
||||
bridge.on_gateway_admin(|session| {
|
||||
@@ -97,7 +97,7 @@ pub(super) fn wire(ui: &MainWindow) {
|
||||
});
|
||||
// Advanced.
|
||||
bridge.on_advanced_changed(|form| {
|
||||
with_app(|app| app.advanced_changed(&form));
|
||||
with_app(|app| app.advanced_changed(&form.into()));
|
||||
});
|
||||
bridge.on_srtp_move(|index, by| {
|
||||
with_app(|app| app.srtp_move(index, by));
|
||||
|
||||
@@ -0,0 +1,138 @@
|
||||
//! A Slint list model kept in step with plain rows: the view-model code
|
||||
//! produces the new list, [`list::diff`](voelin_ui_vm::list::diff) finds
|
||||
//! the row operations, and only those rows are converted and handed to the
|
||||
//! `VecModel` (views redraw only the rows that changed: a client that
|
||||
//! starts talking is one `set_row_data`).
|
||||
|
||||
use std::cell::{Ref, RefCell};
|
||||
use std::rc::Rc;
|
||||
use std::sync::Arc;
|
||||
|
||||
use slint::{Model, ModelRc, SharedString, VecModel};
|
||||
use voelin_ui_vm::list::{Change, Changes, diff};
|
||||
|
||||
/// A plain row that a Slint model shows as another type. Implemented for
|
||||
/// the bridge structs (`convert/items.rs`).
|
||||
pub(crate) trait Row: Clone + PartialEq {
|
||||
/// The Slint type of the row.
|
||||
type Shown: Clone + 'static;
|
||||
|
||||
/// The row as the window shows it.
|
||||
fn show(&self) -> Self::Shown;
|
||||
}
|
||||
|
||||
impl Row for Arc<str> {
|
||||
type Shown = SharedString;
|
||||
|
||||
fn show(&self) -> SharedString {
|
||||
SharedString::from(&**self)
|
||||
}
|
||||
}
|
||||
|
||||
/// The rows of a list as the view model made them (`T`), and the model the
|
||||
/// window shows.
|
||||
pub(crate) struct Rows<T: Row> {
|
||||
model: Rc<VecModel<T::Shown>>,
|
||||
rows: RefCell<Vec<T>>,
|
||||
}
|
||||
|
||||
impl<T: Row> Default for Rows<T> {
|
||||
fn default() -> Self {
|
||||
Self { model: Rc::default(), rows: RefCell::default() }
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Row> Rows<T> {
|
||||
/// The model, for a window property.
|
||||
pub fn model(&self) -> ModelRc<T::Shown> {
|
||||
ModelRc::from(self.model.clone())
|
||||
}
|
||||
|
||||
/// The rows now.
|
||||
pub fn rows(&self) -> Ref<'_, [T]> {
|
||||
Ref::map(self.rows.borrow(), Vec::as_slice)
|
||||
}
|
||||
|
||||
/// Row `i` now.
|
||||
pub fn get(&self, i: usize) -> Option<T> {
|
||||
self.rows.borrow().get(i).cloned()
|
||||
}
|
||||
|
||||
/// Change row `i` to `row` if it differs.
|
||||
pub fn set(&self, i: usize, row: T) {
|
||||
let mut rows = self.rows.borrow_mut();
|
||||
if rows.get(i).is_some_and(|old| *old != row) {
|
||||
self.model.set_row_data(i, row.show());
|
||||
rows[i] = row;
|
||||
}
|
||||
}
|
||||
|
||||
/// Append a row.
|
||||
pub fn push(&self, row: T) {
|
||||
self.model.push(row.show());
|
||||
self.rows.borrow_mut().push(row);
|
||||
}
|
||||
|
||||
/// Make the list `new`, with the fewest row operations.
|
||||
pub fn sync(&self, new: &[T]) -> Changes {
|
||||
let mut rows = self.rows.borrow_mut();
|
||||
let changes = diff(&rows, new);
|
||||
for change in &changes.0 {
|
||||
match *change {
|
||||
Change::Update(i) => self.model.set_row_data(i, new[i].show()),
|
||||
Change::Remove(i) => {
|
||||
self.model.remove(i);
|
||||
}
|
||||
Change::Insert(i) => self.model.insert(i, new[i].show()),
|
||||
}
|
||||
}
|
||||
changes.apply(&mut rows, new);
|
||||
changes
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
struct Plain(i32);
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
struct Shown(i32);
|
||||
impl Row for Plain {
|
||||
type Shown = Shown;
|
||||
|
||||
fn show(&self) -> Shown {
|
||||
Shown(self.0 * 10)
|
||||
}
|
||||
}
|
||||
|
||||
fn run(old: &[i32], new: &[i32]) -> Changes {
|
||||
let rows: Rows<Plain> = Rows::default();
|
||||
rows.sync(&old.iter().map(|&n| Plain(n)).collect::<Vec<_>>());
|
||||
let changes = rows.sync(&new.iter().map(|&n| Plain(n)).collect::<Vec<_>>());
|
||||
let shown: Vec<i32> = rows.model.iter().map(|s| s.0).collect();
|
||||
assert_eq!(shown, new.iter().map(|n| n * 10).collect::<Vec<_>>(), "{old:?} -> {new:?}");
|
||||
assert_eq!(rows.rows.borrow().len(), new.len());
|
||||
changes
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_model_follows_the_rows() {
|
||||
assert!(run(&[1, 2, 3], &[1, 2, 3]).is_empty());
|
||||
assert_eq!(run(&[1, 2, 3], &[1, 9, 3]).updated(), 1);
|
||||
assert_eq!(run(&[1, 2, 3], &[1, 2, 7, 3]).inserted(), 1);
|
||||
assert_eq!(run(&[1, 2, 3], &[1, 3]).removed(), 1);
|
||||
run(&[], &[1, 2]);
|
||||
run(&[1, 2], &[]);
|
||||
run(&[1, 2, 1], &[1, 1, 2, 1]);
|
||||
run(&[4, 5, 6], &[1, 2, 3, 4, 5, 6, 7]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strings_are_rows() {
|
||||
let rows: Rows<Arc<str>> = Rows::default();
|
||||
rows.sync(&["720p".into(), "1080p".into()]);
|
||||
assert_eq!(rows.model().row_data(1).as_deref(), Some("1080p"));
|
||||
}
|
||||
}
|
||||
@@ -25,7 +25,7 @@ pub(super) fn wire(ui: &MainWindow) {
|
||||
});
|
||||
bridge.on_join_channel(|cid| {
|
||||
with_app(|app| {
|
||||
if let Some(session) = app.current {
|
||||
if let Some(session) = app.state.current {
|
||||
app.join_channel(session, cid as ChannelId);
|
||||
}
|
||||
});
|
||||
@@ -45,17 +45,21 @@ pub(super) fn wire(ui: &MainWindow) {
|
||||
bridge.on_push_to_talk(|on| {
|
||||
with_app(|app| app.command(|session| Command::SetTransmitting { session, on }));
|
||||
});
|
||||
bridge.on_edit_bookmark(|id| with_app(|app| app.bookmark_form(id as i64)).unwrap_or_default());
|
||||
bridge.on_edit_bookmark(|id| {
|
||||
with_app(|app| app.bookmark_form(id as i64)).unwrap_or_default().into()
|
||||
});
|
||||
bridge.on_save_bookmark(|form| {
|
||||
with_app(|app| app.save_bookmark(&form));
|
||||
with_app(|app| app.save_bookmark(&form.into()));
|
||||
});
|
||||
bridge.on_save_and_connect(|form| {
|
||||
with_app(|app| app.save_and_connect(&form.into())).unwrap_or(false)
|
||||
});
|
||||
bridge.on_save_and_connect(|form| with_app(|app| app.save_and_connect(&form)).unwrap_or(false));
|
||||
bridge.on_delete_bookmark(|id| {
|
||||
with_app(|app| app.delete_bookmark(id as i64));
|
||||
});
|
||||
bridge.on_open_client(|id| with_app(|app| app.open_client(id as u16)).unwrap_or(false));
|
||||
bridge.on_client_audio_changed(|form| {
|
||||
with_app(|app| app.client_playback_changed(&form));
|
||||
with_app(|app| app.client_playback_changed(&form.into()));
|
||||
});
|
||||
bridge.on_invite(|| with_app(|app| app.invite_link()).unwrap_or_default().into());
|
||||
// Nav.copy, from any screen.
|
||||
|
||||
@@ -13,10 +13,10 @@ pub(super) fn wire(ui: &MainWindow) {
|
||||
with_app(|app| app.close_settings());
|
||||
});
|
||||
bridge.on_audio_changed(|form| {
|
||||
with_app(|app| app.audio_changed(&form));
|
||||
with_app(|app| app.audio_changed(&form.into()));
|
||||
});
|
||||
bridge.on_toggle_mic_test(|| {
|
||||
with_app(|app| app.set_mic_test(!app.mic_test));
|
||||
with_app(|app| app.set_mic_test(!app.state.mic_test));
|
||||
});
|
||||
bridge.on_apply_ptt(|enabled, key| {
|
||||
with_app(|app| app.apply_ptt(enabled, key.to_string()));
|
||||
@@ -34,7 +34,7 @@ pub(super) fn wire(ui: &MainWindow) {
|
||||
with_app(|app| app.voice_compact_changed(compact));
|
||||
});
|
||||
bridge.on_appearance_changed(|form| {
|
||||
with_app(|app| app.appearance_changed(&form));
|
||||
with_app(|app| app.appearance_changed(&form.into()));
|
||||
});
|
||||
bridge.on_set_crash_reports(|enabled| {
|
||||
with_app(|app| app.set_crash_reports(enabled));
|
||||
|
||||
@@ -64,7 +64,7 @@ pub(super) fn wire(ui: &MainWindow) {
|
||||
with_app(|app| app.dm_volume(percent));
|
||||
});
|
||||
bridge.on_send_offline(|form| {
|
||||
with_app(|app| app.send_offline(form));
|
||||
with_app(|app| app.send_offline(form.into()));
|
||||
});
|
||||
|
||||
// The bell.
|
||||
@@ -97,8 +97,10 @@ pub(super) fn wire(ui: &MainWindow) {
|
||||
bridge.on_toggle_event(|id| {
|
||||
with_app(|app| app.toggle_event(id));
|
||||
});
|
||||
bridge.on_edit_event(|id| with_app(|app| app.edit_event(id)).unwrap_or_default());
|
||||
bridge.on_save_event(|form| with_app(|app| app.save_event(&form)).unwrap_or_default().into());
|
||||
bridge.on_edit_event(|id| with_app(|app| app.edit_event(id)).unwrap_or_default().into());
|
||||
bridge.on_save_event(|form| {
|
||||
with_app(|app| app.save_event(&form.into())).unwrap_or_default().into()
|
||||
});
|
||||
bridge.on_delete_event(|id| {
|
||||
with_app(|app| app.delete_event(id));
|
||||
});
|
||||
|
||||
@@ -4,9 +4,9 @@
|
||||
use crate::app::{Bridge, with_app};
|
||||
|
||||
pub(crate) fn wire(bridge: &Bridge) {
|
||||
bridge.on_open_share(|| with_app(|app| app.open_share()).unwrap_or_default());
|
||||
bridge.on_open_share(|| with_app(|app| app.open_share()).unwrap_or_default().into());
|
||||
bridge.on_start_share(|form| {
|
||||
with_app(|app| app.start_share(form));
|
||||
with_app(|app| app.start_share(form.into()));
|
||||
});
|
||||
bridge.on_stop_share(|| {
|
||||
with_app(|app| app.stop_share());
|
||||
|
||||
@@ -52,13 +52,13 @@ pub(crate) fn wire(bridge: &StudioBridge) {
|
||||
with_app(|app| app.studio_add_picked(index(i)));
|
||||
});
|
||||
bridge.on_add_source(|form| {
|
||||
with_app(|app| app.studio_add_source(&form));
|
||||
with_app(|app| app.studio_add_source(&form.into()));
|
||||
});
|
||||
bridge.on_source_form(|source| {
|
||||
with_app(|app| app.studio_source_form(id(source))).unwrap_or_default()
|
||||
with_app(|app| app.studio_source_form(id(source))).unwrap_or_default().into()
|
||||
});
|
||||
bridge.on_apply_source(|form| {
|
||||
with_app(|app| app.studio_apply_source(&form));
|
||||
with_app(|app| app.studio_apply_source(&form.into()));
|
||||
});
|
||||
bridge.on_toggle_source(|source| {
|
||||
with_app(|app| app.studio_toggle_source(id(source)));
|
||||
@@ -93,7 +93,7 @@ pub(crate) fn wire(bridge: &StudioBridge) {
|
||||
with_app(|app| app.studio_set_output(&w, &h, &fps));
|
||||
});
|
||||
bridge.on_set_layer(|i, layer| {
|
||||
with_app(|app| app.studio_set_layer(index(i), &layer));
|
||||
with_app(|app| app.studio_set_layer(index(i), &layer.into()));
|
||||
});
|
||||
bridge.on_add_layer(|| {
|
||||
with_app(|app| app.studio_add_layer());
|
||||
@@ -120,9 +120,10 @@ pub(crate) fn wire(bridge: &StudioBridge) {
|
||||
bridge.on_end_stream(|| {
|
||||
with_app(|app| app.studio_end());
|
||||
});
|
||||
bridge.on_settings_form(|| with_app(|app| app.studio_settings_form()).unwrap_or_default());
|
||||
bridge
|
||||
.on_settings_form(|| with_app(|app| app.studio_settings_form()).unwrap_or_default().into());
|
||||
bridge.on_apply_settings(|form| {
|
||||
with_app(|app| app.studio_apply_settings(&form));
|
||||
with_app(|app| app.studio_apply_settings(&form.into()));
|
||||
});
|
||||
|
||||
bridge.on_respond_viewer(|client, accept| {
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
//! The engine keeps the history: [`Event::ChatHistory`] is an upsert of
|
||||
//! messages by their local id (see `voelin_core::history`), so a tab holds
|
||||
//! the messages it was given, ordered by `(ts_ms, id)`, and the lines of
|
||||
//! the selected tab are rebuilt from them with [`vm::list::sync`], which
|
||||
//! the selected tab are rebuilt from them and synced ([`Rows::sync`]), which
|
||||
//! touches only the rows that changed. Sessions the engine keeps no history
|
||||
//! for (it does not know the server yet) fall back to [`Event::Chat`].
|
||||
//!
|
||||
@@ -19,7 +19,7 @@
|
||||
use std::collections::HashMap;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use slint::{ComponentHandle, ModelRc};
|
||||
use slint::ComponentHandle;
|
||||
use voelin_core::gateway::Pin;
|
||||
use voelin_core::settings::CACHE_FETCH_IMAGES;
|
||||
use voelin_core::{
|
||||
@@ -30,11 +30,13 @@ use voelin_gateway_proto::{ErrorCode, TopicInfo, feature};
|
||||
use voelin_model::{ChatMessage, ChatTarget, HostMessageMode, ServerDetails};
|
||||
use voelin_store::ChatRead;
|
||||
|
||||
use crate::app::{App, Bridge, ChatLine, ChatTab, FileItem, Msg, Nav, PinItem, SessionView, Tab};
|
||||
use crate::app::{App, Bridge, Nav, SessionView, Tab};
|
||||
use crate::settings::UI_IMAGE_PREVIEW_KB;
|
||||
use crate::vm;
|
||||
use crate::vm::bbcode::LinkKind;
|
||||
use crate::vm::bridge::{ChatLine, ChatTab, FileItem, PinItem};
|
||||
use crate::vm::chat::{LineCache, LineCtx, Previous};
|
||||
use crate::vm::state::{Download, Msg, PinRow, store_target};
|
||||
|
||||
/// Where the server's welcome and host message keep what their lines were
|
||||
/// built from (`LineCache`), apart from the messages' ids.
|
||||
@@ -61,32 +63,6 @@ pub(crate) fn server_text<'a>(view: &'a SessionView, tab: &Tab, key: i32) -> Opt
|
||||
server_texts(&view.presence.server).get((-1 - key) as usize).map(|(text, _)| *text)
|
||||
}
|
||||
|
||||
/// The store's name of a chat.
|
||||
pub(crate) fn store_target(target: &ChatTarget) -> voelin_store::ChatTarget {
|
||||
match target {
|
||||
ChatTarget::Server => voelin_store::ChatTarget::Server,
|
||||
ChatTarget::Channel(cid) => voelin_store::ChatTarget::Channel(*cid),
|
||||
ChatTarget::Private(uid) => voelin_store::ChatTarget::Private(uid.clone()),
|
||||
}
|
||||
}
|
||||
|
||||
/// A file being downloaded from a chat message.
|
||||
pub(crate) struct Download {
|
||||
/// The message's handle and which of its links this is.
|
||||
pub key: i32,
|
||||
pub index: usize,
|
||||
pub name: String,
|
||||
pub state: TransferState,
|
||||
}
|
||||
|
||||
/// A pinned message of a chat, with who pinned it.
|
||||
pub(crate) struct PinRow {
|
||||
pub key: i32,
|
||||
pub message: HistoryMessage,
|
||||
pub by: String,
|
||||
pub ts_ms: i64,
|
||||
}
|
||||
|
||||
/// "3 min ago", "yesterday", "12 Mar".
|
||||
fn ago(ts_ms: i64) -> String {
|
||||
let Some(then) = chrono::DateTime::from_timestamp_millis(ts_ms) else { return String::new() };
|
||||
@@ -104,10 +80,10 @@ fn ago(ts_ms: i64) -> String {
|
||||
|
||||
impl App {
|
||||
pub(crate) fn open_chat(&mut self, target: ChatTarget, focus: bool) {
|
||||
let Some(id) = self.current else { return };
|
||||
let Some(id) = self.state.current else { return };
|
||||
let index = self.chat_tab(id, target);
|
||||
if focus {
|
||||
self.sessions.entry(id).or_default().focus_tab(index);
|
||||
self.state.sessions.entry(id).or_default().focus_tab(index);
|
||||
self.prefetch_counts();
|
||||
self.track_reading();
|
||||
}
|
||||
@@ -122,7 +98,7 @@ impl App {
|
||||
ChatTarget::Private(uid) => self.peer_name(uid, None),
|
||||
_ => String::new(),
|
||||
};
|
||||
let view = self.sessions.entry(id).or_default();
|
||||
let view = self.state.sessions.entry(id).or_default();
|
||||
if let Some(i) = view.tabs.iter().position(|t| t.target == target) {
|
||||
return i;
|
||||
}
|
||||
@@ -148,7 +124,7 @@ impl App {
|
||||
view.set_current_tab(index);
|
||||
view.tabs[index].topic = None;
|
||||
}
|
||||
if let Some(id) = self.current {
|
||||
if let Some(id) = self.state.current {
|
||||
self.fetch_previews(id);
|
||||
}
|
||||
self.prefetch_counts();
|
||||
@@ -158,13 +134,13 @@ impl App {
|
||||
}
|
||||
|
||||
pub(crate) fn close_tab(&mut self, index: usize) {
|
||||
let Some(id) = self.current else { return };
|
||||
let view = self.sessions.entry(id).or_default();
|
||||
let Some(id) = self.state.current else { return };
|
||||
let view = self.state.sessions.entry(id).or_default();
|
||||
if index == 0 || index >= view.tabs.len() {
|
||||
return;
|
||||
}
|
||||
self.save_read(id, index);
|
||||
let tab = self.sessions.entry(id).or_default().remove_tab(index);
|
||||
let tab = self.state.sessions.entry(id).or_default().remove_tab(index);
|
||||
self.engine.send(Command::CloseChat { session: id as u64, target: tab.target });
|
||||
self.prefetch_counts();
|
||||
self.track_reading();
|
||||
@@ -173,8 +149,8 @@ impl App {
|
||||
}
|
||||
|
||||
pub(crate) fn send_message(&mut self, text: String) {
|
||||
let Some(id) = self.current else { return };
|
||||
let Some(view) = self.sessions.get(&id) else { return };
|
||||
let Some(id) = self.state.current else { return };
|
||||
let Some(view) = self.state.sessions.get(&id) else { return };
|
||||
let target = view.tabs[view.current_tab].target.clone();
|
||||
self.engine.send(Command::SendChat { session: id as u64, target, text });
|
||||
}
|
||||
@@ -198,10 +174,10 @@ impl App {
|
||||
/// A live message of a session without stored history: appended as it
|
||||
/// comes, without an id.
|
||||
pub(crate) fn add_message(&mut self, id: i64, message: ChatMessage) {
|
||||
let current = self.current == Some(id);
|
||||
let current = self.state.current == Some(id);
|
||||
let reading = self.reads_now(id);
|
||||
let new = !self.is_own(id, &message);
|
||||
let view = self.sessions.entry(id).or_default();
|
||||
let view = self.state.sessions.entry(id).or_default();
|
||||
let title = vm::chat::tab_title(&view.presence, &message.target, &message.author_name);
|
||||
let index = Self::tab_for(view, &message.target, || title);
|
||||
let seen = reading && view.current_tab == index;
|
||||
@@ -231,7 +207,7 @@ impl App {
|
||||
source: HistorySource,
|
||||
complete: bool,
|
||||
) {
|
||||
let current = self.current == Some(id);
|
||||
let current = self.state.current == Some(id);
|
||||
let reading = self.reads_now(id);
|
||||
// A private chat is named after the peer, whoever wrote first.
|
||||
let peer = match target {
|
||||
@@ -244,7 +220,7 @@ impl App {
|
||||
)),
|
||||
_ => None,
|
||||
};
|
||||
let view = self.sessions.entry(id).or_default();
|
||||
let view = self.state.sessions.entry(id).or_default();
|
||||
let author = messages.first().map_or("", |m| m.message.author_name.as_str());
|
||||
let title = peer.unwrap_or_else(|| vm::chat::tab_title(&view.presence, target, author));
|
||||
let index = Self::tab_for(view, target, || title);
|
||||
@@ -308,8 +284,8 @@ impl App {
|
||||
|
||||
/// The page of messages before the oldest one shown.
|
||||
pub(crate) fn load_older(&mut self) {
|
||||
let Some(id) = self.current else { return };
|
||||
let Some(view) = self.sessions.get_mut(&id) else { return };
|
||||
let Some(id) = self.state.current else { return };
|
||||
let Some(view) = self.state.sessions.get_mut(&id) else { return };
|
||||
let tab = &mut view.tabs[view.current_tab];
|
||||
if tab.loading || tab.complete {
|
||||
return;
|
||||
@@ -329,7 +305,7 @@ impl App {
|
||||
|
||||
/// The lines of a tab's messages (`main`) or of its open topic, grouped
|
||||
/// and with everything the row shows (also the stream chat of the
|
||||
/// Stream Studio, studio.rs). The server chat starts with what the
|
||||
/// Stream Studio, studio/). The server chat starts with what the
|
||||
/// server says to everyone who connects ([`Self::server_lines`]).
|
||||
pub(crate) fn lines_of(&self, view: &SessionView, tab: &Tab, main: bool) -> Vec<ChatLine> {
|
||||
let messages = if main { &tab.messages } else { &tab.topic_messages };
|
||||
@@ -384,7 +360,7 @@ impl App {
|
||||
cache.keep(ids, messages.len());
|
||||
}
|
||||
// Pokes of a private chat's peer show among its messages.
|
||||
if let (ChatTarget::Private(uid), Some(session)) = (&tab.target, self.current) {
|
||||
if let (ChatTarget::Private(uid), Some(session)) = (&tab.target, self.state.current) {
|
||||
lines.extend(self.poke_lines(session, uid));
|
||||
lines.sort_by_key(|(ts, _)| *ts);
|
||||
}
|
||||
@@ -466,14 +442,11 @@ impl App {
|
||||
let Some(ui) = self.ui.upgrade() else { return };
|
||||
let bridge = ui.global::<Bridge>();
|
||||
let Some(view) = self.view() else {
|
||||
vm::list::sync(
|
||||
&self.models.tabs,
|
||||
&[ChatTab { title: "Server".into(), ..Default::default() }],
|
||||
);
|
||||
self.models.tabs.sync(&[ChatTab { title: "Server".into(), ..Default::default() }]);
|
||||
*self.models.strip.borrow_mut() = vec![0];
|
||||
bridge.set_current_tab(0);
|
||||
bridge.set_current_chat(0);
|
||||
let empty = ModelRc::from(self.models.no_chat.clone());
|
||||
let empty = self.models.no_chat.model();
|
||||
if bridge.get_messages() != empty {
|
||||
bridge.set_messages(empty);
|
||||
}
|
||||
@@ -523,7 +496,7 @@ impl App {
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
vm::list::sync(&self.models.tabs, &tabs);
|
||||
self.models.tabs.sync(&tabs);
|
||||
*self.models.strip.borrow_mut() = strip;
|
||||
if bridge.get_current_tab() != current {
|
||||
bridge.set_current_tab(current);
|
||||
@@ -535,9 +508,9 @@ impl App {
|
||||
if view.has_history() {
|
||||
let lines = self.lines_of(view, tab, true);
|
||||
divider = lines.iter().position(|l| l.unread_start);
|
||||
vm::list::sync(&tab.lines, &lines);
|
||||
tab.lines.sync(&lines);
|
||||
}
|
||||
let lines = ModelRc::from(tab.lines.clone());
|
||||
let lines = tab.lines.model();
|
||||
if bridge.get_messages() != lines {
|
||||
bridge.set_messages(lines);
|
||||
}
|
||||
@@ -546,7 +519,7 @@ impl App {
|
||||
.divider
|
||||
.and_then(|d| tab.messages.iter().position(|m| m.message.id == d))
|
||||
.map_or(&[][..], |i| &tab.messages[i..]);
|
||||
let session = self.current.unwrap_or_default();
|
||||
let session = self.state.current.unwrap_or_default();
|
||||
let count = new.iter().filter(|m| !self.is_own(session, &m.message.message)).count();
|
||||
bridge.set_unread_index(divider.map_or(-1, |i| i as i32));
|
||||
bridge.set_unread_count(count as i32);
|
||||
@@ -586,14 +559,14 @@ impl App {
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
vm::list::sync(&self.models.pins, &pins);
|
||||
let filter = self.topic_filter.trim().to_lowercase();
|
||||
self.models.pins.sync(&pins);
|
||||
let filter = self.state.topic_filter.trim().to_lowercase();
|
||||
let now = chrono::Utc::now().timestamp_millis();
|
||||
let topics: Vec<crate::app::TopicItem> = tab
|
||||
let topics: Vec<vm::bridge::TopicItem> = tab
|
||||
.topics
|
||||
.iter()
|
||||
.filter(|t| filter.is_empty() || t.title.to_lowercase().contains(&filter))
|
||||
.map(|t| crate::app::TopicItem {
|
||||
.map(|t| vm::bridge::TopicItem {
|
||||
id: t.id as i32,
|
||||
title: t.title.clone().into(),
|
||||
creator: t.creator.name.clone().into(),
|
||||
@@ -609,7 +582,7 @@ impl App {
|
||||
archived: t.archived,
|
||||
})
|
||||
.collect();
|
||||
vm::list::sync(&self.models.topics, &topics);
|
||||
self.models.topics.sync(&topics);
|
||||
bridge.set_current_topic(tab.topic.map_or(-1, |t| t as i32));
|
||||
bridge.set_topic_title(
|
||||
tab.topic
|
||||
@@ -618,7 +591,7 @@ impl App {
|
||||
.unwrap_or_default()
|
||||
.into(),
|
||||
);
|
||||
vm::list::sync(&self.models.topic_messages, &self.lines_of(view, tab, false));
|
||||
self.models.topic_messages.sync(&self.lines_of(view, tab, false));
|
||||
}
|
||||
|
||||
/// A link in a message was clicked (`masked`: its text shows something
|
||||
@@ -656,7 +629,7 @@ impl App {
|
||||
/// New messages of session `id` in its current tab are read as they
|
||||
/// come: they are on screen in the focused window.
|
||||
fn reads_now(&self, id: i64) -> bool {
|
||||
self.focused && self.current == Some(id) && self.chat_shown()
|
||||
self.state.focused && self.state.current == Some(id) && self.chat_shown()
|
||||
}
|
||||
|
||||
/// After anything that can change which chat is on screen (a tab, a
|
||||
@@ -664,26 +637,26 @@ impl App {
|
||||
/// loses its divider; the one on screen, in the focused window, is read
|
||||
/// (its divider above what was new). `true` if a tab changed.
|
||||
pub(crate) fn track_reading(&mut self) -> bool {
|
||||
let open = self.current.filter(|_| self.chat_shown()).and_then(|id| {
|
||||
let view = self.sessions.get(&id)?;
|
||||
let open = self.state.current.filter(|_| self.chat_shown()).and_then(|id| {
|
||||
let view = self.state.sessions.get(&id)?;
|
||||
Some((id, view.tabs.get(view.current_tab)?.target.clone()))
|
||||
});
|
||||
let mut changed = false;
|
||||
if open != self.reading {
|
||||
if let Some((id, target)) = self.reading.take()
|
||||
if open != self.state.reading {
|
||||
if let Some((id, target)) = self.state.reading.take()
|
||||
&& let Some(index) = self.tab_index(id, &target)
|
||||
{
|
||||
let tab = &mut self.sessions.entry(id).or_default().tabs[index];
|
||||
let tab = &mut self.state.sessions.entry(id).or_default().tabs[index];
|
||||
changed |= tab.divider.take().is_some();
|
||||
self.save_read(id, index);
|
||||
}
|
||||
self.reading = open.clone();
|
||||
self.state.reading = open.clone();
|
||||
}
|
||||
if let (true, Some((id, target))) = (self.focused, open)
|
||||
if let (true, Some((id, target))) = (self.state.focused, open)
|
||||
&& let Some(index) = self.tab_index(id, &target)
|
||||
{
|
||||
let own_uids = &self.social.own_uids;
|
||||
let view = self.sessions.entry(id).or_default();
|
||||
let view = self.state.sessions.entry(id).or_default();
|
||||
let own_client = view.state.own_client;
|
||||
let tab = &mut view.tabs[index];
|
||||
let before = (tab.unread, tab.divider);
|
||||
@@ -695,7 +668,7 @@ impl App {
|
||||
|
||||
/// Where the tab of `target` is in session `id`.
|
||||
fn tab_index(&self, id: i64, target: &ChatTarget) -> Option<usize> {
|
||||
self.sessions.get(&id)?.tabs.iter().position(|t| t.target == *target)
|
||||
self.state.sessions.get(&id)?.tabs.iter().position(|t| t.target == *target)
|
||||
}
|
||||
|
||||
/// The current chat came on screen or left it (`Nav.chat-shown`).
|
||||
@@ -710,7 +683,7 @@ impl App {
|
||||
/// only).
|
||||
#[cfg(not(target_os = "android"))]
|
||||
pub(crate) fn window_focused(&mut self, focused: bool) {
|
||||
self.focused = focused;
|
||||
self.state.focused = focused;
|
||||
if self.track_reading() {
|
||||
self.refresh_chat();
|
||||
self.refresh_servers();
|
||||
@@ -720,8 +693,8 @@ impl App {
|
||||
/// The current chat is read (the bar over its messages): the divider
|
||||
/// goes.
|
||||
pub(crate) fn mark_read(&mut self) {
|
||||
let Some(id) = self.current else { return };
|
||||
let Some(view) = self.sessions.get_mut(&id) else { return };
|
||||
let Some(id) = self.state.current else { return };
|
||||
let Some(view) = self.state.sessions.get_mut(&id) else { return };
|
||||
let index = view.current_tab;
|
||||
let tab = &mut view.tabs[index];
|
||||
tab.divider = None;
|
||||
@@ -737,7 +710,7 @@ impl App {
|
||||
if self.demo_ui {
|
||||
return;
|
||||
}
|
||||
let Some(view) = self.sessions.get_mut(&id) else { return };
|
||||
let Some(view) = self.state.sessions.get_mut(&id) else { return };
|
||||
let Some(server_uid) = view.state.server_uid.as_deref() else { return };
|
||||
let Some(tab) = view.tabs.get_mut(index) else { return };
|
||||
let Some((ts_ms, message)) = tab.read.filter(|r| tab.stored_read != Some(*r)) else {
|
||||
@@ -759,7 +732,7 @@ impl App {
|
||||
/// Store where every chat of session `id` was read (it ended, or the
|
||||
/// app exits).
|
||||
pub(crate) fn save_reads(&mut self, id: i64) {
|
||||
let count = self.sessions.get(&id).map_or(0, |v| v.tabs.len());
|
||||
let count = self.state.sessions.get(&id).map_or(0, |v| v.tabs.len());
|
||||
for index in 0..count {
|
||||
self.save_read(id, index);
|
||||
}
|
||||
@@ -769,7 +742,7 @@ impl App {
|
||||
/// server is known (or another one: the gateway's id wins): its tabs
|
||||
/// start from there, now and when they open.
|
||||
pub(crate) fn load_reads(&mut self, id: i64) {
|
||||
let Some(view) = self.sessions.get_mut(&id) else { return };
|
||||
let Some(view) = self.state.sessions.get_mut(&id) else { return };
|
||||
if self.demo_ui || view.state.server_uid.is_none() || view.reads_of == view.state.server_uid
|
||||
{
|
||||
return;
|
||||
@@ -796,8 +769,8 @@ impl App {
|
||||
}
|
||||
|
||||
pub(crate) fn gateway_update(&mut self, id: i64, update: GatewayUpdate) {
|
||||
let current = self.current == Some(id);
|
||||
let view = self.sessions.entry(id).or_default();
|
||||
let current = self.state.current == Some(id);
|
||||
let view = self.state.sessions.entry(id).or_default();
|
||||
match update {
|
||||
GatewayUpdate::Connected { capabilities, .. }
|
||||
| GatewayUpdate::Capabilities { capabilities } => {
|
||||
@@ -978,8 +951,8 @@ impl App {
|
||||
|
||||
/// The topics drawer's search.
|
||||
pub(crate) fn search_topics(&mut self, text: String) {
|
||||
if self.topic_filter != text {
|
||||
self.topic_filter = text;
|
||||
if self.state.topic_filter != text {
|
||||
self.state.topic_filter = text;
|
||||
self.refresh_chat();
|
||||
}
|
||||
}
|
||||
@@ -1026,7 +999,7 @@ impl App {
|
||||
|
||||
/// Download a file a message links, into the download folder.
|
||||
pub(crate) fn download_file(&mut self, key: i32, index: i32) {
|
||||
let Some(id) = self.current else { return };
|
||||
let Some(id) = self.state.current else { return };
|
||||
let index = index.max(0) as usize;
|
||||
let Some(file) =
|
||||
self.message_of(key).and_then(|m| m.message.file_refs().into_iter().nth(index))
|
||||
@@ -1035,7 +1008,7 @@ impl App {
|
||||
};
|
||||
let dir = dirs::download_dir().unwrap_or_else(|| PathBuf::from("."));
|
||||
let path = dir.join(&file.name);
|
||||
let view = self.sessions.entry(id).or_default();
|
||||
let view = self.state.sessions.entry(id).or_default();
|
||||
let transfer = view.next_transfer;
|
||||
view.next_transfer += 1;
|
||||
view.downloads.insert(
|
||||
@@ -1054,10 +1027,10 @@ impl App {
|
||||
|
||||
pub(crate) fn transfer_progress(&mut self, id: i64, transfer: u64, state: TransferState) {
|
||||
// An upload from the composer: post the file's link once it is up.
|
||||
if let Some((_, channel, name)) = self.uploads.get(&transfer).cloned() {
|
||||
if let Some((_, channel, name)) = self.state.uploads.get(&transfer).cloned() {
|
||||
match &state {
|
||||
TransferState::Done { size, .. } => {
|
||||
self.uploads.remove(&transfer);
|
||||
self.state.uploads.remove(&transfer);
|
||||
let file = voelin_model::FileRef {
|
||||
channel,
|
||||
path: "/".into(),
|
||||
@@ -1073,11 +1046,11 @@ impl App {
|
||||
self.set_status(format!("{name} shared"));
|
||||
}
|
||||
TransferState::Failed(e) => {
|
||||
self.uploads.remove(&transfer);
|
||||
self.state.uploads.remove(&transfer);
|
||||
self.set_status(format!("Could not upload {name}: {e}"));
|
||||
}
|
||||
TransferState::Cancelled => {
|
||||
self.uploads.remove(&transfer);
|
||||
self.state.uploads.remove(&transfer);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
@@ -1087,14 +1060,14 @@ impl App {
|
||||
return;
|
||||
}
|
||||
let done = matches!(state, TransferState::Done { .. });
|
||||
let view = self.sessions.entry(id).or_default();
|
||||
let view = self.state.sessions.entry(id).or_default();
|
||||
let Some(entry) = view.downloads.get_mut(&transfer) else { return };
|
||||
entry.state = state;
|
||||
let name = entry.name.clone();
|
||||
if done {
|
||||
self.set_status(format!("{name} downloaded"));
|
||||
}
|
||||
if self.current == Some(id) {
|
||||
if self.state.current == Some(id) {
|
||||
self.refresh_chat();
|
||||
}
|
||||
}
|
||||
@@ -1102,8 +1075,8 @@ impl App {
|
||||
/// Attach a file to the current channel chat: ask for one, upload it
|
||||
/// into the channel and post its link.
|
||||
pub(crate) fn attach_file(&mut self) {
|
||||
let Some(id) = self.current else { return };
|
||||
let Some(view) = self.sessions.get(&id) else { return };
|
||||
let Some(id) = self.state.current else { return };
|
||||
let Some(view) = self.state.sessions.get(&id) else { return };
|
||||
let ChatTarget::Channel(channel) = view.tabs[view.current_tab].target else {
|
||||
self.set_status("Files can be attached to a channel's chat.");
|
||||
return;
|
||||
@@ -1126,10 +1099,10 @@ impl App {
|
||||
/// Upload a file into a channel and link it in the chat once it is up.
|
||||
pub(crate) fn upload(&mut self, id: i64, channel: u64, from: PathBuf) {
|
||||
let Some(name) = from.file_name().map(|n| n.to_string_lossy().to_string()) else { return };
|
||||
let view = self.sessions.entry(id).or_default();
|
||||
let view = self.state.sessions.entry(id).or_default();
|
||||
let transfer = view.next_transfer;
|
||||
view.next_transfer += 1;
|
||||
self.uploads.insert(transfer, (id, channel, name.clone()));
|
||||
self.state.uploads.insert(transfer, (id, channel, name.clone()));
|
||||
self.engine.send(Command::UploadFile {
|
||||
session: id as u64,
|
||||
transfer,
|
||||
|
||||
+64
-35
@@ -70,8 +70,8 @@ use slint::{ComponentHandle, Rgba8Pixel, SharedPixelBuffer};
|
||||
use voelin_core::gateway::Pin;
|
||||
use voelin_core::stream::{StreamInfo, StreamKind};
|
||||
use voelin_core::{
|
||||
Contact, Event, GatewayUpdate, HistoryMessage, HistorySource, JoinFailure, ObserveState,
|
||||
OfflineMessageInfo, Relation, SessionState, Source, VoiceState,
|
||||
BackendInfo, Contact, Event, GatewayUpdate, HistoryMessage, HistorySource, JoinFailure,
|
||||
ObserveState, OfflineMessageInfo, Relation, SessionState, Source, VoiceState,
|
||||
};
|
||||
use voelin_gateway_proto::{
|
||||
Action, Attendee, ConfigEntry, ConfigSource, EventInfo, EventKind, EventSpec, PermRule,
|
||||
@@ -79,14 +79,13 @@ use voelin_gateway_proto::{
|
||||
feature,
|
||||
};
|
||||
use voelin_model::{
|
||||
BannerMode, ChannelInfo, ChatMessage, ChatTarget, ClientInfo, GroupInfo, Presence, ServerFlavor,
|
||||
BannerMode, Capabilities, ChannelInfo, ChatMessage, ChatTarget, ClientInfo, GroupInfo, Presence,
|
||||
};
|
||||
use voelin_store::{Bookmark, MessageSource};
|
||||
|
||||
use crate::app::{
|
||||
App, Bridge, MainWindow, MobileTab, Nav, Page, RecordingItem, SettingsSection, with_app,
|
||||
};
|
||||
use crate::app::{App, Bridge, MainWindow, MobileTab, Nav, Page, SettingsSection, with_app};
|
||||
use crate::settings::LastVoice;
|
||||
use crate::vm::bridge::RecordingItem;
|
||||
|
||||
/// The switches read at start.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
@@ -185,7 +184,7 @@ pub(crate) fn start(ui: &MainWindow, switches: &Switches) -> Running {
|
||||
}
|
||||
Some("observe") => {
|
||||
with_app(|app| {
|
||||
if let Some(id) = app.current {
|
||||
if let Some(id) = app.state.current {
|
||||
app.observe(id);
|
||||
}
|
||||
});
|
||||
@@ -215,7 +214,7 @@ pub(crate) fn start(ui: &MainWindow, switches: &Switches) -> Running {
|
||||
}
|
||||
// The current server's dialog, Advanced open.
|
||||
"bookmark" if arg == "edit" => {
|
||||
if let Some(id) = with_app(|app| app.current).flatten() {
|
||||
if let Some(id) = with_app(|app| app.state.current).flatten() {
|
||||
nav.invoke_edit_server(id as i32);
|
||||
}
|
||||
}
|
||||
@@ -426,9 +425,9 @@ fn late(
|
||||
/// The current chat's read marker `back` messages before its end, as if
|
||||
/// they came while away, its "New" divider shown (`VOELIN_OPEN=unread`).
|
||||
fn open_unread(app: &mut App, back: usize) {
|
||||
let Some(id) = app.current else { return };
|
||||
let Some(id) = app.state.current else { return };
|
||||
let own_uids = app.social.own_uids.clone();
|
||||
let Some(view) = app.sessions.get_mut(&id) else { return };
|
||||
let Some(view) = app.state.sessions.get_mut(&id) else { return };
|
||||
let own_client = view.state.own_client;
|
||||
let own = |m: &ChatMessage| crate::social::own_message(&own_uids, own_client, m);
|
||||
let index = view.current_tab;
|
||||
@@ -484,7 +483,7 @@ fn save_png(image: &SharedPixelBuffer<Rgba8Pixel>, path: &std::path::Path) -> Re
|
||||
/// channel, which asks for its password; `wrong` as if the server had
|
||||
/// refused one.
|
||||
fn open_channel_password(app: &mut App, wrong: bool) {
|
||||
let Some(session) = app.current else { return };
|
||||
let Some(session) = app.state.current else { return };
|
||||
let locked = app
|
||||
.view()
|
||||
.and_then(|v| v.presence.channels.values().filter(|c| c.has_password).map(|c| c.id).min());
|
||||
@@ -501,6 +500,26 @@ fn open_channel_password(app: &mut App, wrong: bool) {
|
||||
|
||||
const DEMO: i64 = 9001;
|
||||
|
||||
/// The software of the sample voice server, as a link reports it, and what
|
||||
/// that software can do (streams, files, offline messages).
|
||||
fn demo_teamspeak_6() -> (BackendInfo, Capabilities) {
|
||||
let backend = BackendInfo { product: "TeamSpeak 6".into(), version: "6.0.0-beta13.1".into() };
|
||||
let capabilities = Capabilities {
|
||||
streams: true,
|
||||
raw_query: false,
|
||||
ssh_query: true,
|
||||
http_query: true,
|
||||
file_transfer: true,
|
||||
offline_messages: true,
|
||||
};
|
||||
(backend, capabilities)
|
||||
}
|
||||
|
||||
/// The software of the sample server seen through a gateway.
|
||||
fn demo_teamspeak_3() -> BackendInfo {
|
||||
BackendInfo { product: "TeamSpeak 3".into(), version: "3.13.8".into() }
|
||||
}
|
||||
|
||||
fn channel(id: u64, parent: u64, order: u64, name: &str) -> ChannelInfo {
|
||||
ChannelInfo { id, parent, order, name: name.into(), ..Default::default() }
|
||||
}
|
||||
@@ -530,7 +549,7 @@ fn demo_ui(app: &mut App) {
|
||||
client_version: None,
|
||||
cached_server_icon: None,
|
||||
};
|
||||
app.bookmarks = vec![
|
||||
app.state.bookmarks = vec![
|
||||
Bookmark {
|
||||
gateway_url: Some("wss://gw.nightfall.example/v1".into()),
|
||||
..bookmark(DEMO, "Nightfall Guild", "ts.nightfall.example:9987")
|
||||
@@ -540,12 +559,12 @@ fn demo_ui(app: &mut App) {
|
||||
];
|
||||
// Home's "Continue where you left off": a channel of a server without
|
||||
// voice, so it shows Join.
|
||||
app.settings.last_voice = Some(LastVoice {
|
||||
app.state.settings.last_voice = Some(LastVoice {
|
||||
bookmark: DEMO + 1,
|
||||
address: "pixel.example".into(),
|
||||
channel: vec!["Art Corner".into()],
|
||||
});
|
||||
app.current = Some(DEMO);
|
||||
app.state.current = Some(DEMO);
|
||||
let session = DEMO as u64;
|
||||
|
||||
let mut p = Presence { server_name: "Nightfall Guild".into(), ..Default::default() };
|
||||
@@ -641,10 +660,9 @@ fn demo_ui(app: &mut App) {
|
||||
sort_id,
|
||||
..Default::default()
|
||||
};
|
||||
let flavor = ServerFlavor::from_version_string("6.0.0-beta13.1 [Build: 1]");
|
||||
let capabilities = flavor.capabilities();
|
||||
let (backend, capabilities) = demo_teamspeak_6();
|
||||
let events = [
|
||||
Event::ServerInfo { session, name: "Nightfall Guild".into(), flavor, capabilities },
|
||||
Event::ServerInfo { session, name: "Nightfall Guild".into(), backend, capabilities },
|
||||
Event::Groups {
|
||||
session,
|
||||
server_groups: Arc::new(vec![
|
||||
@@ -695,7 +713,7 @@ fn demo_ui(app: &mut App) {
|
||||
session,
|
||||
streams: vec![StreamInfo {
|
||||
id: "demo-stream".into(),
|
||||
streamer: tsclientlib::ClientId(2),
|
||||
streamer: 2,
|
||||
name: "Exploring the Lands Between".into(),
|
||||
kind: StreamKind::Screen,
|
||||
bitrate: 8000,
|
||||
@@ -756,7 +774,7 @@ fn demo_social(app: &mut App) {
|
||||
app.handle_event(Event::ServerInfo {
|
||||
session: session + 1,
|
||||
name: "Pixel Lounge".into(),
|
||||
flavor: ServerFlavor::from_version_string("3.13.8 [Build: 1]"),
|
||||
backend: demo_teamspeak_3(),
|
||||
capabilities: Default::default(),
|
||||
});
|
||||
|
||||
@@ -922,7 +940,7 @@ fn demo_social(app: &mut App) {
|
||||
// The samples came one by one, as new ones do: all are read (no "New"
|
||||
// line, which a gateway page on screen gets), but for Mira's and
|
||||
// Lumen's messages, which came while away.
|
||||
for view in app.sessions.values_mut() {
|
||||
for view in app.state.sessions.values_mut() {
|
||||
for tab in &mut view.tabs {
|
||||
tab.divider = None;
|
||||
tab.catch_up();
|
||||
@@ -965,7 +983,7 @@ fn demo_social(app: &mut App) {
|
||||
});
|
||||
|
||||
// The pictures of the links, as if downloaded.
|
||||
if let Some(view) = app.sessions.get_mut(&DEMO) {
|
||||
if let Some(view) = app.state.sessions.get_mut(&DEMO) {
|
||||
for (channel, name) in
|
||||
[(2, "night-castle.png"), (2, "guild-banner.png"), (2, "map-notes.png")]
|
||||
{
|
||||
@@ -977,7 +995,7 @@ fn demo_social(app: &mut App) {
|
||||
};
|
||||
view.extra.previews.insert(
|
||||
crate::previews::link_key(&file),
|
||||
crate::previews::Preview::Ready(voelin_core::Bytes(
|
||||
crate::vm::state::Preview::Ready(voelin_core::Bytes(
|
||||
demo_picture(640, 360, name.len() as u32).into(),
|
||||
)),
|
||||
);
|
||||
@@ -1176,15 +1194,12 @@ fn demo_social(app: &mut App) {
|
||||
clip: name.contains("clip"),
|
||||
path: format!("/tmp/{name}").into(),
|
||||
};
|
||||
crate::vm::list::sync(
|
||||
&app.models.social.recordings,
|
||||
&[
|
||||
recording("raid-night-2026-10-02.webm", "1.2 GB · 2 Oct 22:41"),
|
||||
recording("clip-boss-down.mkv", "38.4 MB · 2 Oct 21:57"),
|
||||
recording("lands-between-stream.mkv", "2.8 GB · 28 Sep 20:12"),
|
||||
recording("clip-lucky-parry.mkv", "12.1 MB · 28 Sep 19:40"),
|
||||
],
|
||||
);
|
||||
app.models.social.recordings.sync(&[
|
||||
recording("raid-night-2026-10-02.webm", "1.2 GB · 2 Oct 22:41"),
|
||||
recording("clip-boss-down.mkv", "38.4 MB · 2 Oct 21:57"),
|
||||
recording("lands-between-stream.mkv", "2.8 GB · 28 Sep 20:12"),
|
||||
recording("clip-lucky-parry.mkv", "12.1 MB · 28 Sep 19:40"),
|
||||
]);
|
||||
app.refresh_chats();
|
||||
app.refresh_people();
|
||||
app.refresh_home();
|
||||
@@ -1227,7 +1242,7 @@ fn demo_pictures(app: &mut App) {
|
||||
};
|
||||
let mut events = vec![Event::ServerDetails {
|
||||
session,
|
||||
address: app.bookmarks.iter().find(|b| b.id == DEMO).unwrap().address.clone(),
|
||||
address: app.state.bookmarks.iter().find(|b| b.id == DEMO).unwrap().address.clone(),
|
||||
details: Arc::new(voelin_model::ServerDetails {
|
||||
icon: DEMO_SERVER_ICON,
|
||||
..Default::default()
|
||||
@@ -1619,9 +1634,8 @@ fn demo_chat(app: &mut App, session: u64) {
|
||||
None,
|
||||
),
|
||||
];
|
||||
let mut id = 1;
|
||||
let mut pinned: Vec<HistoryMessage> = Vec::new();
|
||||
for (chat, author, client, text, ago, relay, reactions, pin, topic) in lines {
|
||||
for (id, (chat, author, client, text, ago, relay, reactions, pin, topic)) in (1..).zip(lines) {
|
||||
let target = if chat == DEMO { ChatTarget::Channel(2) } else { ChatTarget::Server };
|
||||
let message = HistoryMessage {
|
||||
id,
|
||||
@@ -1652,7 +1666,6 @@ fn demo_chat(app: &mut App, session: u64) {
|
||||
source: HistorySource::Gateway,
|
||||
complete: false,
|
||||
});
|
||||
id += 1;
|
||||
}
|
||||
// A server chat besides the channel chat.
|
||||
app.handle_event(Event::ChatHistory {
|
||||
@@ -1893,6 +1906,22 @@ pub(crate) fn answer_older(session: i64, target: ChatTarget, oldest: Option<Hist
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// The sample servers say what they run, as they did when the engine told
|
||||
/// a flavor: the home page's chip reads the product, the status line the
|
||||
/// product and version, and the sample voice server keeps the
|
||||
/// capabilities of a TeamSpeak 6 server (its streams).
|
||||
#[test]
|
||||
fn demo_servers_name_their_software() {
|
||||
let (backend, capabilities) = demo_teamspeak_6();
|
||||
assert_eq!(backend.product, "TeamSpeak 6");
|
||||
assert_eq!(backend.label(), "TeamSpeak 6 6.0.0-beta13.1");
|
||||
let flavor = voelin_model::ServerFlavor::from_version_string("6.0.0-beta13.1 [Build: 1]");
|
||||
assert_eq!(capabilities, flavor.capabilities());
|
||||
let backend = demo_teamspeak_3();
|
||||
assert_eq!(backend.product, "TeamSpeak 3");
|
||||
assert_eq!(backend.label(), "TeamSpeak 3 3.13.8");
|
||||
}
|
||||
|
||||
/// Two pages back from the sample chat's first message, each older than
|
||||
/// the one before, the second one the last.
|
||||
#[test]
|
||||
|
||||
@@ -3,13 +3,16 @@
|
||||
//! home page), our permissions there, its configuration (gateway
|
||||
//! administration). The pins, reactions and topics are in `chat.rs`.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use slint::{ComponentHandle, SharedString};
|
||||
use voelin_core::{Command, GatewayRequest, GatewayUpdate};
|
||||
use voelin_gateway_proto::{Action, EventKind, EventQuery, EventSpec, RsvpStatus, feature};
|
||||
|
||||
use crate::app::{App, Bridge, EventForm, EventItem};
|
||||
use crate::app::{App, Bridge};
|
||||
use crate::social::{NoticeKind, NoticeTarget, now_ms};
|
||||
use crate::vm;
|
||||
use crate::vm::bridge::{EventForm, EventItem};
|
||||
use crate::vm::social::{date_block, event_when, format_local, parse_local, soon};
|
||||
|
||||
impl App {
|
||||
@@ -26,7 +29,7 @@ impl App {
|
||||
use GatewayUpdate as U;
|
||||
let mut ask: Vec<GatewayRequest> = Vec::new();
|
||||
let mut remind = None;
|
||||
let extra = &mut self.sessions.entry(id).or_default().extra;
|
||||
let extra = &mut self.state.sessions.entry(id).or_default().extra;
|
||||
match update {
|
||||
U::Connected { uid, capabilities, .. } => {
|
||||
extra.gateway_uid = Some(uid.clone());
|
||||
@@ -118,8 +121,8 @@ impl App {
|
||||
|
||||
/// The events page of the current server was opened.
|
||||
pub(crate) fn open_events(&mut self) {
|
||||
let Some(id) = self.current else { return };
|
||||
let loaded = self.sessions.get(&id).is_some_and(|v| v.extra.events_loaded);
|
||||
let Some(id) = self.state.current else { return };
|
||||
let loaded = self.state.sessions.get(&id).is_some_and(|v| v.extra.events_loaded);
|
||||
if !loaded {
|
||||
self.gateway_to(id, GatewayRequest::Events { query: EventQuery::default() });
|
||||
}
|
||||
@@ -205,41 +208,40 @@ impl App {
|
||||
editable: moderate
|
||||
|| extra.gateway_uid.as_deref() == Some(e.creator.uid.as_str()),
|
||||
soon: soon(e.spec.start_ms, e.spec.end_ms, now).into(),
|
||||
attendees: crate::app::model(
|
||||
e.attendees
|
||||
.iter()
|
||||
.map(|a| {
|
||||
let status = match a.status {
|
||||
RsvpStatus::Going => "going",
|
||||
RsvpStatus::Maybe => "maybe",
|
||||
RsvpStatus::NotGoing => "not going",
|
||||
RsvpStatus::Unknown => "?",
|
||||
};
|
||||
SharedString::from(format!("{} ({status})", a.user.name))
|
||||
})
|
||||
.collect(),
|
||||
),
|
||||
attendees: e
|
||||
.attendees
|
||||
.iter()
|
||||
.map(|a| {
|
||||
let status = match a.status {
|
||||
RsvpStatus::Going => "going",
|
||||
RsvpStatus::Maybe => "maybe",
|
||||
RsvpStatus::NotGoing => "not going",
|
||||
RsvpStatus::Unknown => "?",
|
||||
};
|
||||
Arc::<str>::from(format!("{} ({status})", a.user.name))
|
||||
})
|
||||
.collect(),
|
||||
expanded: extra.expanded.contains(&e.id),
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
vm::list::sync(&self.models.social.events, &items);
|
||||
self.models.social.events.sync(&items);
|
||||
}
|
||||
|
||||
/// Answer an event ("" withdraws the answer).
|
||||
pub(crate) fn rsvp(&mut self, event_id: i32, status: &str) {
|
||||
let Some(id) = self.current else { return };
|
||||
let Some(id) = self.state.current else { return };
|
||||
let status = (!status.is_empty()).then(|| RsvpStatus::parse(status));
|
||||
self.gateway_to(id, GatewayRequest::Rsvp { event_id: i64::from(event_id), status });
|
||||
}
|
||||
|
||||
/// Show or hide who answered (fetching the event with its attendees).
|
||||
pub(crate) fn toggle_event(&mut self, event_id: i32) {
|
||||
let Some(id) = self.current else { return };
|
||||
let Some(id) = self.state.current else { return };
|
||||
let event_id = i64::from(event_id);
|
||||
let view = self.sessions.entry(id).or_default();
|
||||
let view = self.state.sessions.entry(id).or_default();
|
||||
if !view.extra.expanded.remove(&event_id) {
|
||||
view.extra.expanded.insert(event_id);
|
||||
self.gateway_to(id, GatewayRequest::GetEvent { id: event_id });
|
||||
@@ -275,7 +277,7 @@ impl App {
|
||||
|
||||
/// Create or change an event; the reason when the form is not right.
|
||||
pub(crate) fn save_event(&mut self, form: &EventForm) -> String {
|
||||
let Some(id) = self.current else { return "No server selected.".into() };
|
||||
let Some(id) = self.state.current else { return "No server selected.".into() };
|
||||
let Some(start_ms) = parse_local(&form.start) else {
|
||||
return "Write the start as YYYY-MM-DD HH:MM.".into();
|
||||
};
|
||||
@@ -289,7 +291,7 @@ impl App {
|
||||
}
|
||||
};
|
||||
let channels = self.event_channels();
|
||||
let text = |s: &slint::SharedString| Some(s.to_string()).filter(|s| !s.trim().is_empty());
|
||||
let text = |s: &Arc<str>| Some(s.to_string()).filter(|s| !s.trim().is_empty());
|
||||
let spec = EventSpec {
|
||||
title: form.title.trim().to_owned(),
|
||||
description: form.description.to_string(),
|
||||
@@ -313,14 +315,14 @@ impl App {
|
||||
}
|
||||
|
||||
pub(crate) fn delete_event(&mut self, event_id: i32) {
|
||||
if let Some(id) = self.current {
|
||||
if let Some(id) = self.state.current {
|
||||
self.gateway_to(id, GatewayRequest::DeleteEvent { id: i64::from(event_id) });
|
||||
}
|
||||
}
|
||||
|
||||
/// Watch the stream of a live scheduled stream.
|
||||
pub(crate) fn watch_event(&mut self, event_id: i32) {
|
||||
let Some(id) = self.current else { return };
|
||||
let Some(id) = self.state.current else { return };
|
||||
let stream = self
|
||||
.view()
|
||||
.and_then(|v| v.extra.events.iter().find(|e| e.id == i64::from(event_id)))
|
||||
|
||||
@@ -9,11 +9,10 @@ use std::path::{Path, PathBuf};
|
||||
use slint::ComponentHandle;
|
||||
use voelin_core::VoiceState;
|
||||
|
||||
use crate::app::{
|
||||
App, Bridge, HappeningItem, LiveItem, Page, RecordingItem, ResumeItem, ServerItem,
|
||||
};
|
||||
use crate::app::{App, Bridge, Page};
|
||||
use crate::settings::LastVoice;
|
||||
use crate::vm;
|
||||
use crate::vm::bridge::{HappeningItem, LiveItem, RecordingItem, ResumeItem, ServerItem};
|
||||
use crate::vm::home::ResumeAction;
|
||||
use crate::vm::social::{event_when, plain};
|
||||
|
||||
@@ -30,8 +29,10 @@ impl App {
|
||||
/// streaming.
|
||||
fn live_rooms(&self) -> Vec<LiveItem> {
|
||||
let mut rooms = Vec::new();
|
||||
for (b, backdrop) in self.bookmarks.iter().zip(vm::servers::tints(&self.bookmarks)) {
|
||||
let Some(view) = self.sessions.get(&b.id) else { continue };
|
||||
for (b, backdrop) in
|
||||
self.state.bookmarks.iter().zip(vm::servers::tints(&self.state.bookmarks))
|
||||
{
|
||||
let Some(view) = self.state.sessions.get(&b.id) else { continue };
|
||||
let channel_of = |cid: Option<u64>| {
|
||||
cid.and_then(|c| view.presence.channels.get(&c))
|
||||
.map(|c| vm::tree::channel_title(c).0.to_owned())
|
||||
@@ -45,7 +46,7 @@ impl App {
|
||||
let avatar = match (client, uid) {
|
||||
(Some(c), _) if view.avatar(c).is_some() => vm::avatar::image(view.avatar(c)),
|
||||
(_, Some(uid)) => self.avatar_of(uid),
|
||||
_ => slint::Image::default(),
|
||||
_ => vm::ImageRef::default(),
|
||||
};
|
||||
LiveItem {
|
||||
session: b.id as i32,
|
||||
@@ -63,15 +64,15 @@ impl App {
|
||||
let mut covered: Vec<u16> = Vec::new();
|
||||
if view.streams_available() {
|
||||
for s in &view.streams {
|
||||
let name = view.nickname(s.streamer.0);
|
||||
let name = view.nickname(s.streamer);
|
||||
let title =
|
||||
if s.name.is_empty() { format!("{name}'s stream") } else { s.name.clone() };
|
||||
let mut room = item(s.id.clone(), title, Some(s.streamer.0), None, name);
|
||||
room.channel = channel_of(view.channel_of(s.streamer.0)).into();
|
||||
let mut room = item(s.id.clone(), title, Some(s.streamer), None, name);
|
||||
room.channel = channel_of(view.channel_of(s.streamer)).into();
|
||||
room.viewers = view.stream_viewers.get(&s.id).map_or(0, |v| *v as i32);
|
||||
room.kind = vm::streams::kind_label(&s.kind).into();
|
||||
room.watchable = view.state.own_client != Some(s.streamer.0);
|
||||
covered.push(s.streamer.0);
|
||||
room.watchable = view.state.own_client != Some(s.streamer);
|
||||
covered.push(s.streamer);
|
||||
rooms.push(room);
|
||||
}
|
||||
}
|
||||
@@ -124,8 +125,8 @@ impl App {
|
||||
let now = crate::social::now_ms();
|
||||
let mut events: Vec<(i64, HappeningItem, Happening)> = Vec::new();
|
||||
let mut news = Vec::new();
|
||||
for b in &self.bookmarks {
|
||||
let Some(view) = self.sessions.get(&b.id) else { continue };
|
||||
for b in &self.state.bookmarks {
|
||||
let Some(view) = self.state.sessions.get(&b.id) else { continue };
|
||||
for e in &view.extra.events {
|
||||
let ends = e.spec.end_ms.unwrap_or(e.spec.start_ms + 3 * 3_600_000);
|
||||
if ends < now {
|
||||
@@ -184,16 +185,16 @@ impl App {
|
||||
/// `refresh_chats`).
|
||||
pub(crate) fn refresh_home(&self) {
|
||||
let m = &self.models.social;
|
||||
vm::list::sync(&m.live, &self.live_rooms());
|
||||
m.live.sync(&self.live_rooms());
|
||||
let items: Vec<HappeningItem> = self.happenings().into_iter().map(|(i, _)| i).collect();
|
||||
vm::list::sync(&m.happenings, &items);
|
||||
m.happenings.sync(&items);
|
||||
}
|
||||
|
||||
/// A live room's card: watch it at once in our channel, else go to its
|
||||
/// server (and the streamer's channel, watching once there).
|
||||
pub(crate) fn watch_live(&mut self, session: i64, id: &str) {
|
||||
self.show_server(session);
|
||||
let Some(view) = self.sessions.get(&session) else { return };
|
||||
let Some(view) = self.state.sessions.get(&session) else { return };
|
||||
if view.streams_available() && view.streams.iter().any(|s| s.id == id) {
|
||||
self.watch_stream(id.to_owned());
|
||||
return;
|
||||
@@ -233,8 +234,9 @@ impl App {
|
||||
}
|
||||
|
||||
fn last_resume(&self) -> Option<vm::home::Resume> {
|
||||
let voice = |id| self.sessions.get(&id).map_or(VoiceState::Disconnected, |v| v.state.voice);
|
||||
vm::home::resume(self.settings.last_voice.as_ref(), &self.bookmarks, voice)
|
||||
let voice =
|
||||
|id| self.state.sessions.get(&id).map_or(VoiceState::Disconnected, |v| v.state.voice);
|
||||
vm::home::resume(self.state.settings.last_voice.as_ref(), &self.state.bookmarks, voice)
|
||||
}
|
||||
|
||||
/// Home's "Continue where you left off", its server as the rail shows
|
||||
@@ -253,7 +255,7 @@ impl App {
|
||||
icon: server.icon.clone(),
|
||||
channel: resume.title().into(),
|
||||
open: resume.action == ResumeAction::Open,
|
||||
connecting: server.status == "connecting",
|
||||
connecting: &*server.status == "connecting",
|
||||
}
|
||||
}
|
||||
|
||||
@@ -273,17 +275,17 @@ impl App {
|
||||
if self.demo_ui {
|
||||
return false;
|
||||
}
|
||||
let Some(view) = self.sessions.get(&session) else { return false };
|
||||
let Some(view) = self.state.sessions.get(&session) else { return false };
|
||||
let (VoiceState::Connected, Some(cid)) = (view.state.voice, view.state.own_channel) else {
|
||||
return false;
|
||||
};
|
||||
let channel = vm::tree::channel_path(&view.presence, cid);
|
||||
let Some(b) = self.bookmark(session).filter(|_| !channel.is_empty()) else { return false };
|
||||
let last = LastVoice { bookmark: session, address: b.address.clone(), channel };
|
||||
if self.settings.last_voice.as_ref() == Some(&last) {
|
||||
if self.state.settings.last_voice.as_ref() == Some(&last) {
|
||||
return false;
|
||||
}
|
||||
self.settings.last_voice = Some(last);
|
||||
self.state.settings.last_voice = Some(last);
|
||||
self.store_settings();
|
||||
true
|
||||
}
|
||||
@@ -304,7 +306,7 @@ impl App {
|
||||
}
|
||||
let dir = self.recordings_dir();
|
||||
let items = recordings_in(&dir);
|
||||
vm::list::sync(&self.models.social.recordings, &items);
|
||||
self.models.social.recordings.sync(&items);
|
||||
if let Some(ui) = self.ui.upgrade() {
|
||||
ui.global::<Bridge>().set_recordings_dir(dir.display().to_string().into());
|
||||
}
|
||||
|
||||
@@ -2,23 +2,13 @@
|
||||
//! `Store::default_identity`), chosen under Settings → Profiles, and the
|
||||
//! import of the official clients' identities on start
|
||||
//! (`voelin_core::identity::import_new`, app.rs). The rest of the Profiles
|
||||
//! page is in `settings_pages.rs`.
|
||||
//! page is in `settings_pages/`.
|
||||
|
||||
use tracing::warn;
|
||||
use voelin_core::settings::IDENTITY_IMPORT;
|
||||
use voelin_store::IdentityOrigin;
|
||||
|
||||
use crate::app::App;
|
||||
|
||||
/// Where an identity came from, as Profiles says it.
|
||||
pub(crate) fn origin_label(origin: IdentityOrigin) -> &'static str {
|
||||
match origin {
|
||||
IdentityOrigin::Created => "Made in Voelin",
|
||||
IdentityOrigin::Imported => "Imported",
|
||||
IdentityOrigin::User => "Chosen by you",
|
||||
}
|
||||
}
|
||||
|
||||
impl App {
|
||||
/// The user's choice of the identity servers see us as, from the next
|
||||
/// connection on; no import replaces it.
|
||||
@@ -51,16 +41,3 @@ impl App {
|
||||
self.refresh_identities();
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn rows_say_where_an_identity_came_from() {
|
||||
assert_eq!(origin_label(IdentityOrigin::Created), "Made in Voelin");
|
||||
assert_eq!(origin_label(IdentityOrigin::Imported), "Imported");
|
||||
// Made by the app, then chosen: an import never replaces it.
|
||||
assert_eq!(origin_label(IdentityOrigin::User), "Chosen by you");
|
||||
}
|
||||
}
|
||||
@@ -65,8 +65,8 @@ pub(crate) fn take() {
|
||||
|
||||
impl App {
|
||||
fn share(&mut self, nav: &Nav<'_>, text: Option<String>, files: Vec<PathBuf>) {
|
||||
let current = self.current.and_then(|id| {
|
||||
let view = self.sessions.get(&id)?;
|
||||
let current = self.state.current.and_then(|id| {
|
||||
let view = self.state.sessions.get(&id)?;
|
||||
let tab = &view.tabs[view.current_tab];
|
||||
// Files go to the channel of the chat, else to ours.
|
||||
let channel = match tab.target {
|
||||
|
||||
@@ -6,7 +6,6 @@ mod bind;
|
||||
mod camera;
|
||||
mod chat;
|
||||
mod dev;
|
||||
mod emoji;
|
||||
mod events;
|
||||
mod home;
|
||||
mod hotkey;
|
||||
@@ -19,14 +18,15 @@ mod messages;
|
||||
mod popout;
|
||||
mod previews;
|
||||
mod servers;
|
||||
mod settings;
|
||||
mod settings_page;
|
||||
mod settings_pages;
|
||||
mod social;
|
||||
mod streams;
|
||||
mod studio;
|
||||
mod video;
|
||||
mod vm;
|
||||
|
||||
// The view models live in their own crate; the modules keep their old paths.
|
||||
use voelin_ui_vm::{self as vm, emoji, settings};
|
||||
|
||||
pub use app::{HostedEngine, RunOptions, run};
|
||||
pub use inbox::{Request, request};
|
||||
@@ -29,9 +29,14 @@ impl App {
|
||||
}
|
||||
};
|
||||
let in_voice = |id: i64| {
|
||||
self.sessions.get(&id).is_some_and(|v| v.state.voice == VoiceState::Connected)
|
||||
self.state.sessions.get(&id).is_some_and(|v| v.state.voice == VoiceState::Connected)
|
||||
};
|
||||
match vm::servers::link_server(&self.bookmarks, &link.address(), self.current, in_voice) {
|
||||
match vm::servers::link_server(
|
||||
&self.state.bookmarks,
|
||||
&link.address(),
|
||||
self.state.current,
|
||||
in_voice,
|
||||
) {
|
||||
Some((id, true)) => self.move_by_link(id, &link),
|
||||
saved => self.open_link_form(saved.map(|(id, _)| id), &link),
|
||||
}
|
||||
@@ -41,7 +46,7 @@ impl App {
|
||||
fn move_by_link(&mut self, session: i64, link: &ServerLink) {
|
||||
self.show_server(session);
|
||||
let Some(path) = &link.channel else { return };
|
||||
let Some(view) = self.sessions.get_mut(&session) else { return };
|
||||
let Some(view) = self.state.sessions.get_mut(&session) else { return };
|
||||
let Some(channel) = vm::servers::channel_by_path(&view.presence, path) else {
|
||||
let server = self.bookmark(session).map(|b| b.name.clone()).unwrap_or_default();
|
||||
self.set_status(format!("{server} has no channel \u{201c}{path}\u{201d}"));
|
||||
@@ -64,7 +69,7 @@ impl App {
|
||||
let form = vm::servers::link_form(link, form, &self.default_nickname());
|
||||
let Some(ui) = self.ui.upgrade() else { return };
|
||||
let nav = ui.global::<Nav>();
|
||||
nav.set_bookmark_form(form);
|
||||
nav.set_bookmark_form(form.into());
|
||||
nav.set_bookmark_open(true);
|
||||
}
|
||||
}
|
||||
@@ -2,12 +2,15 @@
|
||||
//! (private chat, poke, contacts, per-client volume). The rows themselves
|
||||
//! are built in `vm::tree::members`.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use slint::ComponentHandle;
|
||||
use voelin_core::{Command, Contact, Relation};
|
||||
|
||||
use crate::app::{App, Bridge, MemberCard, Nav};
|
||||
use crate::app::{App, Bridge, Nav};
|
||||
use crate::settings::ClientPlayback;
|
||||
use crate::vm;
|
||||
use crate::vm::bridge::MemberCard;
|
||||
|
||||
impl App {
|
||||
/// `VOELIN_OPEN=member`: the card of the first person that is not us.
|
||||
@@ -43,10 +46,13 @@ impl App {
|
||||
let id = view.member_card?;
|
||||
let client = view.presence.clients.get(&id)?;
|
||||
let uid = client.uid.clone();
|
||||
let contact = uid.as_ref().and_then(|u| self.contacts.get(u));
|
||||
let playback =
|
||||
uid.as_ref().and_then(|u| self.playback.get(u)).copied().unwrap_or_default();
|
||||
let groups: Vec<slint::SharedString> = client
|
||||
let contact = uid.as_ref().and_then(|u| self.state.contacts.get(u));
|
||||
let playback = uid
|
||||
.as_ref()
|
||||
.and_then(|u| self.state.playback.get(u))
|
||||
.copied()
|
||||
.unwrap_or_default();
|
||||
let groups: Vec<Arc<str>> = client
|
||||
.server_groups
|
||||
.iter()
|
||||
.filter_map(|g| view.server_groups.iter().find(|i| i.id == *g))
|
||||
@@ -62,8 +68,8 @@ impl App {
|
||||
avatar: vm::avatar::image(view.avatar(id)),
|
||||
status: vm::tree::status_of(client, view.talking.contains(&id)).into(),
|
||||
description: client.description.clone().unwrap_or_default().into(),
|
||||
groups: crate::app::model(groups),
|
||||
badges: crate::app::model(badges),
|
||||
groups,
|
||||
badges,
|
||||
country: client.country.clone().unwrap_or_default().into(),
|
||||
talk_power: client.talk_power,
|
||||
friend: contact.is_some_and(|c| c.relation == Relation::Friend),
|
||||
@@ -75,13 +81,13 @@ impl App {
|
||||
})
|
||||
})
|
||||
.unwrap_or_default();
|
||||
bridge.set_member_card(card);
|
||||
bridge.set_member_card(card.into());
|
||||
}
|
||||
|
||||
/// The card's buttons: "message", "poke", "friend", "blocked", "mute".
|
||||
pub(crate) fn member_action(&mut self, action: &str) {
|
||||
let Some(id) = self.current else { return };
|
||||
let Some(view) = self.sessions.get(&id) else { return };
|
||||
let Some(id) = self.state.current else { return };
|
||||
let Some(view) = self.state.sessions.get(&id) else { return };
|
||||
let Some(client) = view.member_card.and_then(|c| view.presence.clients.get(&c)) else {
|
||||
return;
|
||||
};
|
||||
@@ -102,18 +108,22 @@ impl App {
|
||||
"friend" | "blocked" => {
|
||||
let Some(uid) = uid else { return };
|
||||
let wanted = if action == "friend" { Relation::Friend } else { Relation::Blocked };
|
||||
let current = self.contacts.get(&uid).map(|c| c.relation);
|
||||
let mut contact =
|
||||
self.contacts.get(&uid).cloned().unwrap_or_else(|| Contact::new(uid.clone()));
|
||||
let current = self.state.contacts.get(&uid).map(|c| c.relation);
|
||||
let mut contact = self
|
||||
.state
|
||||
.contacts
|
||||
.get(&uid)
|
||||
.cloned()
|
||||
.unwrap_or_else(|| Contact::new(uid.clone()));
|
||||
contact.nickname = nickname;
|
||||
contact.relation = if current == Some(wanted) { Relation::Neutral } else { wanted };
|
||||
self.contacts.insert(uid, contact.clone());
|
||||
self.state.contacts.insert(uid, contact.clone());
|
||||
self.engine.send(Command::SetContact { contact: Box::new(contact) });
|
||||
self.refresh_member_card();
|
||||
}
|
||||
"mute" => {
|
||||
let Some(uid) = uid else { return };
|
||||
let mut playback = self.playback.get(&uid).copied().unwrap_or_default();
|
||||
let mut playback = self.state.playback.get(&uid).copied().unwrap_or_default();
|
||||
playback.muted = !playback.muted;
|
||||
self.set_playback(&uid, client_id, playback);
|
||||
}
|
||||
@@ -123,9 +133,9 @@ impl App {
|
||||
|
||||
/// Open the poke dialog for a client (the member card, a contact).
|
||||
pub(crate) fn ask_poke(&mut self, session: i64, client: u16) {
|
||||
let Some(view) = self.sessions.get(&session) else { return };
|
||||
let Some(view) = self.state.sessions.get(&session) else { return };
|
||||
let name = view.nickname(client);
|
||||
self.poke_target = Some((session, client, name.clone()));
|
||||
self.state.poke_target = Some((session, client, name.clone()));
|
||||
let Some(ui) = self.ui.upgrade() else { return };
|
||||
let nav = ui.global::<Nav>();
|
||||
nav.set_poke_name(name.into());
|
||||
@@ -134,7 +144,7 @@ impl App {
|
||||
|
||||
/// The poke dialog's Send, with its message (may be empty).
|
||||
pub(crate) fn send_poke(&mut self, text: &str) {
|
||||
let Some((session, client, name)) = self.poke_target.take() else { return };
|
||||
let Some((session, client, name)) = self.state.poke_target.take() else { return };
|
||||
if !self.demo_ui {
|
||||
self.engine.send(Command::Poke {
|
||||
session: session as u64,
|
||||
@@ -152,7 +162,7 @@ impl App {
|
||||
return;
|
||||
};
|
||||
let (client_id, Some(uid)) = (client.id, client.uid.clone()) else { return };
|
||||
let mut playback = self.playback.get(&uid).copied().unwrap_or_default();
|
||||
let mut playback = self.state.playback.get(&uid).copied().unwrap_or_default();
|
||||
playback.volume = (percent / 100.0).clamp(0.0, 4.0);
|
||||
self.set_playback(&uid, client_id, playback);
|
||||
}
|
||||
@@ -160,11 +170,13 @@ impl App {
|
||||
/// Store one client's playback and apply it to the session.
|
||||
fn set_playback(&mut self, uid: &str, client: u16, playback: ClientPlayback) {
|
||||
if playback.is_default() {
|
||||
self.playback.remove(uid);
|
||||
self.state.playback.remove(uid);
|
||||
} else {
|
||||
self.playback.insert(uid.to_owned(), playback);
|
||||
self.state.playback.insert(uid.to_owned(), playback);
|
||||
}
|
||||
if let Err(e) = self.prefs.set(&crate::settings::CLIENT_PLAYBACK, self.playback.clone()) {
|
||||
if let Err(e) =
|
||||
self.prefs.set(&crate::settings::CLIENT_PLAYBACK, self.state.playback.clone())
|
||||
{
|
||||
tracing::warn!(%e, "could not store client volumes");
|
||||
}
|
||||
self.command(|session| Command::SetClientMuted { session, client, muted: playback.muted });
|
||||
|
||||
Loaded 100 of 134 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user